{"docstore/metadata": {"87e184ca-9a81-4558-ae8b-60c96e312094": {"doc_hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7"}, "e0e6979e-8a6a-4c5f-b82e-5186805f23e5": {"doc_hash": "592359f7fd1879cd2a559e9f0729446fb7e8e9adccdcf3397cb01d4ff594e44c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d65d4d81-9002-465f-8c7d-920c2b9f81db": {"doc_hash": "f4f653753036a2756502d61822c83c79407f796b3f9df0105b9f7bc8f3d377db", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9828bafc-474d-4158-8726-abeef5a5924c": {"doc_hash": "74faaa3c902833306ea64c2a49b87f8e25d932bb97b110ebb6bce877bd2353bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d9aee546-43f1-4309-8c76-361455b0f096": {"doc_hash": "08fdb894a8287aa0b8c6d5db4bd069e2c1868df545a87cd9b3b224bf9eef46cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "55918571-ab4c-4d7e-a944-fc0274e1922f": {"doc_hash": "56f403c27ec526298850cfefad94fd9a2c84a7248a2ae1ede44321dd55313209", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e2b42c71-346f-4308-a90f-bc4cc7f113c7": {"doc_hash": "d5f6a38f54543b4ad3dfa616e3a03630f65af2a483a70abbb7e5a6e33f7d0f2a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "29fac197-b5a5-4a95-a5d5-0796081c45ca": {"doc_hash": "46afd2fe19565b2adcbb8addc95115013bc75d2429148042730573109fbe1961", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c249a192-586e-4261-94d2-639cdae37e12": {"doc_hash": "d4a8aeba65f30e5e9202f91e55adbc4910f91b04dba8186fed20865930b47012", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "df45b317-8fbb-434f-bae7-2ff4234217ce": {"doc_hash": "ea1d4bbc785d5dae010cf38dae4a8f0f114b3eb6d2b5152e43e5185ec6551c5d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4f057cc4-8680-4708-816c-ff7c92e8f032": {"doc_hash": "667e2b2f49aac205c0e22c65109ed9e017ce1c7b414915af95335b6d9a1079f7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c7974532-f799-4bd4-872e-602718275823": {"doc_hash": "86aa12f5fab696a7e1d7142e0b9cc2bbcd4dcdcb1074c42ec77a132736f97446", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "adc20649-cce2-4e46-acfc-47c7b5b8f21e": {"doc_hash": "971c3a36344b3d777921abbd307fff1904d15850582d68b251e29023aa7f9cbe", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ebc1d360-26a7-4392-9653-bf887a7543f6": {"doc_hash": "ae5e7153b1545f1f67b839627d52450f1c109e1865863408d5d9ad98f04e4b06", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8e40d97a-b776-484c-921b-1ae55f524854": {"doc_hash": "3398c1ecf6a030c9cf717eb74615ff108fe28f691d65edb32cff749e13b771af", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8889ad8a-fa7a-40c3-806e-7cac3cad03c4": {"doc_hash": "b91be1989a2da19e01da84acd72ac4f15eae87a7f2a50401480a75fd91a07f35", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "85c32ff5-b949-4689-ad89-3c0224ad4dd7": {"doc_hash": "25bbee0c032f5983cb6770305b5d2d8fb89eba48ff286f090a2e1e17e68f9f1e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e9f9fa2a-b624-475c-a19e-d09d8a160190": {"doc_hash": "62113e3edfbbdf02cf657509688ff4184dba7f6b04af2b84f9abc92e7e674d6b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e2a931cc-815d-4690-a2f2-428c2ac14fda": {"doc_hash": "87249e27325e4828958c9064334c6bbcb56f2525d5ca620253b958a73b554b61", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b80653b9-4e48-447c-86c0-2973bc925855": {"doc_hash": "b18fd919d4446ccd8057bb4f661a7eadccd8643c3e877e70ef850a0c635ab0ff", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71a3f8ff-3f46-4494-a96e-c91b6f73aa5f": {"doc_hash": "9f38fe8b128116bf42df1791087d2921d3808d9e70ab2ebc2803caa5bd2120bd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bae9f5ee-61a4-43d3-bb37-bbba9cddd932": {"doc_hash": "fb2368b79e4ad316a8176ec88efd75a4f3e28fff5ef27f3af28fc2ea9bef5694", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3a244935-fe9b-4da7-9ec2-47612fe7f853": {"doc_hash": "bf58a1c0e91aac192b56ad5f7fc7d689c3c2b813fb510ca4ab25a7e8fe5f08b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "89413d59-1d59-4f2b-bd2a-401f5d10a8b2": {"doc_hash": "a5b4a8581dbadd5e7c6beb069b106410237506b720a7e3d85fe9c31dca23fa67", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c0a129e3-b2c5-464c-a622-28b9260944f2": {"doc_hash": "5f04af87c8c6f463564e5feb4c40f76e01341f9bcefd1547a1e8f813b6efb9b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "58466317-2e44-4d07-b031-73f32f4bbf4f": {"doc_hash": "03377d2469d54e984a5612e4f5ca98710b2519bd740b07506c061a9d05110193", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "995591b5-a45a-4b9c-8e62-c2e7b5d22e8e": {"doc_hash": "9450eae3f1313904fd00fb5cc967f7989be91ad8800811efed6268d1748bb91f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c08e079c-16f8-4408-9b98-7c73c5c1e11e": {"doc_hash": "20ee2a8d448f9723d397e40b8d94afa0fc51de2c4d7ccb5b1766e969c4cb10eb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34160ac3-06ae-4c64-865e-51d0ce5baa9b": {"doc_hash": "d141c3e6321e69d0600b2589eebc7b2f5d5b92c3a9b3a58491fe4c0bd10ef129", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d610d334-8512-44a1-b56f-2cd0e9812770": {"doc_hash": "8367900273431f91de700c9ed217b7bbee9420e95aeff09949715328dbb2a98a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6af49c03-fe53-4a07-8dc1-0eeca6a3b8a1": {"doc_hash": "e516d274d12718cb263dce63de5163dae8649c8f28e606b85fa2b4564215c6d0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bbd5d7b3-370d-43a1-a4c8-d1a989086c54": {"doc_hash": "072a329a050ca07e649abe770ca9da91f534b7e232701d559c75285932f59030", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f29a4ce4-8fcc-450a-90a8-2d3f2749f4fe": {"doc_hash": "96ebf95436ff78860ebf5a82231e03444e44fb356910c43efac92190944316c5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1953ffbc-0101-4858-b2e1-8a814f4db175": {"doc_hash": "6c441ba51d28a6c898bb626efbeacba5116881f7780bfd91f436211969d1ad26", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e22cc0da-78fd-4a1f-a0ab-fa248ecd23b8": {"doc_hash": "52335ba03246cf10c2b0848d9f5a3ad175dd4a21ddf229bed3814effa64942e5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "efe826e9-93f4-4f80-a413-bb872c5518c9": {"doc_hash": "9e7f59a86ab758abaf331d55936a8e28c2a7986600a2d73715b2845144f59597", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "26b43b04-ad51-4609-aaa9-4a6dfd9b1bd2": {"doc_hash": "56f12f6989fff88148d5586ae951a9134b11013ae27d972ab31c0379ed05c663", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "027bfb21-0124-4507-bf52-95e0ffbb9065": {"doc_hash": "f6b93bfc8f2c068ac383e2344b40a436168ee118fb1c594830de3f78056aa3e1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c52facd1-5cd9-48af-a4dc-d57100d9b40d": {"doc_hash": "9eb0ae60ede95d2d36b8f458a9bc9574517924cc321b791843e142b058c4f976", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "65754c3a-cb69-408e-95a3-09e7c6b835d8": {"doc_hash": "086ed06685a626913df4d92ac1feb00c72b9b20c315148014a63ffee68e342e6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "955060b2-7811-4f18-a16e-64eb75b3866b": {"doc_hash": "0a1b452b69c112c7b2d0b0e57716aa90ed32205e236933b5ff37a832a4f406c8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "92d3eb9c-bc51-45a4-8c4d-c280c62d1094": {"doc_hash": "10ef977d4ade314adb74e38168701d9b5c08cc747b4d9dc7ce96d6c6d7aef5bd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "892ba326-42e2-428d-a59e-36c764161d29": {"doc_hash": "1b3b6f1e17cfa041947cbb8197d8d4140dfb41eaa30a8908e1ae4d9df0ad4aa9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e370cd1d-18af-49d3-afca-dde8cc7ce724": {"doc_hash": "875e1a7e969afd49f9f9e5eecd39ee7bc5d116303129cfa5c660205a8ef24e28", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6dc21dc4-2085-468e-925d-753b0bb9ac54": {"doc_hash": "b82174b831a90af1a1ef33ef65f74743ac257307944cc2485d2c7100da6798d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "496dabbe-134f-48b6-9dd8-34d78307e950": {"doc_hash": "a9550893caacc5aad4459585bccbb598ac0b6ad7f94cf525b299786352b3cf8b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8c24a722-b617-4bf6-8a44-558c94c99861": {"doc_hash": "a8745b0813bbcc4510f53946fcab119b8f99543b972849494f7b078fa29c7e87", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "41f8dc68-dabc-4c0e-b79b-5b2f849aa7f8": {"doc_hash": "90b3bf815e19b8b0d61eae7e2fb780585f1af2b165fee7414b10f9932f50d5be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "82999996-b9ff-470b-b563-bd397252c078": {"doc_hash": "d036043437cdba74b47af5c9c66726e7c31bd95d8e5f513ba4ee4adc19283d60", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc8c2054-8783-47d2-8fc5-eb7cf34276db": {"doc_hash": "024b3b64c4459248f8509bcffc6c8ac4a99019256a559c0a07196808254632b9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c94b42a5-99f6-49c7-91cd-d3c4d818ee95": {"doc_hash": "ee3216d5e6677f8f88cf9d95192d1b8833942e7108e8a1a5cadf9a6d50832488", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fe5542d6-7059-4a5c-8d5f-dd46425348d0": {"doc_hash": "ce8abf4225c0868b0c8fcc7422c82ae67b796c20e6b28794fdfd0aa1f2bf0eaf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "792c4dce-31fd-4131-9c27-a19e6dded82e": {"doc_hash": "324d93ec21a82cc078b05fabafd44ae47c6d47723efbf7e571488411599065ac", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0934db89-8d06-4383-9892-2f10e1613d52": {"doc_hash": "56913eb1da544e12c510057a02d6471eb4b48750a941cff32f259254e42cc417", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a886fe5a-d752-4078-8f5a-8991d9fd9f34": {"doc_hash": "af14bdda88bbb943979e5c9502d3dacb808ae028e87e06620f63f8e78349ffc8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4b45aeb3-6ab9-4abf-aece-bcd4bf713aac": {"doc_hash": "a15d8308d23ec182645247f5956d83ab44e30e026579e3c599853a54d9aa6d11", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1455980-7e31-4bab-af1c-b99b3e2a4625": {"doc_hash": "a6c7ff7c184fd1e3b464f6d9b54069e8fc6c630a98f1b638c3735d4522f8a891", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "80e01c24-441c-4d0c-9825-cb0cbdb97b69": {"doc_hash": "a95d3c1e7187ffff4b61944ae5069823255fdf463e9963d3104914ea1cdd4fc1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "10c780ae-9a03-45b8-8e70-41cdf7ba1af7": {"doc_hash": "589db3adab3f8bba91d57bac43e1248b54023489329d93646dc7cf6f411b7e0b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bdcf5616-4ed3-4400-b658-e90ebbcee24f": {"doc_hash": "5b80323c248ff10e184c581845414ba36eda919354b776aa9f97e0d5acf82578", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "82dafc99-0d89-4ab4-9edc-b5b9574d22cf": {"doc_hash": "d40820a3ab63db7377b176397d951f2882a8af23b4baf53098a36ac0058d23d3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8b887623-fe58-4988-8d05-f6537d3bc072": {"doc_hash": "cd3f152a450ebf913c1764d07b29adbcccc4020a6033a720a26fe3bea5eb6a8e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f94e23dc-4e95-49e5-91eb-33b962f86837": {"doc_hash": "d4cf05c5bb303746d3023ca9653887dc2be86074067668f727331e4f93ba6496", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "685c52f8-0af2-443f-b714-bbcd3a0b8648": {"doc_hash": "3983f7879cf7ea8251cefb3e6329ab4507da6cc6d85d8e527da3c84d60e7dfd2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "58aae5da-f430-4b30-8b7f-19f23c5b30ad": {"doc_hash": "39e07d5099a765126f1253f130976c40b5088544397a2e7bd7f4f07328a3bace", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c00b08c4-8091-4f8e-b987-49fcc82fbbba": {"doc_hash": "1867b9a8dab61d940d1a48bb0c1cf5183645cb4156121b98e274a4a0bfaa6964", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "422f1b1e-f734-4c25-96a6-a2fa099e2223": {"doc_hash": "41b0c13c10637dc1fdb7e241c135ed0cc4382cf30317a7a6b2025a0e84c66946", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "38c6d081-a462-46ca-b14c-a6cd9cadbc2e": {"doc_hash": "62de4e1a575837ec61771512dfd9fd386136de469f0d55b2ee213154fc03e554", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "07f4f88c-1d50-404d-af6f-a3b6f3466c36": {"doc_hash": "c997bec4a8526b1c4d1508ce246488625966bf7be3f556cc189020d91befe668", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "793d79d1-2aa7-479e-a8a4-0b1437d18a4d": {"doc_hash": "98635858869e56d277bd0e22ef968d11d96ab3145b2d2daf76a2d89e1b7e5166", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2439a6d2-6998-4ceb-a2b6-656fe8c84cf9": {"doc_hash": "ca53f9c2048411f4c750435e90f450080dd50060dad4ea89d5a101e04d6d3a8d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c8a9cc22-3df2-43a0-ad72-97d260a710c6": {"doc_hash": "99cab1aa58db6292dfc913300351d11df50ec1f5f7884b4fd2876d07b29dc7cf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "23a43a67-22a5-4f0d-bdc1-3a6938e2a137": {"doc_hash": "929089f98939829c5f4f05644e6b05385cdeccb87111a392cb289270e4b6b220", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a731d2be-754a-4e05-8808-bcf6ca968782": {"doc_hash": "e30ac3b20a97ac6bd8e146634f3a6c21f54e6724560611fe1e53f4ff3dd612a8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ef788bd3-af02-4fa1-b0aa-963d036441ce": {"doc_hash": "30a122333175d32aefe20c4b54a9f73221878b2a876c399e60a102b8f2ea9eed", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e39006a1-ecfe-4cd7-9e07-f488a42ea4ec": {"doc_hash": "c4ba64320ccefb553784fa935cad61154a5171f4d21d771b3a1f35aa60795994", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5be5e087-c96f-436d-bea0-cfd2992982e1": {"doc_hash": "a9173fa4f0a3002c545ddd84357e3bb903bf8c8c1cd1c43c3c8fe627bcf5393e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f7592766-8d31-4ec8-9c35-afc9b3861b31": {"doc_hash": "84a54811b13fd2fe3dd641403d5b3d3720553790b08961e2aa6ebdac3538c831", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1bf9c4e8-1201-4385-9ed1-f4714f7ce405": {"doc_hash": "15f90945e74913661c58bbe5b45367dad9f4225ce6fd56cadb4ebc3aa09f1390", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2604f5b6-57b3-4c0e-a687-b8ae3c6acc49": {"doc_hash": "6d907a0cb9ee2d1d3bbff88993bf46d0b6c987769364c500852d2d14957c60d0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3a9f6df5-5960-483f-87ff-7e198dff1ee4": {"doc_hash": "a80030c4817fd85fee841fe7df8400e799b491db9ee03ea34c5f95ebce683605", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b4506b57-3a8b-43b6-a960-5101883be3b7": {"doc_hash": "f8179c167c93c30ec1d3800bc438ac83e4234f8dae74e20f69d4be9078885cd5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7998eff4-6958-426e-a167-bbabf80a4bc1": {"doc_hash": "0ec6c1136bafbd03edf6e6338458e620905894bdda439e9159a8324332c4932c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7a0b5048-d3d8-4144-87ca-f996353fb2b7": {"doc_hash": "4bdc196b1d000afc19f9dbace22627c18ad4cfd3debad280c2e387e90bdd3468", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5698fc7a-45c6-47e8-9dbc-841e5f8e4c60": {"doc_hash": "23c6fd52b72ff9e7f9188d08b33009adefb53ccae1ac0e91e68ffdaaba4f707a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cd80467c-7146-4b84-b439-f62d57f2b603": {"doc_hash": "cad3929e4eef563758fa27a9c49b71be050ec2534396e04a450c082bc6ed73fc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c5ae0006-3bc3-401d-9b5d-82434b8394cc": {"doc_hash": "91548391d40076edc91f2ac8844b13a82e407b750765a49dd609c084ebd8fc39", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7868bd27-338c-4837-abff-ee89a92f4e88": {"doc_hash": "e246911c493ca9da6f250930a7c4a59935a49a5309e23fefc71b5a45c2eca145", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7a1f09a-124b-4e30-8cf1-4e631ceaf8a7": {"doc_hash": "e7c8cb13d8e6d39b6676f7ce88f370e77fc44d2d9e760efdf4eeff447d393d91", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cf3c96f4-c37b-4f57-863e-843987b94137": {"doc_hash": "4f5315ac400457c8b837a6885c5eccac77598731e453f213d26443a297a3edd9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7230461e-4629-4114-8211-5c39af38b6b5": {"doc_hash": "c9b7f7cacf2e6f76da254e818cb742bf6fc57a2c00b6c24082daa84a2c2237e0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "91596306-ff18-457c-bee4-486932861f98": {"doc_hash": "f54d51d4e1ad0a5e9ce09531cbdec50cbdaf5a134f7da603f14079079c4d35fd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "682e836e-43fc-4e9d-98bf-40185f053000": {"doc_hash": "e6942c88c6a5036f563edafca3b8ad45f3ca733ce2dc78858944c9bfc034bd1d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1ea05da0-6897-4ecc-be81-3df8ea758bb7": {"doc_hash": "3408df058b7727f98a8bb1fac7f3962a7d03a4b7c159a7c69e5877c8a7c55969", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34f6d956-cf0d-4b65-a5f7-fdadcfaec330": {"doc_hash": "6760f74e0818785d607289e133d79ca607ea51e66644b39742124283358a13b7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2b706988-3999-437e-965c-2fa0c6558f6e": {"doc_hash": "49c1880c6e1ffa413179ef65db15ee6a855573b157736bf854ca18d470845273", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c8a9c2b7-206d-40b3-a610-4dbe6d282882": {"doc_hash": "463e13a5781b5ddc3b46a53701741c0695a6951f8e9c6d06620fb4b37e211d55", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ca5f9ce7-1a71-42b1-acd3-37195165f13d": {"doc_hash": "0886cf906a1a3a420ae15edc851f2f751efe059c361e5e97aea5334b30d8ca21", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "35efb14a-e80b-4a18-b523-e16794538adb": {"doc_hash": "b81b9a2c930e3605e37eefd404cb0a6d9e2c9df0e233318d47a68214f816e179", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0a0a8d26-a299-4b96-bbce-bac234211899": {"doc_hash": "0dd9263950a7f37fc8c61ff61cb9c9450af8be701fd5ad3f469835bb16176268", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "beb37876-5399-4104-8c40-a30a8896b53b": {"doc_hash": "a4bd33257d683c0f97db6c0c4440cd5d62ebd96807d5836ea075694af045d186", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1c4434e-5aec-4cb4-b77d-4d282273a068": {"doc_hash": "f91e863bd22cd35bd01be0fbf343207f4dad50a62dbfa69d0fd9b61904533dd9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "21cd4fa4-b7ca-41be-9a4b-5705fcf571bd": {"doc_hash": "7036a7891d3d9077d977eccd49170f1139d219732b9804aee5da511966ad902a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7b6d158b-eeac-415d-b095-8a0d8176c873": {"doc_hash": "08ebbe0e632d203a3fa407e07dbf1c9998fb4465c817e85388c8c7102f56ebd0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cab522b8-15ae-4f34-98a1-a8d3cdd53d74": {"doc_hash": "f32bb66b9836da7d34915f98361baef8bfe4875ec7d23e06c083aa0ca37a4119", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f246314e-97f0-4edb-b921-229d9a97d2ff": {"doc_hash": "24c6904f856605fa761b27b8f4d9b5bff43496ada6f3b839f00289ed0528a1d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e55b346d-7477-45bd-9d40-05b1bc4d4775": {"doc_hash": "04c5ac62feb999fd73d10a92103d90760de370ad144952f539952136d9b89918", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "032bb48a-52d5-49e0-9bf8-522d906b3a19": {"doc_hash": "e1439b0bc34e69fc5444bffd55319b16303e95ab4185056404c88b1189cb77bf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "99ed2e3d-71da-42c8-b53c-cf413c576497": {"doc_hash": "b090d9c0690d3ba4fddbd852cfb335fc114675b61d7ac500ba5e9d2dcaf616ef", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "eb0823e4-f72c-4659-a5f8-5fa9e467417e": {"doc_hash": "9518679d8b88d3d449544c871a4381723565ac0b3cc3a4cdbc13410225f8159e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7d177cac-1368-465d-9b79-de44e1ab20fb": {"doc_hash": "4eb9307279d1a70a636ee2228801bed20d522192ffc8ba81ad854fc20b0ebb95", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6f2607b4-5562-4b7d-abbe-c01f8b9a458a": {"doc_hash": "a9160eefc1ff6f3cc735af2f91c194777df25f6e847fff712b7ee2da9b6591c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9af6753c-5364-47c1-b643-4f223a0588fa": {"doc_hash": "545bb5c97b886070957238033a768e342c40d49cf8b1d96e2cf540f6c397cd36", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "af712d37-c85a-4524-ae64-dea69f79c629": {"doc_hash": "f80ca0c0cc295146c37cead562597d20a842a8f8d0c72f18aa7c874f1c5ca6a2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "88ecf9dd-4580-4dbe-834f-012908511ff1": {"doc_hash": "b4ae35cf143ffe8d9ee289b411f41d20ab702a687805f340a890cbce4710d61e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5b5d5ba8-7870-4f93-b89c-bb205fc1e1b8": {"doc_hash": "5d6f434eea189609a07065b2cf9995ad9c6c3f8fd60103b19692fa5efd39944b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "688d6c99-8576-4db4-b131-ff16b3434507": {"doc_hash": "c228a157d25e3d4c40e25017de379e55352d8ceb43bff9a1fe59eecb678b2237", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b3101e47-d789-49f1-abab-14a2db0eacb1": {"doc_hash": "d9e160b568babcafb9d49afc65a3360788e9bbf6eda53ec7832b8bfe9535ce96", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e90571c1-b7b9-4838-9c19-f3d8ededa619": {"doc_hash": "7568358baec1ca21324b59b12b3f43d2c28e6166435d9dcc1875c821f9103e6b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f06f0b44-f1f5-45b2-9201-83d128513b9a": {"doc_hash": "27fb2a6091f001204dbb9f728490b32e47432656667569d404be8647ae4e5976", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "00ad3afc-b3dd-4fbc-97a0-cde939f32086": {"doc_hash": "037e9bc24e4c8b6905b14488ec65ab67c14320f3c5a600d52186a2f493958e4a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9d734949-8064-44c6-8832-1debb7b49355": {"doc_hash": "7059885696ffa1ba2585891103c005644134b1dfd3d969bb58450150d9f4eeb7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "69236577-29b9-4dbd-98d7-f550c8d08e0a": {"doc_hash": "cae147e66095fff811b3cd55533b7c9d6a483c08e968b0525924fee27ed0da90", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4e5ceaf7-d972-43d5-a79e-c5cf703f4023": {"doc_hash": "ded3a4ab86b857bf0aab8a0e6ce8f309f47f581457b4c8972d5db74a40a6185c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fb4a951e-7347-486c-9a6f-a074adfbedef": {"doc_hash": "a559a6b5298d3ce7ba4bbfd6398d2f7fddae0467a99bbb62fb74157a905d6cc3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7d515bc-fc64-4d34-80ae-5d4830795c08": {"doc_hash": "8898e035990c7eff9d3e58e3c4c8e59cc06d871b70759052c2fdfd7b73a656ef", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1539c246-2a12-4348-a793-9c0090deaee1": {"doc_hash": "8f42e47c9635bc2e6f92db86e2cd3e92fbecbe5a52e33c9375ca67540e9ada91", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "900ecc94-c531-4e54-a93b-e3171190522f": {"doc_hash": "a0e8e3af2bdc6c16e3291ab385fc4f9a54ef0860f9982dc6f4de6dc0d25a8590", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f42a1946-5f68-4c67-84c2-fb408a7ee80d": {"doc_hash": "b1994095255c1e7492e952f6708ea787be557a949ad42ded3e24b505754b00e4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e781d225-83de-48ff-9b4b-6ae0aa980f58": {"doc_hash": "a91fd70383b7d993ade6b4d158d3bae670849014008ca2be66c4520b32ea2020", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "03b85c8c-0e21-43f6-96d8-fdd60c8821f1": {"doc_hash": "1ee25ba2455aea16945b330e2471f2f3d6484a85b2ed2093820a18343d2b0df9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ecc5cf1d-f62a-4b53-9112-8055efffa577": {"doc_hash": "12b7d4a33e923ce4f7d68d7776ed954594eadee90a7d6aaee899adec4ea66cd5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8df00194-ce5f-4507-9635-b2add11a49bb": {"doc_hash": "00304a54b5fa239164b039904e998b054eac0430c45d0dc7a5cf9c9dfd11ef87", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "952b94d2-13a2-494e-a932-4bcd93424c3e": {"doc_hash": "4e52425895d2d01573ee33f48fc521a9662764c8c098eaad167bc3dee047cfca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "79cc8653-d0cd-41c9-a2c8-fe6ea7b69b7e": {"doc_hash": "d472c47eccc43fd5c54927b4e3d88dd67378ac404b7ca823f6d26c21c3d7a152", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7f800fec-ac96-400e-8a98-91215f39011b": {"doc_hash": "95dade1fe249d4e76bc477e07117b5d37edf9f782742b6304175b477a69023de", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "580275da-3407-4437-bc74-3a33f40047ca": {"doc_hash": "677fe1d95170b6eb17becf63240da765bc4b9d95d1ad8ea3dd70041459e1fc31", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f59d0f78-fd43-4f37-9205-dc0f9c28bdf8": {"doc_hash": "8cd56db0386b0e0fca9fccd70eb05e3236262faf4a97bc4dc12d950be1931188", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8fc6e583-86ab-4496-85c5-01cc949e66ce": {"doc_hash": "a8f3181d72637bbfb52cee72b33b829b708d556b7018a172428af37dbca0e4c2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a632bea0-7abb-4497-9f68-af5aad303d83": {"doc_hash": "b0804298b19d9f6eecf10f7c5ba8384d02d614d65fe1efd0a2fbe1a2e3cda991", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4f9cd22d-deeb-45cd-9e7f-af10c1c65c46": {"doc_hash": "112dd943eedf71d9d97dcfa9a68951c163acd6319809556259e5b31820ac6afd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "55e81afb-bb97-43fe-9e96-90f7ed1e38c5": {"doc_hash": "479e86705bc210092de874c49e3a6f5992486b6561e63ac1d88d9c923886b012", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c12c45e0-5683-4805-95d6-3459e911eaf6": {"doc_hash": "d2c55cc992b12c2275a6f1be51d80de3867cea9a7895468dc058d7cb785063f5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0dd620a-fe30-4fb1-8293-0677b36200a4": {"doc_hash": "703a2fe12c419ebc5af5f04e0596355631908d9ddf45f5bd802815453fe10a17", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6e376087-7056-4791-aa93-7b9328a0d196": {"doc_hash": "c6a4d31992444999b482c304965081a8c56682a963a71e583a16713d692477d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "235ecd4a-02ed-4214-af6c-98098e939480": {"doc_hash": "46b74c766c319e00e4c02ee753f7576536b4684aeb2cc57588ecbd1dba30bf25", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05f0954a-11d4-4d41-ac1d-f37c2a8e27e4": {"doc_hash": "3289a2fb4c3367efdd62c7f52131518d6446ac7a9cf09acb36aae31366fefb3c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b103e39c-d442-4dae-9504-2656e846e9c2": {"doc_hash": "61ad3334d9aa80ed4b3a3b0b66781bfee4287e74b2c28dfac4ca65694e1f3bd9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1293c4ac-54b4-47e0-ad2c-5cab7986f521": {"doc_hash": "d4e6c8cf170b259a2703f80186b477124ac37c6bf3239594ae0091e223bf0cb3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3db5805e-b1ec-4ea4-8f2b-ca91cff3d640": {"doc_hash": "da35c60c464ff444d90c5d2904d77d5ce8ed3ae1ceb99668830f2cea038ccfb8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e78ee09e-a34b-479c-9ab8-b6a80a64bc9a": {"doc_hash": "b126ac936eb49cd96bd8496282865343e487a62e5559896f06e5ab8af9dd838c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "635dd438-2ff7-45e9-9aa8-c4dc78b43f86": {"doc_hash": "ee5b202a231fb30988baa4b4b920075de5ecfd1b963f50ee4b5298d176726eaa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "791530e6-1751-442a-8d0a-3372b5a1c103": {"doc_hash": "e810764471ab42466b63d16743ee8c62eb5fb66a6b6d84dacaca116fca90283b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3ddcd0e8-d9e7-4b4a-8328-9064d699f36f": {"doc_hash": "1bdfeadcdb7179501f210ebee1dff1edd4b979f1d4ade5fe4a7b3a57a73230cf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ca524135-8d96-4465-8527-e6b81af4e8f0": {"doc_hash": "4a87be63f26938b1bb90347bf7903fccb1c023379de3751474036dcf2135b7a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6241f454-9e57-4942-998e-11400e850a6b": {"doc_hash": "a62382f7ada47f88e58c408aca75de52acd377d700f9b980180c3f8a71ff0766", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cf2f91bd-5ca0-4219-84c7-8bad3fa17f36": {"doc_hash": "88f3c32e78314edc5fda1b0e7833461835434889bac41bc08c0672627fd7362b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a1014947-6138-45b0-895f-7a8bad2d5c92": {"doc_hash": "24b5747f3ff2d9949bf479b2ab4c1496115b15c31ca3251ad51c207adbcf7948", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "597cd494-1612-4bcf-9bd9-1504a7c76bd4": {"doc_hash": "ea8ba362d1be65166c493d060d30552b3a34276fa9d4e88f4ba9616f867ea313", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "12bd2db6-d9e7-4822-b422-9125a30b642d": {"doc_hash": "1ad99a7cc9e7ce7ecd7a58bc80da9088760785af85518d683f8575322b593cb1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d3e85526-3917-4338-a29a-26974d4be77f": {"doc_hash": "3715418787598ea5354fea2e482dca271e80d1ff36bf74f4f8750a852c807ee8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "30213cf9-6501-42c0-b453-497ae86a167c": {"doc_hash": "00f5d02bff5f765d7d129c357191e7f9446af56b9591a8f0b12cdc2ffa66bb3d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a262f90b-3ba1-4d62-bf47-a9b100e9b3ef": {"doc_hash": "95e2ca13e9baafa1e4caa8f60b097266f9021b12d26f42470d012d486d96aad4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6287483c-f8f8-42c3-9475-ea87df4a103f": {"doc_hash": "76bacb6960d881a708114ef51868267742c0ebae42df0e9a9c464a33e7431289", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e4400356-b71d-4fef-88ab-fc4dadb84e6e": {"doc_hash": "49b2ae47f77cc35423d2cc69337174077e88af918e30e1f71cf8a0f664d5a5e9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b24224fd-cf67-49b0-bfe6-ad8ca23bf4d9": {"doc_hash": "f4f418fc4de4d1ecd4cfbb51514a866bd1478ecc4c540d16b673b9c0cc9e6ad3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0c1a1c91-e431-4aa2-9ac6-bccbb830fbd6": {"doc_hash": "a7bc745b1a7b24caf5d59314afed19f66cb78e5d9419f251d4c2533a9163eb85", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b1cf77dc-e69c-417e-8920-f7bfbce96ffa": {"doc_hash": "6ddce18cde3de647abec59b66051b4490ec15e250f282b57b0c07b06d780978f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4c6346d5-4acb-4b98-acb1-5863237f99a7": {"doc_hash": "cb6bb76c4c98248d532619f39abfff2b3889b265e47cbf8bb05215574a60bb5b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "23e96c96-2997-4a45-89b5-9aea4012578f": {"doc_hash": "61e1e087e14f8a87eb56bb6e200b29dd80aae4332e6b0e00950f95e10f836bcd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce4d6666-099e-4d1f-9022-08491108c4d8": {"doc_hash": "74670f7b7aa784f23fe113eb26bc31c79b1a5456518b4e2119ae9512b7c422ca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "988ab430-82e6-4145-8762-bf3154002d93": {"doc_hash": "6f9c0352d330a9c74c5dcd2c44b2fb980e672307721880db613f1ee825ad628a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2d75a828-d3f5-4bd8-9f60-613e1fff1497": {"doc_hash": "25eb6c2e98554e804b8cb54f5eb9f014488b1d0b1d5cb2d7e0e65d6f93417c4a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c65207fe-5fdd-4a35-a87b-88b2aeca62ca": {"doc_hash": "39e706bf449efab39cb396511906cb7cbfe550578054d684b7274938c3c0708b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "62a2eaff-45f1-4665-975f-17a47d36f9c5": {"doc_hash": "f8c1c09f16d3e17db57923977e99fb6f39168383ba56df116057af350611fdfd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c98f4122-59d8-44c1-9323-a9e97dd9a1a3": {"doc_hash": "23b81c7a6089bc48e9b0c5fd2d09eff105e1a6a6f2b44a5b7a733b62d11e36ae", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "305aedb7-b2b7-413f-ae2a-99e49fbb2b07": {"doc_hash": "5a783b4a385a83b310496d23dd5d271e67720c390dac58d287e008c1059c18e2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "76ca33e3-2af5-4f40-846f-1facfdbb64b1": {"doc_hash": "1b8f649e86e18677f420232f2ee9f2de85754524092a2d1cd4cec2104e9156e9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7dcc506a-b552-4a21-86bd-1fca06baabba": {"doc_hash": "7ce0b1f172dbbd4cf94b985a5b216a1514e00cb2c5152f0653f5033b562cd760", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aef1e9a9-128a-4d21-aacc-a306439ea1b7": {"doc_hash": "28984dad5736fc22f405b081662338e6e1b7e0e9d687f58cbd38e7e1e5b77360", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9ecdfac6-de60-4bb4-a019-99016c52823c": {"doc_hash": "87e849ccb37f4382998181be18fbdb1546ab69fa4187c5f89869116d29279a38", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ea5e7b8f-3a47-4279-8783-267b5ee603ef": {"doc_hash": "9cd074ec7350aa590baae0f732b780977cd838b4f3669cca933e5fe2e76f54e5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2b3f54b0-4dfa-41bd-b608-3e5541e632bc": {"doc_hash": "1f235126a6d1340ea552d1e58bd84800a988b623b7901357504a41e1f8c81f85", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aa9e65b0-40e2-46cf-a575-9e3a0e24c178": {"doc_hash": "9701b76467d226b3a28f24510f6ca63ace30fd44655e530dd445668eb4ae92fc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0e4581fd-7f44-435b-9965-81ddde6c1df9": {"doc_hash": "807a4c2df89c6bf6fcd55a7062c8b068d49901717166c28ec4e487c48de4d8a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "545a6fda-cdcd-466c-a552-9fabafff40d4": {"doc_hash": "69cda44197ecea1ae751b424bfdeb3b1381a701b1d1d51aa42d4e3ba9156eb3b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e4b6629f-bda7-42ff-b788-1da8afc1be3e": {"doc_hash": "1851e07fdd624f4a6e1cd609a8ea597c7ce73330053ee6ddeb7d9f2fc016b0fe", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9a0dfcc2-09ae-4210-9b70-d570f75aa118": {"doc_hash": "d57bb314d68ffcf2a9350c20b6c61e8a762fc5e35b810cc2dfa409754054b3a8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "032e2def-ac57-4483-ad24-704767e7826f": {"doc_hash": "505a4243ea19d7424e63bc1a8cbeb6781d2a3e5d2667c7e3a63fe3de56c23646", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a6394455-dc90-4d99-903b-f61c187cb1b5": {"doc_hash": "54be2abbb2b16eb7a5de84757548f41b70a6ff5f2d93c2a86a16d42c39239d9d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1715c75c-23e9-4159-afee-a3f390a45650": {"doc_hash": "28ce83f8e090effbc78ab654aca06bd404cfde7f7e31ec01c430749f36c6fd44", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5d22b188-7eb0-4210-963c-e00829c9886d": {"doc_hash": "488037455587c8a66a11094b1428a4311d5d891a23f9b5c1f2343a5a64bffbf2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b8655aa6-0570-4b68-936f-c1398ef4bc33": {"doc_hash": "141589d5dc50da22c034778e803a6e2041d4416b851ec1524cbf61b2446ec80e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc4d5e6d-70a2-4427-9760-aee7faf62840": {"doc_hash": "9dbd22c893a2ee5af7ed2b38df6ef8fd17852e484515aac112ce271ce00282a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5dcc43c5-1af3-4255-93bf-bc5764e96422": {"doc_hash": "ea010fc62e855f6f7643c7e1e817030ca872cf087f0b260ab52414d4ec2ee42a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7340accf-7384-4a05-b5c6-6aeee6b4b50c": {"doc_hash": "3776677eda435cf3b556f86b3272cd7af5d1bc30bc38aef4f6171da59dafd5fd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "77173165-39aa-4b8e-83cf-f775766917b2": {"doc_hash": "7ccc6bcee3b770cfc282d89bb3214631426b09f008df0929b96126e044f9e0dc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "827e424d-d993-45f9-b478-c1335e68ca4e": {"doc_hash": "0e71f3972b67532a8481a284125ac6a52821ac164c4a1b18ec945d46fa3b2979", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "75c7b6b3-8f00-40ef-8980-daced5ea1e29": {"doc_hash": "9e8b911c51a3033ab3f8d232c00dd7829a6195e202f5194fc99c6a417531f4d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f24a8807-5fed-44e7-b5e6-c555740fdeda": {"doc_hash": "1048ebe07900ddd345dff3f4bbba963258f7c9c329b0803732cc7c1b5a1f1b7b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "885992aa-525c-4d3a-9b3f-04c6c3f6b0d3": {"doc_hash": "b8984b0d227a61994ce3fad5b8c3d0203da03f2c6cb78e85a4ba57db9ed7e35d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "deeafbc1-5166-4acd-9e80-c2161448398c": {"doc_hash": "4c5a4c3d53ba58b0996c830caf4a7c30a6ad859d1ae780db16376ba3b309900a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "54c38f20-5dc3-47fd-bf12-5d382a9d7c88": {"doc_hash": "21670a3b6c83cf33772a5afa21361f0c2938c093fb8972bd3c0e850864b8ce0e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b59c3aa9-da22-4b6f-8b51-fbdfb42073b6": {"doc_hash": "439cf8966f9368a01707764f14c655ed0c4ce485a2889dcd3ee1dbc4c61565fd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34b3096a-9aa7-4ee3-a4db-0c6286fa9e8a": {"doc_hash": "708aa094c6cf04412dbaf17841f5c66d336c900a4ce9a0206aaae26eaf966145", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6927e421-bd87-4cdb-85c2-c6dc07499069": {"doc_hash": "e5d041fe7c773f4e8dce246b6518df2b2918338a362a0cecd8f534af8c55b3b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "daa590a1-9945-4da5-a504-dc976cc52de3": {"doc_hash": "9aa3c6a8152e3f1fcd0be0eaf65b1ec125e588970c7bfecd70dbc1396d781ae0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7c3b2889-bfe7-49fa-b20b-a13d568fff86": {"doc_hash": "a9869caeda732f2489cc2cc08f03a55a4b4d2bb37e42e10bac7350e000ed036a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bfe66aab-a3ff-4be6-a394-61f49f90946e": {"doc_hash": "711203b9221ec818b24c72637bc422ec04c0f1fed576626b60596b5c95306752", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "30f9f7c4-2366-4ccb-8a07-175f77ed9756": {"doc_hash": "aaf86e1750c59a1569316524441b115bba4dce25462b8123b575f4833ef8b67e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9fdd7d68-e56b-409f-a400-cadb299185da": {"doc_hash": "2c60b2cd1d5500db755ddc16cab8ea7460afbeefd14a7e9b854c8d0cf4b62680", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "219d8599-efd8-4f69-a5af-b39886ecd9fb": {"doc_hash": "6164e0a8b7d75a04819090ae159b0f4b10ceee44405401f4c0c0ea0a45923ef9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9e2804ed-802b-4693-b107-5608986ac855": {"doc_hash": "0e64a543c7a489b536b92c9c5a1a1b3c65f826815c98adc12da5a8a3d4d87b01", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "59bbdf9d-1fee-4252-beca-e4313d977ec4": {"doc_hash": "9aaf7e256bfc389a1b31d5a24fd87d298cfc356cc3a14c8b1fcc42b665203e34", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "738dd8e4-d9d1-481b-81d0-340aec1dd43a": {"doc_hash": "016d18e2145f3b3ecb269c6a4b62ec6b33c2904da325b2bafc4cd85451ac3a5c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b32e6ef9-10e5-46c6-86ef-c069e8a29153": {"doc_hash": "3f843e960c98d1a0e082947cbe1be0aca5fd69c27b727d29e79c29bc6d19a1fe", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d08c0d78-59ae-40b8-acdc-ca772c874ee5": {"doc_hash": "18792e1ce49856d974d45839fc0d369b9c99628f68a28b4fea0ef96fe7cd6044", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b311f2db-345b-42aa-ab1f-2e728ff07e9c": {"doc_hash": "f43150aa04b4969e5b3ecbf3f3c2bdb38509dd08c273437f2a6af0bb7a83215c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dbe7368e-7963-4de5-b58c-8e512a86a120": {"doc_hash": "47a71e639af5c349533f6f9cf5d0cefb97371b2c58a9bcaef7492b6ce1110554", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e061ab11-ab3b-42b4-a6fb-98bc8c7e2e35": {"doc_hash": "e7bde9b380ad71223be83b3cdeddcad15acf07418ee7fa47fc0d30f7645dd927", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6309fda8-c605-4685-81cc-fda613c092fa": {"doc_hash": "c7c3878559dc66c8762ed7a16280a332ca5e50b2c2fd20de025de02687dce955", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bd1027e9-5bfd-4c8a-a4bf-764cb710ca81": {"doc_hash": "81f4d73e1190103523e357b026fcfa93d36121e5ea4933a0efc84d748f64d9ae", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5dc465b2-16e7-4216-8033-32335e23e84c": {"doc_hash": "b37197bd803962920dca7eaaaae197dc37cf9886040d3ecead2497d16adc56a4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "33a84877-1f76-4c11-b610-586e7f8b2d4d": {"doc_hash": "92811d642c1d88862e3e07954c7cb7693b84295e103e4a5611f7e83a20315f01", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "16577af4-0cef-49bd-9ddd-69952167c15a": {"doc_hash": "f8c95fe06e83a96d1f6ee0995b004ac3e93eca15ee8d3f19b65be1adac38fac0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "95a44b1a-c6b9-4f73-acf8-3d0798376a2c": {"doc_hash": "3a13aed6cf9bb955a92c7fea243473994267b073d47d37735e50ce9c34983cca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dbca4706-5dec-43de-970f-ab310f50cafd": {"doc_hash": "153ca19911c32e47c6343d95eddfd7688b90e61bc70ac476731ba174aab4f505", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8fcab725-6697-4f99-b9fb-ef1afe18f980": {"doc_hash": "627f517bca42273f39f95a89ac32cb788c9c06819abecd062304d3f76c9ef3f2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05b21a26-f329-4d25-a93f-f8d63816e622": {"doc_hash": "407504975b7b1e6df4232463fff755eb9aba69f6be467537b77a6cf955269d73", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7383294-0fd9-442a-bc8e-d61b2e66bed3": {"doc_hash": "a76f249b240fd3d8ed2f549cb95688909ada3fb141b5d4b6338cec43520fe758", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1dc62790-7f9b-4fb6-9c76-33e6f88339ff": {"doc_hash": "d53f0bdda9bc430c9a8dcf74d208945fcd20b502364fe120ff817359a33183eb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6f15b4b0-804a-4284-8241-de0362fc1d22": {"doc_hash": "103ef6b702953105998b8ec6612ac1638fad91667ecc5d36ee3312d66195abf8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4b0017f3-bb15-4d76-9d59-e15abb40c668": {"doc_hash": "d89ec7721b9765c74714d6b8b903f211b14a5bd138cbdd3b1530a20775e6a86e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "21081f43-7894-4288-a343-cfe41d62aec0": {"doc_hash": "7d694572ed3f35a6b656d34ca5416737bac1c0a04f9f2e58549d6e4c9a8f4a3c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7d2fb3fd-9b5e-48dc-a246-4d4f4b84ec24": {"doc_hash": "ce18af00519cb71e4271fae342d46ea5b1424a5cd9abb7520036716a4289e38e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "60e739c8-97b1-43ce-896f-e983b52143bc": {"doc_hash": "c9a82acd4661c2cc1f7ff8b02d1c573bd25cd03f1b442f306806c327f10169a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "383bc2ed-4c36-41ed-9a79-9306d3307353": {"doc_hash": "e03a5742470ca63f39103efe5959141c307f18e4a2c3542efb790eb711b4adb5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ca3531c8-1fca-4824-8970-4bcf0ae5f77e": {"doc_hash": "7d0cc2f9448747f02259969b7fdd9b2d6716b31d7307508c29ef73ca5a85d7e3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6e832700-e49b-4ae0-aaed-76ddd9e0d8d0": {"doc_hash": "59a0c8dd97d665b6fe0eff5ee0fb7b9d9b52f8680e8f5cc1e22ff8a3cbccdf42", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7361a568-2312-479e-aa47-e13ad758108a": {"doc_hash": "c1c151a26bffd8cfbc148a7e5f8ba1908430235010ecccf1e6ca947dbe42d617", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b2ca5baf-a3ad-493f-86f6-8177d451c5b0": {"doc_hash": "91c23fda4f0dd76959eb938cb91019e4f6e216cb050a3f01ffb349aa14cd78be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8fc7e000-a3c2-4f96-87c9-0bea15114873": {"doc_hash": "624f27f8ce4572c345721ec8ce928ae416e6763be9056f6452cb80fcad4bd790", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "86613be0-b201-40ed-a6b1-54581e753641": {"doc_hash": "6f1862a0d067de8725356940d853ba4cd0d1146e7e8a757ec93ef935505e5ff8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f6237566-db60-4345-9af3-4b79f7263880": {"doc_hash": "235509e0a8cab68cd375b5e02fe882cfc4b424a98edc5b41536dffe6c6872648", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0e5ab22d-2e9a-4b95-bfb0-660d20dcae0d": {"doc_hash": "1dc800329cd894fcc6954d7d5f7f3c463ea56d539c75f12aa06a9c0fe6a4afa2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "640b07a7-4f08-48da-b512-683641fefc29": {"doc_hash": "daecce7d3c455a50bdd548350e6523f553fcb56e0290594382742ba167aee991", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b709e6c9-327a-41b7-a204-ac572ba3b050": {"doc_hash": "2ccf12d065a5c6c11bff835625272784fb6f860162ec9d8a94189be2db4ef35f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c9920f29-354c-4b57-9be4-1cd5de4be0b8": {"doc_hash": "407283857bcf25807fe942347e473431e1b0fa3803b4ac23a26cf171a7ce81b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b67a7af3-3450-4042-89fa-f7ef60de3b75": {"doc_hash": "5a91e3a0d1bcd6449e16d7b510d880873032fd3b58f443e04747739da7d5c0ea", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9c52d7ca-871c-4e4e-b094-6e51e7e242a7": {"doc_hash": "323d11750aec9388f158ec27e43dfe0a5fc33473d33d69d536c816b455f0d236", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fb3ed8d6-77b1-4a97-b398-907695774fda": {"doc_hash": "b0a4cda4d7b20b3563c8640243d97230d57931225bff1151a31c7f2678477a45", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2c90791a-8b60-4b87-b7a9-fb79b21bbc7f": {"doc_hash": "e7efaab390ab6a239f4b82cf3bf9d13c426cf92358dfb63a4a4945539b8f0826", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fa8e738f-f0bd-4796-82c9-debe907be99a": {"doc_hash": "8d72131edc3b75dccd60f3655259f1ff530cb82cffaf8bc43d7f29366deccaa3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a90ca940-500e-42cd-a60b-c6d92577959f": {"doc_hash": "f76e31598686961cc7bb5874112d587a879a51d8bf21e154b4958d0c0bf2e5e9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce338694-235d-4b75-a875-08cfef1cea84": {"doc_hash": "3d7cee0b73ae2885494e5335efefe50a56f2152179c5a60e9cc9b31d4a357b8f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0a91000f-30be-4a5a-b93a-969cef413cc2": {"doc_hash": "099a2c1cab0ac55aeb0adb6528f6465491a8ca0efcf378d05cf2b82d8cb8eca2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c2733677-9c87-4b0a-9039-eba8db290368": {"doc_hash": "0caceaaf7c4f5d16489e39efd9a5ca0cc1e763db8bf52516355476c1acce0d17", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5f05a5f2-c568-46b3-acae-a0458dc291b3": {"doc_hash": "4e892e89d04f96e18690dcbbf7ab855e150a8330a6e58072e74fa0a97a6db921", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5c4faae1-3dc6-4d2f-8f08-5439bbfcebb0": {"doc_hash": "7302848249891f8bd58407a4d21b031660067af43e659261d033215d63d6bf73", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "31b31038-b6d5-4bf2-b9f8-4a063ea4e8ac": {"doc_hash": "f1c3ef4bd24ff34ffa7bc9445a0821b0eadd59bd5b1064ef7b142e814cb4dc9f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "38cbb6c9-b411-4bb7-affc-7094cf098f01": {"doc_hash": "dae5d254107f1baf7df79ba6d66e7ef145358543accb724bf6d6c29c6e6c5c9e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ef8b5ade-7c63-4c3a-96f4-4efb948dc40f": {"doc_hash": "891278ba59e95a5041b7825ec625c9f7d39f366d30e2c0c842c62eafc99ab4be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "26edbf00-cde8-46a8-959c-b31e5fe1f008": {"doc_hash": "5fae2b4c43333c12bbff15849b60faa15fb0e438008617d614240b416bfc6465", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "823c20a6-e08e-42ab-b578-20f0047e95c7": {"doc_hash": "cf6f1c5101c5dacb541f83ea3baad92f607565226a3dcc79470301bf9d7aff0e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fbd578cc-4c00-43ec-9abc-ae50f8312684": {"doc_hash": "199084ae124b92d4eaaf83541088dbea58d893db84a812cb791509a299065421", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "059d64f8-83d7-4b00-8124-3e8dccc2bd94": {"doc_hash": "d868414a5e25798c6c6fe78cd356e7a805a10369f152c6dabde476b24cf68507", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "de04f443-e141-406b-97cf-552bbccc19d2": {"doc_hash": "0fe83dea90a98dc54590cce2fd7300b52b6090f1c66c516e3c121a2cf7f7b30c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8fa2618c-f204-45dd-a785-c617658af805": {"doc_hash": "8066ccd18e31564f8106ed070dd0c4623e649990fbacdfd38d04a3d25a399fc2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "665a0869-0eea-4bb9-a8f5-0aa4cc126f8b": {"doc_hash": "17f44cdb8906359ce2d9a69f01208ea592765e7ef5aa1c49102aa6e87774fdab", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a7fee9b2-020e-49dc-bc00-128f305a3e69": {"doc_hash": "b3c2dc7e30b0da3c4f044440eecab4bbddf59fa538618ae9995063098cc8d483", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9974e4aa-3591-4bb0-ab46-b2459a666951": {"doc_hash": "aad10b13556d2b91dc954edcc45290f05e4d3af4830a7f8ac9bf0a8d94ad66ff", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "29138787-7d9e-4289-a03a-3a67a08db26e": {"doc_hash": "a93349de3bfc50e3f3d49f1d740d0010a65e663228f8e44259b22638e0d99d65", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1240a006-3da2-4c1c-b75c-99b5df422140": {"doc_hash": "e90a3383f7b6af205d1ca35a8347bdacd64d85508126ecbdc2a0e986463adaca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9f7bdf7e-fed2-4a0b-8df5-4b22f791383f": {"doc_hash": "aa31657bbd0727ee39a1d117c13ddbbce36b460f75817d440bb374c120944094", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "350cd722-3cf2-4bac-bf75-42d21d49c70d": {"doc_hash": "c91bee10cbb77885064cefb4762569a1ef36898c7bdb9263c0c1d0afe7ef5591", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f4525ee1-312b-4f8c-b85e-f2c39a05e12b": {"doc_hash": "94dfcf17f2f690a94a2402c8e66cc004fdcc684fc60a74383cfd4f78fce5e702", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5e912467-1ab7-427e-b67d-4ca3486dbf9b": {"doc_hash": "0f719d637c85acdc401ad37e92dc6f425e2121069ac1cfff41bfb48eb3ab51df", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "853e229f-0a1a-4b8e-b2d4-b0eac7d10747": {"doc_hash": "ac74cc527a76340a591a9107d9ca1bc9d3ba5dcf38ff3b2e338aacf3d4557d7b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b0485739-31d0-4f75-adf3-ac80d3c6a481": {"doc_hash": "dc882e866158f625d0f1ef171e31201dff3e180671456c2915cc7c0c8f4a4443", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "87f2c27d-d610-4d5c-be6f-20717d7eb9aa": {"doc_hash": "6e91d7d398fafb74bedd77a11870a49772f00742d65d71bcd3d785b524f5afd2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ad4def69-3dab-40f4-b11a-311e5f6ac54e": {"doc_hash": "ae670ff7ef7d5ef5742eebe119a799fadd4f0fb982a9ecd7f72e723e7f0a4a13", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d082242a-df8a-4e5f-9a6f-044c682247e9": {"doc_hash": "402133ce28a1f0eda752461c4fbdd8babef936509ff5a14422b962ff64b5fcdc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5c0a0648-7ec8-48f8-809d-da65dfb4e917": {"doc_hash": "9f47395be07e9ae9fdc72888cb13626dcef43cc466b4087b2e012db0b9a9b2a3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9f1c83bb-c862-4ba5-a41d-64a370c45fa9": {"doc_hash": "93873f0001a0ddeca086768ff8a44a8b009183a11409f6bb54c50faf4c9c7df5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1687d876-9b43-4608-b7de-fad565823d6f": {"doc_hash": "6dc6326b0de014b686bee06e3c7ec9c374b95a563e9a222a6e4486b38ebcd0db", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5212e8fa-0739-4d04-afef-dd6d2de7b63f": {"doc_hash": "3b9cfda41ea99167ece7a8ccdd68824b7d9785f66b98d06703bc95c684b0d211", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "103c322c-4989-4332-b737-6d45c4b85ec3": {"doc_hash": "9d561cdb78d94f508a87f6d491e2ff1d25c143531c659274f0b08e359a768dd0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce4cbfdf-8e53-47a5-a2e1-eb3fa374ebed": {"doc_hash": "6ce4876363d2aa9266257923066939ef8805c31a8e26eb09cb4b574aba4de1db", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1db28704-c9a6-46e5-89ec-81e37ba20044": {"doc_hash": "106f419056946b8c16f222d0ce3327fb3ef3ca1420afe17cf2e12376be59ab49", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0f8c38c2-7420-43b1-a364-5ce207090d0e": {"doc_hash": "c4a3321d3b1949a5ba21fcf0c6e4101e8aaa6d03030a94049677b69cd7f99907", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5e0c50cd-08cc-414d-982b-b5b47b4d51c2": {"doc_hash": "4d498ac806ce88e5767fb69367fb5bd838432160e626e03462060865d9af31f4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "335ba7e1-8f90-448d-9252-3f1e0469e6c3": {"doc_hash": "8545adc96a65e160820b0b1bb2e299dedba2d74cb6aa873842a45df2f2820a11", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aa1b2fe5-9889-4420-a499-94ee22cc3029": {"doc_hash": "13218e17142afbb69521884c2f3ab030d93589e18fa78e3abdc878dbd7c80f3f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8936efc7-eea6-4fcf-9309-15f097965a0b": {"doc_hash": "c03d7e6ee2a796dbbc86bc24f9b29eb83bc21f7147d0abee17641913af15ba36", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8d34144b-cbab-4ce2-b5ac-993ed741ad5a": {"doc_hash": "9ea52b8547e045287f1f47e5b024f9d63a69b4ac1d87b74de5181a0c1ff048e8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b428d621-93c3-446a-b2ff-2eb2d1fb78df": {"doc_hash": "49b6badda541310b50a50e44318cea134b8dbfaa18400c8af3e8e0ac54ab786d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5ecdadfe-06a9-4745-bcc4-3b9fd095e939": {"doc_hash": "d28f9d44b53fcf5468a322c5c5087eafb027790f1f798614f8fb2051e4cb00a7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9f3fcb25-ca3b-487e-8153-17488d5f4a31": {"doc_hash": "5240b1c38169e5e61737afece254d0b16dc49f7a3ff4c320c00ee92243ced072", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a1d312c4-06af-4c3b-8e0c-90137c63bafd": {"doc_hash": "7a6564e2ba6e88e97f1a60c43773de43df4711531c96ac8649892c7529cec3ca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8a05d80b-5994-4300-a88f-77394ac0cff8": {"doc_hash": "1a58441f6e0363143fa2d3a22cc3917d2556d780c43158763604d6d8e6cdb467", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "35231165-e92b-4d16-a46c-0bd7d157c53a": {"doc_hash": "1e36c380c577b2b00e670a1362b456699aa1a67db45673f9a39722e997846936", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c359e396-535b-4493-a607-e207efa683db": {"doc_hash": "9da04d14349a6424c04222cc627e1ac57c1fad5ae0b0d328e1611439b092657c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "68c91fbb-859f-4e25-b8c6-dc07e8f1608e": {"doc_hash": "964af22c570fdcd59396a37372fce4a5a2fbf357d1901fb7bbb8c404f10c48ea", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71f897b3-3dd4-4056-9f33-a988fa552dfb": {"doc_hash": "1ade72c958ee40bd476a6606b5ebd8384c0a8286d6f6d102022f374e36a761a7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8c85056c-ed33-4b4e-9d71-640f855a7d9f": {"doc_hash": "4ce18db9b5da48f2fcf711e06719e5372ff61a44daf9597a9e78bae05a34ec5e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d303a5d5-16e6-420c-9f96-05d099df2a3d": {"doc_hash": "cd3d654aa1ee96b8306f67a5bd5f74b8df58d65e6894e8300a4857f09f8c2350", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b0846b50-1c46-4ad0-b6d8-13c9900dd84d": {"doc_hash": "bd135723ee35296c91090d024efe073f7fbef066940f5915f1e8a0457cee67aa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b6fb1377-9005-403b-84c2-4fb3f12d09bf": {"doc_hash": "012e755910c60b9ee17d796d8240abf85e22fbb7490fe57fbd029d17031d8cb8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b207a3fc-9bcc-42b1-bd56-e1db4a50ab41": {"doc_hash": "f59a54915f2d669f67a5df492102e80baf55a3cbb1cb2812d09e72740961e0c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2cb90d0b-73ba-4cb0-bf67-0888fc6af683": {"doc_hash": "4a92f01c33f9c96acf6b1af510d2ec3be39c2ba57d9832d04132d75769b83298", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc83aa8c-bd53-4fa1-81ba-da06c9ffe75e": {"doc_hash": "c381e5726600de4b2a823bc15262f5e6190514a33e953b0daadcc2cd4e8b4011", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f53c6621-36db-41ea-acb2-aa9b0da17806": {"doc_hash": "9b43a055ef18ce93bb0851acc8d9c67986876d4d139de85c389f63f18ef53a6e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7d090e9-9588-4b8b-bf33-be8774ff8d22": {"doc_hash": "ebb237ab71f1fd23417385ca8f36be511840679742c2e10726413ffa1d56b1ac", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f0efda7f-74c7-46ba-8676-19d8ac051f22": {"doc_hash": "72472aedf238c8d2db0521b22a8706188223e86bff308e936198e7dfb645a588", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "08094d77-ed64-40a6-94a9-e14bdf7f8650": {"doc_hash": "d8b3fb9d25a92b964d532dbf726b6e3002ce64b19bd79ed1d7668070463d664f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "eee336ac-bf2c-4fff-8e1f-aa8cc7a050ef": {"doc_hash": "519a29a22e801fee2113c257f43da12a88650a5ac89e95ef4aba8b16ff62a475", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c9831bd-35a9-44af-9c46-848cc80f9ea0": {"doc_hash": "f880a6300bcd559465f77489d89452d5f5dbb0e657090078f6f3f002a40669e7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5d51b3bb-53a9-45a0-9132-39e4d2c14b70": {"doc_hash": "1cfd14529a84d9d8cf3ff1569bfac10b389e9063d3829e9100ab4f5ac1204be6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ebf5c6bf-47cc-4af6-961c-f5a4b28161c9": {"doc_hash": "a8b231b2b791d8ad20cd1b8496ab5da5ab3563b8abc368d5cc914fab22f0c0dd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fdcec42b-0525-4799-b28f-4e8c3f085c59": {"doc_hash": "b195995556c126959e5849b89b149f93e4319d17b578e876e013c1114ffbc06f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a3b2c513-940e-4543-8974-b263e5d920cf": {"doc_hash": "538aec31cb326b7d24b696d0d2ea6dde261e34bfd01f738ee59af86a4f3f4648", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7882b2b7-8d74-4b75-a080-bc7021a9eff6": {"doc_hash": "05dba7e1135cf59a1fc33f2029ae9e5f86d0d647e3d39f9b50bc6b7aeac62afe", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1df8bab7-1e54-4cf4-b13e-fd87f3f81ab1": {"doc_hash": "ce228451b4d496d62b51aa0e42bae56674f85dfdf6e2f1b7253c1d3c392eb460", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "625fd63f-d761-4fab-bc56-b43e7c41200a": {"doc_hash": "577224d62e2e6027d043909baf75fc692b3523bfc4c5ac3164db57e12d9ba090", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "247e6c7e-a768-4b90-878a-ca4dc433c9fb": {"doc_hash": "93561a42633e24899cea0d1f23110d022f7ffe281c66b97ef63beb080768b638", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b35b0d8d-fcec-451e-8f5f-5069daad95a1": {"doc_hash": "e32fa8a8c8deb15d714a0a894b76c1a47dd2113387706ae6daa43d6e63f8039a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "07f3f519-69e4-4e9e-a5aa-9dcb8ad05403": {"doc_hash": "4b2c80d7ccd8697cd082f6a07f48f37c12e24f1af4d318956ea7c0a3abe3b932", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cbab7583-bfb5-4fca-9045-01318ac4eeb4": {"doc_hash": "292a841a528b7d366cb57a9ec31bd7b4bf0108b5f75d73e87e480370d62885db", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9c691b00-633a-44d5-ac59-2fcd6c48963b": {"doc_hash": "984fa8eadd0dd8c4197200d3192458c24b2fd93ee19e009dcd54d51b04d3f304", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8afec0be-80f2-4361-9f1f-ea8a16748c0a": {"doc_hash": "b398cecb327fc3025c9ae1075ee11d5141138bb78943c7445212837afff67ede", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "23403119-b096-423f-b84a-a89ea7cd5605": {"doc_hash": "2638e4b037fa9b45a5db6a00275155fe2dc8aa862b7d001621facbe9da54327a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9fcb799d-36a2-4fd7-9a37-9c809b1ab715": {"doc_hash": "38cce7c657101b876918e7de1940fce5ac240093f3f949e79057e58722a50b28", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ad8c6486-8752-42d6-ab4e-286325244518": {"doc_hash": "915bb28c7e3ca1830a23f9dc56b72f14d95cd875961a1026bc59298f571dc384", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e4b4e19b-34ff-4378-8797-3aca2209cf3c": {"doc_hash": "3107f63c4b3792209578602e1221800e2a9a5935b7f989b730b7e674c6d748c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "68a7e795-4593-4de1-8243-0646853bf1ef": {"doc_hash": "7e97ab9d1cb03ff756b911fa5b2ce12bb8373880094cb8ea4c57e41dab54a898", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7f857d1c-41d4-46ed-98bf-e8774af5b6ca": {"doc_hash": "30dfe15350f4df002e96e68fc50373dc20a9b6690fde23d18896a24f20014ea0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e03f4163-9818-4dc5-98ff-ab5dc3d63bf8": {"doc_hash": "a5a8088e7ba49e387fdde5fbefe3517421935a83898900e7d863a9eb8dbf75ca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "09411206-7ff8-4ba7-845d-c4a2c5203e83": {"doc_hash": "68b46bc68e56fc1e2694916373ebd125da577d4e24d212c95800872359b3bc97", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "76cd9a09-e980-425f-a108-855ca0485815": {"doc_hash": "e423208fea90d3bad82977debe93c41a8f2cfcc891b6a94f134a1569b157621a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6221e26f-61e7-40d0-ac0f-4fced0d13cd7": {"doc_hash": "c3454026e72cb992785a9d08cac34379b8919bb734a8d35e573cd5fd1ff7d666", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5f06b8b1-0031-46dc-ad84-de548da0adfd": {"doc_hash": "6c248cfd8e4728002f74ad43b0eb74ba4917fa436ca5e4a72ce3c5d19e2edcab", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "93934fb7-7761-4cd6-b8aa-460de19efd70": {"doc_hash": "3e2d5f607c7d95400c1e474adcf3b282ffebc5fa27c4a774331f385dee7bed91", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1935cc9-41fc-45fb-899f-227d67e29c3f": {"doc_hash": "5d0574ced24e433a44cbbf1c38981080c85672b050240182fad65dfed3ad29ca", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "28ef4cae-07fe-46fa-a758-810fa89b9255": {"doc_hash": "17f3a19f91bf493f0eb24e05c9fc11ba113b8b57e0ceada7f91a1f9fda3f589e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6162008e-079e-4a3c-a5bc-a2540b83b9f6": {"doc_hash": "259478638a25433780b2c2fe8aeda6640f7ce7c5fefcfeb961226c1ba25407dc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "69f67f25-1c48-475a-90aa-6e107406847c": {"doc_hash": "d0e8e8c3c3c430247803fee847c3ab20902efef4d1f19c288dc2dd99a9e27d2c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "918cf268-cb13-4af0-ba78-7d147df5484e": {"doc_hash": "7718c501691233d8fe7cd9de998c2925241f6760d657a8eae3a00fd3d8fa0e8f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7a28b953-cec1-4079-99e3-b1a77f66e883": {"doc_hash": "6c76a3b1ded764f2b309d07731012ab4212a9a65189676f6e440ddd148008e5a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "29927a83-f3f6-46eb-b856-da473016e946": {"doc_hash": "d806f5c56f7c7142ca56062570d3f743befb26f3a7bb4e38956cfe2bc6d4aa99", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1fdb3a24-7ad4-4cac-bb21-06392c698cef": {"doc_hash": "9ca9705057acefab7622dbb19568f54d31b508207d4657a296fe5a7ab2547642", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f69b467b-fd2d-48f1-bf72-2ca2091eff21": {"doc_hash": "030642bc19fa6c2c5d81abbc43787bd109239e6a7a732493147e43a59cbe6516", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce76a1b7-3efd-4c1c-835a-220c70aeee8a": {"doc_hash": "8e1df987a459af1f1034d5f53745224192be4e30b4d0cf5c0c56c2cd54ea7fad", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cd94903c-ae7a-4c6e-939d-02d459e640bd": {"doc_hash": "b4cd05318e1d162be2215d0d036d4750cf8c92fd0d7a169649c9242c9675bef6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "46e72a62-0366-4e16-8dee-9762f8055065": {"doc_hash": "6be8563643fc551c837f3041d79245f9be78828153220487346ff56c92fbcfcf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9c32b579-e408-4ebf-b405-8aee63ada3c5": {"doc_hash": "0bac0e8fe94b2d97b6a66d8905a2c026985552be899df423139670075e5d5be3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "16927a4a-e956-4601-8fee-c448174c9cf6": {"doc_hash": "089e45bcfe09d51b6a69b4ca8cb44e15c635486955b74374e0767552b2e1bba8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0db593f2-2b89-4b5d-b8af-0160bd04d0fe": {"doc_hash": "adc6e97879ab131513075a2e6b0dae1684dfa23fb3c9f26385d6375ff6487b0f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "64c8d0bb-8cd1-446c-b5e0-9c06ed848049": {"doc_hash": "bf58890484c491860c19242cd90b906162b453f050bfd040ff58a5968ede6d8b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b276ae0c-0050-420d-a8ea-cd5bafd9ea12": {"doc_hash": "798a98a7c5aa2058ece28c624a1581850e6b81b6cf3e9276e8b578d4bcd89fbf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cb3f6cd2-ea68-4eb1-bd88-f3db54d029de": {"doc_hash": "2f60073a6686ce10ffe26fe7a350d10d7e8d4844d4b91952ecfd51819365510e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "46ad5aa4-1cdb-4a93-8031-8cc5b1c7df4e": {"doc_hash": "49594696e2f84a1ea058b9cc3bd9c39b6f6ca50b07594c337c05c33ef0d1490a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "092998f5-f360-4b7e-a923-f3234b01dc27": {"doc_hash": "5eec0c23ce400c6526ccfff099c896090b13bb4fcd16c8b7a290b4bf4e596725", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bedab5ce-352c-440e-b9a4-92f6f016d218": {"doc_hash": "1c4467629b35287d8caebb19b01eed573a77253a5f0dc8e45ff1818362b4debe", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a70dca95-2537-4239-8fac-4dcc1b59921a": {"doc_hash": "d91d64d49a19304357c9fe8a7368e3db36a14f45dfa1910e13ff94e499eb30bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f845c4dc-57f1-4d68-922b-9f30ec090790": {"doc_hash": "4eda155c36a54174d8816395a858a2bc24d01b8b174c7358f1486f874bd53aa9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "97bf1c8f-ba03-4ad0-962e-5ff694d26ffb": {"doc_hash": "606bdb2b546dc9c9f76b2b850abe55ecec74c28aac3c0de6958d9187714ca830", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7cb96e58-31f6-4726-b46f-a463ed56652f": {"doc_hash": "0c38aa0ff938f6c28d32f77ee4c625a8791ae014efcb40c5d06bd9e39511e541", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1241607-efd2-4fef-b738-d669bd1b4dcc": {"doc_hash": "cf5e55c6ecbc8533c6b5a904f38fc265059005121ac2325ff45571c33ee6f7d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "20357f6b-7cf0-4c3a-87a0-9e256b0f918b": {"doc_hash": "d02fb0f2dceccc46a28fe1cbb89fcc448f59afa0853da77170975fb4025be81e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ebd0f2b8-4630-4110-9082-1b3331f9023d": {"doc_hash": "0ea9a4cd7dc6e9d1852c112f626dea6e7f88954c1105ee0969ee29830183c924", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b698a3ed-d031-4c92-8db0-243384051955": {"doc_hash": "5200b6fc04a339776537ed2119b5025e7fa26b4e330882219438030411e56f3d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f87b0663-2ced-4b2b-9497-5e40751cf78b": {"doc_hash": "64be19bbcf163eeaea9148f8460ccc396d604a485621ace00f0a6b0219f8b8a7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fd629807-2c7b-41be-8e1e-eab26c80efca": {"doc_hash": "709fd10c2d7e2ac126fde0dbf4712cc64ff61dfd1f1532785659aeae198d2c38", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a70b49c8-5886-412a-9909-2a57af361fc6": {"doc_hash": "224d266b74f0f211ab68d34c9d97488ff4a976674dc6d519c6641bb4657af42a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "90773e7d-756f-446b-ac97-341f91c6cd8d": {"doc_hash": "0ae312fb9a54b6516664e94ef77cbc1db6dc797247f0337e48a0f578bb3eebb6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1f72fc8-4e9d-495b-95ef-5a1c625fb309": {"doc_hash": "f48f712b7cb4be7a9d5287126f605cb9140d62de96b7e697b9416f71c698eb92", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3d9cb92e-d1d3-4d61-9ec8-a1edbbbb7ce0": {"doc_hash": "eb34768185bd0d6cd20fd4ecb2400575b9fdfba18c6465177b84964c15606ddc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "21896c1a-b697-493f-9ec6-068e55f82e3c": {"doc_hash": "4fb3c817eba1105894a35df03ae032dd00497e18193cb9a699336009d1a87560", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "775db991-96e5-4c81-b422-7edc6d37df8a": {"doc_hash": "681a644e12416963e302fbfc02b6c501bf701bd6c6c2301a74482b6253eea778", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d0514a34-cb7f-49ef-9805-d37f12e0710e": {"doc_hash": "dd22eaf0701d6ed2594100987ca1891a926c8fdb7511cdea65568500b252aee6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5f21811a-0f3e-433a-ae14-02f1c74caaef": {"doc_hash": "493d95f1d28e7dab7c27bde917fca62cb2963eb650de52f5012cf5bd07d119ed", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1c92d4af-dc90-40cf-a557-bdfb63dc4ce8": {"doc_hash": "c5f14421bdf50d15ced03c26eac78802154fbcdb40d5dfb3909a26a3df15551d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0434081-2332-4533-ae32-662e7b74551a": {"doc_hash": "bcef1647b722501fbaf60398a627b2d4823ab659dde665a120480d7aa2a3384e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7a60d185-8cfb-45e5-a794-da7aaf1b8d1d": {"doc_hash": "cf5412f9e4c2941aaa1223551c80c9633dfd493d303d1b9c3c575ffdfbaa0e0c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7184676f-8ac9-44c9-a677-80fa23cef7e3": {"doc_hash": "007ffd504b71b668391abcaf3fa1301a66fdddfbac1db836d47019e55cfdf1e3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0bd08976-3abd-4176-9a94-2f34c3a9f020": {"doc_hash": "dfbf4beb2ab8139c39be16f158abe135ce21e4dda4233f060b6aa454c46b328b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c404cbe3-2dac-410b-8445-7a2d3de78178": {"doc_hash": "b470d103a0f059598a947ddf2231aa16fc93e2ccfd9023aadb6889ac16238f65", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b51d85ae-2c1f-43a3-b1bf-bfe1c30f4433": {"doc_hash": "7d4458a380cb2d6e8dc652b7da7fb915d19ee36554c1b303563fb17e146f8ff0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c5cbb8ea-7756-49ab-8d37-6e0b28eb2e35": {"doc_hash": "f5989cc374abb9b06c8268fa8a980090507e86fe41712d918eb2dfd276e7cd08", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0d805e0a-e9f7-4b32-83be-681e14b0476a": {"doc_hash": "32fc2730662bd55c348ee303aae6735373dbfab11bb28432361f43cc712a3a31", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1b0ee22-7e73-40d2-b685-0f7d82f61339": {"doc_hash": "972036a6d4e0c9aaea7e29bc394aee8d8de2adb5ffe8bcc043637bd5b1536e94", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "825d64b5-8bd2-44c8-9765-1bba4faa0ddc": {"doc_hash": "10bd50d97fdbd9a1b69cc801dfe4a39bcb27b1fe233705530c2570fc9877a7bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a8ffab7c-f34e-491f-81a3-969b7f39ce19": {"doc_hash": "a488786a2ee072bc76ecb432c3163ae88520508a637a4957d254c8d9df0725e2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b4e31807-a78d-4cc3-9f84-5015ff0dae18": {"doc_hash": "3a845e2a83b4129fb979962b5f7e11f5aefb19ead9bf9dc6b4b26b6740381622", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1fa0bb22-6ade-4b0f-a66c-cd24b1300982": {"doc_hash": "8805883448b91a9a669aaba981dc8a16a84755e8c2589763afcecb27607c8da6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "32ac2345-4985-4dd4-877a-ff2959a8d9b6": {"doc_hash": "eb62d4cfe9615bc90c753df56d599fd7943936069d19ba5e278116e12c9fed09", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2d0bff93-13f8-4b98-bda4-cdde6c7af180": {"doc_hash": "39c1f3af8a2d5c33fdb8dc33aa9f2ab1c082bfe5e7bb46993c1b63d0c07bebb0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "15311a2c-b9fe-41a7-adb3-b81ffb855d2f": {"doc_hash": "34d62052ac9c6a55f7c8cb7d3682034a189c065a8ff7e9bc5c4db49cc8d0fc49", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4aa68656-7ec4-4046-800c-d31aeadf6d87": {"doc_hash": "7cadce83987804b9313ebf46131422038511a228ae5ed91bbd3214558c0134e3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a97a3b95-f676-40c4-bdbc-685040931765": {"doc_hash": "850f3b0001c84179cf250144a2fbeabb0439819211bb0d7bb5455074e9fcb48c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "222216fa-abd2-426d-9177-eaf07b21448f": {"doc_hash": "abe4fa752644b642199b863955a2ad74a3c9489c33e8c9c4f599befe1aebc636", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ae71f509-f2f4-4203-803e-4baf38c35e87": {"doc_hash": "69433555791a16ea89f09717378595555a11aa7e57187b4a945494ee7dc962c6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fbe50c50-e101-4ead-b036-bd60fce81ad9": {"doc_hash": "f05206d79a93079fbb2238cf100bcdcc75760bb5be6478431f55ea55cbb4f079", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "169414c7-17c4-4f22-8f67-086fafc89663": {"doc_hash": "8cdfd390393b59fae02fc228ac9721534959375c521c98d4ace919d92bc99b69", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2d1ce43c-b23d-4c37-b162-88d69955c814": {"doc_hash": "87c9a1705e2ab50079e4e5f474631b40d71ae08ed1b4070d6530e54f98e4171a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce5be3b3-5938-4c2c-adb9-c23f925b0bf9": {"doc_hash": "779cd8ff893d7bbf26c018f3794f8d7564cc454ef22c11a63567ab89e172b382", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dfd935ad-6d18-4487-90e2-755c9662650a": {"doc_hash": "cbbe8a6e9b366af0b8e8e843ffd371248f1bd26835686bd8c569ced74fe85f7e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f9c264e6-adae-4ec9-9862-e66d315d4464": {"doc_hash": "437b6ff7c9a43a03b443c47a7056aaa8925d03dbf0c0627b7ad9dc9ea9d60d8c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "36629fb8-d963-4eef-90d1-e0790f676d74": {"doc_hash": "4a34fca4790138bb32aaa5dee04be5582ca8cedbf1bed8c8cd4b510d86d10e64", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7bd72be9-7db4-48dd-b3c6-59268a6f9c01": {"doc_hash": "5c399d408bfa1eed1e0fc0b4c23287be36ac4ffbbbd2af0ccbf73001383065d3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ef37754c-2af3-4fab-bace-b174b3ebee98": {"doc_hash": "d5e90886bac7127b01343fc5a3975ab897e85a39967a2968cd5991ffe2fe8e48", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fa046099-e812-4e4d-8c35-5143c9caca45": {"doc_hash": "32301d9281702e70d8d762b1281b49dcdc9138b31271e9eab5188699667deb66", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0d019d7-cc07-4e51-a797-ba7c9d08bc06": {"doc_hash": "257a008bf302d10e5a4d50d207ab12091287a81dac6840c28c33cfbc3a34891e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2f927671-bdbc-485b-8ca7-e32020558d4a": {"doc_hash": "33a864a4595be6d5ca5d2144d80756eb10e2c892d802e8800627b7363a567114", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9110a870-98a8-4c39-bbd9-cd1f9df9ebcd": {"doc_hash": "ebc3bf165d30d66b700ec6c032a76eafab42ed619f388b4c10f7cb2dd30c25b0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9e725470-42e9-4f16-a3d3-fd748753387c": {"doc_hash": "87989ac9d84b2731624e011b30fa955495eabf51bce40c9eb8f9b12ce77a9bd2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "37b0f419-52e2-48a9-8e48-58d3e60362cf": {"doc_hash": "a327ecc547bd4b7a2ef03e1908e505fd98f1ee412fed1e71699e6266f0bfd7b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7d9c2b76-a22d-4eaf-ab56-6ea5d2810be4": {"doc_hash": "da896c7b5b9cd82b395a3a16dca330df1bbc79e6e8d12b5938641893c22a225c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "80dd32c6-b3b8-4117-8ea6-5bba69ed5151": {"doc_hash": "07c4fb6dd243858ee3748d82d7f230407d7f1afd3a53ffcc7e030626f889f320", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f1cee4a3-60e6-4895-b393-ce6a6355e1fa": {"doc_hash": "b4eef14b6e53d1cf664dcbe8c5e3ef222156da607f19b9863d2f48646b598e68", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "386b7615-6e06-4c6a-9fc8-78807f19f493": {"doc_hash": "789a2f969bd9f0ebb2b071425894fcef0dd2aaa470cc84783d84355bd3fa561c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b4e04e6c-6ed5-4aaa-8279-d8453623b203": {"doc_hash": "2aeccf6d88ee36af1491082500e70f9d74d5c352a7453da76b03b0c03cac01bf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a27a86b3-b6e3-4c23-9496-7930ffbfd243": {"doc_hash": "3dda6b9517614c0fa3dab1004f03b77b0907332baa73e783f8007d3623fe7dfd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8d1f77d9-1082-4918-9027-e3a6e556df29": {"doc_hash": "12eb9a68ca0f6787de1463d1f53db90d9b4865143710fc413d8a5e548b88674c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "daf29cfd-8944-491b-9d79-0e55a170d556": {"doc_hash": "b6de89828578c3014dfd0a9e49ed11f4229d0b14340d016efc185525d8a27cb8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ff4de598-30fc-448c-b5f7-7e11176b9380": {"doc_hash": "18b00851b64603f71abf93b38e5d1ef8745e0ca2fcfdc19262967c2354e0213a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4d81e891-2aa8-4c0e-82c8-6d2b27457eca": {"doc_hash": "c9f490d96f999a4ba4bd92d1c794bf7dd3f2eac47ea55b3f80999729c82ab4da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "77461967-9c4f-489d-a9e3-34f6ef018ec8": {"doc_hash": "0517b307587fdfdc16d48e321f102e0a552b433a6e10c7707e39ca6fd755d55f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "94d21098-8d58-46c4-bf79-5a600dfc9a87": {"doc_hash": "6a6a5127b704d51064c68d6d70518075a028c4b5b44dd64ed69eb0362862bdbc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9db9c519-1a93-4985-b1ea-d89065c6f50e": {"doc_hash": "90678a5bc3c12c2ffaf523d6995b3de06e1c9f3f1afe5621854d87c704da4a5a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "97f7b4d8-ff60-4c55-b574-13354765b508": {"doc_hash": "661766ebe27881a216b0cb38390380e99293573322dc6b67b73de15d7b611c5c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fedc6767-8cb2-43cb-88e9-4d3286e9e7e5": {"doc_hash": "3f531c531f437cfdcb0debdc1553b667d95ab9018974e9fa29f71c4dec4668eb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4569adb4-0a77-4f7b-af02-97ea8b44f642": {"doc_hash": "20fc5204c892a7c5e8e95c32ae7469d9b651f896e93ea3230c7960f510b43989", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5c7def5d-59f8-434e-aa74-eb5d8706123c": {"doc_hash": "9ea267e406b527aed893840752abef4c08683282bc71c8c5def00497ee38c4c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d0ca82bd-a917-4ae7-afc2-cd6f6b184935": {"doc_hash": "28ef56a4f6b36aab6b68dbd7438d0bf6c3036955d907443e39e55374bc131693", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "90306be2-4db1-4f7f-9fca-e47dd38b0f99": {"doc_hash": "30b7b2fbb402f5c472e2320f2edb42f8b754c6c3316e559591e8a5836039a523", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4c23e5cf-785e-4e75-959f-a41dc81992ea": {"doc_hash": "1a7d3753080e14b0d94d441cfc495d2092709bc01df44e0aefa83ebb817eee33", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2a6c0c70-063d-49e3-9e03-a6f255017fc3": {"doc_hash": "2dba7694b487c1ce8cfa86b0d628f781ae9bfde321f3ee6388a63db47f5c57df", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9f5793e6-e763-420c-9564-87e713fcbba6": {"doc_hash": "1a216695e75504ec1644114ada9190e2e385e6c3010bd616af1677eb83334f27", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b142807f-d90e-48e8-85c2-07fb5882001a": {"doc_hash": "0fd9f768598e0bcc1fb5d56201b8b9ae381b6f4c80dc442d2508d26b099feeda", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f81b029b-27aa-4eb2-a5c3-9772012ead06": {"doc_hash": "4d6c7187cbabbbfef52baa4a98bd68aa2bf40d4a8a1a30318d8ba0dc584052a1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8ed4c149-461b-41be-afa5-579527ee6ffc": {"doc_hash": "c5140ee047fb3b509c8d3989690c0fdcea2a862a5eb63c415a4ec40beaf7a2a4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ca613011-ec7a-44a4-a455-2f43c590eeae": {"doc_hash": "e5b939cf7a2a57f2adc7f9be8b834005da201429aabeddfbabf1e260ec5a2d56", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1a99b2c3-d7dd-4f09-bdab-ad95c3c0dfb4": {"doc_hash": "a2bba7cee949fd15ebfe200890b12172d28f13d56e15240f355b30972e19b2f1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3e26e1ec-034f-43ea-bcca-8c9370a524ea": {"doc_hash": "077bb02f4156d447a005abbbea12c69468fb45466db8f77172d856a3d160992b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6032c5f8-1a1f-41f6-9c30-b279bedafe8d": {"doc_hash": "a50eb17b202fff03fffff23fa51457348e3818b3b5b044a63f8cde10c0ca2fe2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6fa5a00c-bc26-4032-83d3-aa34ca5a2d62": {"doc_hash": "1d1cb814d7f3b005ae3733eddecdc9dceb6d2c7538c6e3282488e0bf4a162b12", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9bcceae0-5620-4491-8127-b665af9e55d2": {"doc_hash": "548126aa3a2852df6636424d29766e12d7d68813c94c24df25623f22c52c9b25", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b021559e-aa8c-4cf8-8a0d-242838d45681": {"doc_hash": "f041fc3f23a2e5191f19afc371fa614d09995a3407084163800afe1622c1212c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "47f2cefa-e49e-47a9-aa74-ddeeae3c1c9b": {"doc_hash": "335b39caac5f71a8f27706030240f4ac3d3ead45128b9c3352a4b169f1258b59", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3adda22e-608c-402a-96e1-04607bb8b80d": {"doc_hash": "c410263df57940d74fb41e73c0859bd1265ce1ff3cb9fc89c85f558afa30d54c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "72b25be8-34d3-4b5b-9c73-99ecde994fa5": {"doc_hash": "c8184e83771675a8d173f5bae335e94423a3780086ae6753fa6a5bf793f1bd28", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b54da3d0-0748-467f-844b-b8c96719a70e": {"doc_hash": "2218c3d8f7d3dd5120051563d8fc885522a167fb0272990be40867ac20544e37", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2cf0a685-df60-490f-8309-64ee903f634c": {"doc_hash": "f6581a327aac5ab3cd82e543fb1c18533735acfda361701da027836891dfa594", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a3d5b7b9-79d3-42bd-99d5-16c1e1cd568b": {"doc_hash": "d0fb02f5f134a9b9cc038accfee8d805919dfd14ef993fb50a2829e378fb5a6e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "86e1e508-7388-4aad-a310-fd55a65635fc": {"doc_hash": "d8a09a313a75118a865fb3867e988b8ec0bc30c64b025fe6f635010e80b261ee", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "822d9bee-e135-445e-99f8-de521a2ffd22": {"doc_hash": "bbec4638142cce537deb2605dfb38fb1b88199dee19035e289ffda9a9c70fd96", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e2862153-ffaa-49b5-8c17-344ffe23adc6": {"doc_hash": "145cd6515d0d0faaf15c1a3952739e653a7b3a43743e41697635d048ad83f414", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "52be1aa0-b2ce-49b8-86aa-e6dbf83fd121": {"doc_hash": "79cfc81b4d63814897113eb2cb64ddb78f24dc46f5bc9edcbbf6db470992c2a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7c566499-a1be-4b6a-afb9-284f0d89c899": {"doc_hash": "1eae5dbf7c49ec785ef3cecb2ab512a7d30d95e3ae4b359fc1f3e4718fd40171", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f1bedcc7-ba9e-49f7-a26d-ade796b45a2b": {"doc_hash": "849b55567a3ce31a878e97a3aeaf9fcbde9f0360aed82eed46449c5e0c2efe7a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "af2dabb8-57a6-4d71-b2e1-0301cba5d850": {"doc_hash": "486b833cffbe580bdbf2686a6e1b75d0cb5054f1e9e7d30ba2e1c6f1fa17f8f6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "55a0369e-b6df-47b6-a9a3-afebb27cfbf4": {"doc_hash": "098044685841a498f5858174d18d259e28c35fcf031a3a0120a0ce673410a280", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "93a4917d-4040-4cb7-8043-07e60c40d4e1": {"doc_hash": "cccab51825faf92c7ed176ffa19029a32367896ca39636046abbc5da9c53ab27", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a5f539d1-4bc0-424d-afd6-587ae8be4221": {"doc_hash": "64a17dfff494b47b6bdff9bcbed9dba1756a4ceaf17517312f9bccce8d99ba4b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f3b066b6-6c1b-4123-87f5-1af0094bbfd7": {"doc_hash": "7f31e9f074206071d6b47741f4f1b30086ff8ca182f159e32a7bfa72e2e4ee5e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "57df78c6-1644-4efa-b48e-83b8f3b6341b": {"doc_hash": "afa2dbfba0a702d2016f54df32785de3a3de812e18477e6442d0939ef1dcca90", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3adbef6b-7783-475f-bbdc-db716b238479": {"doc_hash": "21f6d8e816dd8733764028133ae33d278f7462ca32d9ea5e35633b16a0069fde", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ee199967-e3a5-4fda-972e-a8738e8ab1b1": {"doc_hash": "1c096cc4885d4a060a76eba592419ad7932e3b3afd7af69c63d64d664c011bf7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6033585c-0bf3-4c50-94b3-972971fd3289": {"doc_hash": "82f17fb3abc48d641cd217918a041c7363a931dbd4a107fb4a68960ed8f7222a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b7399dcc-8ad3-4efb-8ba7-6b8c1c6fe1c9": {"doc_hash": "d730b4cfa5ed35908df7cc321f0eadc41b7bc175545959d6cc0f25a9dbec0c32", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "affadf83-bacb-4642-b826-30f62fb1909e": {"doc_hash": "6d3391707ccec569f679c8a5ba0ad99e4fed1fdb275dab0bedfc9fe2aa9a7e7f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "167f65e7-6710-4af9-8951-fc037d69b3fd": {"doc_hash": "a21cd1ea77f496fe90901ae7c894b61d307beeeade394e9ab32fd889a7b0a792", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aa24f195-86bb-4f05-8a6c-d0c16fa48ebe": {"doc_hash": "7a6fe714b5a60eb8279d061829afe74104c62fa54cc46c30b75ce1b805a6d3ef", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c2084cb-d6c5-4bb8-a6a9-bf10384ccd01": {"doc_hash": "2dade3fddb250c414124d1bbc1b646606c8b44988e49d1fae3d4990d73fac6ee", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e824c63f-ba0b-4009-83c4-63ffc5035f7a": {"doc_hash": "dadc3c7d4eeac343baf93d927ff589f9cac88224216f9f98a635d83735137c1d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7c2d71fd-0109-492f-875f-ac7194a0547f": {"doc_hash": "6fcb28119af368bdd0ece4b08f208b3e47808b7e54463d635c9954f6d8c6be58", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1317cd63-2099-4a67-8eba-e48c78fbc94d": {"doc_hash": "abb8feb1a2e4534b30359ad14a90ca3c9f384a1307beea945e1d7886709d4c7e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b50e9816-4e8e-4125-829e-ec813b305c66": {"doc_hash": "bac105f8cee031c467b981eaf7b688fdc2b6c4af2bf7cb8edc842148bce7f7b1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7a454318-72e2-4ee6-9c97-b2d74ea26d17": {"doc_hash": "dc09107998cac24d0e2f067aeeb6060577d459e3713ec7f736af44baa6fa87a0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "83b622cc-4905-4091-8666-ad981e9be57c": {"doc_hash": "05a6f0ec4b43a9ea7b0205dbabac540e0658b2fc2db2cb565c5275bcdddc13aa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9be3bc65-9d0a-4e03-885d-bbc9d21c6630": {"doc_hash": "861fd94b327764fd06cfe5db99369dbc4f07629d80fadb555a281a684c82dbc8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5aeef79f-f6e6-4a86-b0a4-e01353e73d3c": {"doc_hash": "29c7d4289703c98fbb1afdc873729ceed85e4bdb82f98047282555c8010c6d2c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5ea20b5d-10c4-494e-888e-3c8d838471c1": {"doc_hash": "a1652f635f1cee3e90233a993b885b5da40d9ed91297deb0347a06da31694093", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ee389c18-cda3-4b72-bafa-48c88fdeb7b0": {"doc_hash": "8f85d78fcecbdfc9f2f5a56b345d57cdd6df4f1e52ad7eb0a562c5d626da89ec", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e321da25-39c3-4efa-a5c4-d893bcfd8672": {"doc_hash": "30de87bee18c9a867b496dd621f7d96ac83c190d8d0de667a986a85f0af22f5d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0d5e431-8de0-40da-aa8e-62b62442b2d5": {"doc_hash": "daca9a4abb0d33e00c34d639a5c2bd77dfd0a7b8f5e9fb2359d84de421cf2797", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c47022ea-26bf-4590-a029-21377c61500e": {"doc_hash": "8d69cdc028399768b2ba8495096d1a98863d746057aafd0224910bcda1115dc5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f23efe0c-48bc-481d-a909-096b5cc02af8": {"doc_hash": "bbc8c3ef27062dae0155ed920d1112a18ea2128890239ba336af5114224fc982", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6a7dedc6-131e-43ea-8916-46de522f1727": {"doc_hash": "4e6933a13914eafd1629deb585fba669ee8d8f08b16760dcd5beee58bb0939f4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7629ef0c-1746-4227-af28-ebf098571af3": {"doc_hash": "13a10253ef4fd60d4f71741e2daece1de1976886f55c47654c546bf0c4c88e8d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "15af15dc-d3c1-4f4a-a5ac-3f56172f2559": {"doc_hash": "d34e20a880d78eac530f36c8749009696c4b412b764f692cec59385dc51a231d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e56f9511-f65f-4409-93d9-10a2424a7f99": {"doc_hash": "f01e3eea7cba3f83134bb9848ad2c10090c696112504c7472ae1baa88aea1ba6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3906fef6-368b-4aff-a8b1-a7834c91230f": {"doc_hash": "04f0f67274d339b7da65f34b50bfd310a997924b597898b9dc945dc1064acd92", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8a9585a7-9b85-4f2c-b104-99145d88e22e": {"doc_hash": "01ac1dd80c888952ed4111fcb19f7a6c63a943c08f8e5385d52a956e9e806ba1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9037b208-55a5-4d6d-afd5-d5d234aa22d5": {"doc_hash": "e26ae6791c9a49f0289f4d74f10cf0958b3e25c840b52942ec146aff4172e294", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8ac0a653-9c5e-4e26-a4c7-c7953bb25321": {"doc_hash": "d3ac1f2f9995459ccb39543cddcf4ed8cf04c809870f4b2f52f4e95e78a07c17", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2092d5a5-43c8-449d-bae4-071748945dc3": {"doc_hash": "8670f3d30e881ea1e296fa0642c686975301ae12fe58219ffb75f666091c1a07", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "80000267-e48c-4b8b-9003-2711e5cef75e": {"doc_hash": "d07ded314b431c2ca89eeb58564d43b916092003bc3e0f740da72481e2238b61", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9f5029c7-6e7e-484d-b960-191da077409e": {"doc_hash": "4b801ddd77446fce13d7cdcc889d34ed781a80a9815a8eac3aa237074fb7b755", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6ee75f07-21c6-41f4-a1e9-c64ff3507fe0": {"doc_hash": "25a1962bd7327cb1fa05bd55f656bf329b9e47374e353bc0a54ae56f901ee145", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3fffa7b4-2484-41d3-b8f4-187f67eee017": {"doc_hash": "dcaed15cf6afab3da4316d5b7958ab7a7bd604d9986e1ad91dec631342e5c79d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0be22626-32f3-41b6-b068-876e8c289787": {"doc_hash": "e6e2876b378a786074b95fb3330566df2065d78530449abaf9b9198505c73cb8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9e149ce0-f777-4131-a208-4b405ba97d40": {"doc_hash": "475f8ca7edd594390db4ce9f8e878d87e3474772b38982d8b095b98563b4ecf7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "13e8fb33-c0f0-415e-b704-6bcde4fd12d1": {"doc_hash": "6c41dc40af3a9d938b4b7010512689419018e6554c4e90b038300c1185f59962", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "715b8143-fbec-4d86-96b1-43cbb1a23f43": {"doc_hash": "8beb29bb28a836844535f104d87b3806658f7b67ab954d45186dadc16205b4f8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "049bae34-fceb-4a7b-a8fe-aec90f4d20ab": {"doc_hash": "b2481f1edc9e444aed8565aebfb8e1f7f74d7030cf9f57c228bdb8dc57312d53", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3397da81-f282-49ba-a0fe-7e42ee636ec6": {"doc_hash": "a81d985bfbaa14df0b017579b72575f1299fedd2348efe8f3cc7f84d2aedf493", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bce953f6-f263-47d7-8545-3a96cadb21be": {"doc_hash": "6ed68784407749efa41bf37c4bb23455aef758b260f4c187ee98c7de30c7049e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4f3def97-00c5-4c89-a34b-9bfba71cfdb4": {"doc_hash": "30630e1a2d5361d88719bf1d1febf0a69a9ada77f8fd3466215256a3a8bee544", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c306fb3c-6bfd-441d-8009-b30762e7d67f": {"doc_hash": "7bfab087b816560504030276391de07adcb4527693f3026dd17f44ce07aa6d87", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ef5b6ead-eac9-4e99-9aac-5104e3c1773b": {"doc_hash": "4f3f224c829369a1582d075a6b29461cfac5e1e4ac04f5a6d8ff5cf6601337ea", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "adcffba2-9c82-46b9-8825-ea4850ec5217": {"doc_hash": "8f2287158335493007c08e435c0f5df8525f7ad44f97833d7393caad491504d3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "174bd342-eaa7-4c92-abf8-e820c672b034": {"doc_hash": "b34bd16687391c78b1f35ef650df82e0ef811c1bbbee538f00e0282111a17001", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6ac63310-917b-420a-a63f-b40a0b90acf0": {"doc_hash": "d577dac02ce7806c887d19c94cff7a16cd1030cd981bc8a06bcc9d77f4bba34c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a56aae3a-2bf0-4363-bca6-d0658e6fd9e3": {"doc_hash": "531f9c367d2aa9ac586a61efa91a7a2f725e6ebffb2c5ca5709ad2495ac91f3b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7b78683f-d6f2-4677-baf3-224c695251b4": {"doc_hash": "0954a35dc08d9b6a743cc7770f23c9917a156d186546d3ce41ecde95d49c1206", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fedfced6-081e-4ae5-b893-31941e2fa658": {"doc_hash": "39eec994d10858393409393d65f80fe570ef010ad1373c1a9621aa77e457fb7c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ac17ad1d-59ce-4b86-b495-dfeb3a1e7318": {"doc_hash": "b7c478c6aeeaddebae2d9f302cafd6679d5b1742d75596a70c56b8fea42e3fd3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3e2c1b45-1b5b-4428-90b1-cd5b28773313": {"doc_hash": "631f3bbc03e667d6c6345e2686c9ff5b3ab2fa9066f52b4130b112dfcc06ff3f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2cb00be1-3df7-42d1-8eda-3c21b3fe2141": {"doc_hash": "a811a2696bfa283c693dc8536a5ac3ac1d144ca9527303ce0d38fd6712a7b0d1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "03b02e0e-3d9f-4f30-8160-b2ec0d834b3a": {"doc_hash": "f503cfda3cf2aeda3f676e613887f7d5c01f5ddd0600cb84b03ed2b6404d615d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2f564c0a-2e17-4c84-b301-98c547af183a": {"doc_hash": "983f28893a6d2596e882a8cb8ce06fe038dac0e2bebfbf5c115502fbf8fb21b4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3afcfd41-a168-44ef-8d2a-9c2e419da3e9": {"doc_hash": "b9eea8c3fbc96e935ca7208a61ee3f1bd4d5460cb4540d6ebcdc878a31510df6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d000dd34-3407-4796-bb70-a179fb434443": {"doc_hash": "add632ec68f6e75e07af20cc3c21c4a52b20419626e8cce51232e8b86159d1d0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "630588f5-6235-4ae0-b92f-263f3e1f21d7": {"doc_hash": "94dd977ae0d6ebcdd9a97182c644616bb35a0c44fa525dd89eb90fe11f602344", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1534091f-8216-42a7-a892-fc7dde7122c5": {"doc_hash": "1597c8ef8f32040b2d7cc17995b1bdcf8fb1c4140924c160f62bf0a8dbdb3da5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ee992121-59f9-4a92-b94b-b991645732fa": {"doc_hash": "1e58aea766a2e783f71e05635f4f9b9c3314f5948965c93b5af92587a26eb6ba", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "538a29ca-e819-4b07-9d7d-b4c861f0e3f6": {"doc_hash": "335cbac7edc2a1be403058c50fb52f924240d3ba572a81e81bec282bd2cb1c1f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "65d14539-b735-46f1-bd8d-85271a303ce3": {"doc_hash": "1547c689dd54bef6a566f7024b90aa9df50a7f556095aeba8b74004d9d5856be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0e99dc9-faae-431a-9246-c859b94cfd67": {"doc_hash": "8b0e058bbe1a53208ce2dbd5749ebb9fef4652d9ebad31ce2d8143165133d13a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "79182757-c504-4a6c-9931-8ead62bc5b9c": {"doc_hash": "07050b7d785e49163877dab7636bd7f37d2a4847f672d1d4ba5bce6be8256650", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c5ec1b8e-ce93-4f7b-aa94-b90fd894c28d": {"doc_hash": "aa208fb28956a2eeff495eecd8e23e52e6154ee67c8d24cfdaffb8bd4059c659", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "48c45174-a95f-4011-8d6e-3e2cc929c3de": {"doc_hash": "03ab9ca8b90e92d7978123d1cd8587c8c4959e7e931d3fffa430f3eebeae7e9a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "78d63f8f-3c94-4d5a-8a65-b8d633b8796e": {"doc_hash": "a836220b2eeb264dce0779c40e0970e95cb88e2fd4f207c6ee6e6601e4e71351", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "79130500-0d08-4894-b56a-ae40f4cad42e": {"doc_hash": "c2743d23b2b5e579bc11272315b7bb896dba0e65f430821dd19460bad3c01c69", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4519878f-c50a-4b88-863b-fbecf29a027f": {"doc_hash": "fc53dae27a2f051aa6c0721bd675dbcb39fc0f010b282b053028f70f77d1f0be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "01f7ea4d-4c0e-449d-a307-441f0b5dd95b": {"doc_hash": "e25fa14917215f31be66a45c589d1fcda2c0a6fa765ac5802d6d1bc4cad05cef", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3a1bf9eb-6dca-459b-9897-433c6cbdc785": {"doc_hash": "6b9a79bde5a1887c6ce088944bbef814a198b5d1866ae04e7cd5d0d10a1a34b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b443e61f-2241-4215-b71d-df3d9ace5b6c": {"doc_hash": "bdba645ae90d8d90a7c9964c5a0709781802ec6480384b522be55374c124e0a2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4e77bfc8-b82d-401a-b264-991feb685479": {"doc_hash": "6978e966341a97a72d0b2b0282c19e4e7c3b8d4e683e086ca68a38a2c92360db", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9201da91-9b68-490d-a192-dd13ff3a5200": {"doc_hash": "c95e5f153013e6bec939bc3d4abde5dfda2bd8601e9cadce65dbd3ae1d6a7a0d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05b33c38-267c-484a-b0fa-8942819b1d6d": {"doc_hash": "f475d5131a733c55634fc1fc2357e0ff0fd60b6cbc99ee49c370d46e485354a6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "faaf76a0-8f55-467e-be30-dac383a95bb7": {"doc_hash": "28487760d0d5872db7ba7f64a6cd8120a163d5ea6fc8ec068bc535ca88b61d04", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "06c352af-a2e6-4ff6-bb1f-321ac66f93a8": {"doc_hash": "0b2e7e801b0f265961d1423052bec17a93c536d1b8dc8bc1503dccfd8fe10832", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8c6b86c2-bb4a-4691-b4e4-658171d9553c": {"doc_hash": "2b34856f7d4bd639058f4896f579cefe2c73d597b4cd6ebe0f0135e43c29ab8f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1095cd00-f714-4cdd-8b33-00fd6608a610": {"doc_hash": "c4f4f0bd286f76ca8fc7fcb3015be27bb1c7eb270e469574edfbfc828fe0d6b7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ff5e6049-da54-47ab-9c4c-367d092dd2fc": {"doc_hash": "f9fba1487114a61b30eb9cd1ebb0aac1edc4d16c29286899c45427e952cd8e48", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a1acdaf6-e401-41d9-b73b-e7f19efdf56e": {"doc_hash": "fd47e3015cf4cd276e3cf4e2df3d5047eeb082191b8fb9247f793cdcd33dad2d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "93be8a50-aae3-48f6-821d-a3a8914a3620": {"doc_hash": "cb1eefb00582aa7a8a43d0621cecb0feb1963e64dd081a18e084b4f535c331e9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "206d4cd0-c604-45a3-aab9-57bc58368f98": {"doc_hash": "f7866a8ffbd7d37b35d8c3c4a0f6f41439637a9a001069cf3dfaff2db97374a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "38f7c6fa-e75d-4cb3-bc7f-e66f205048ec": {"doc_hash": "a7e8f78636edfce562a3f41317422df407f186129a4199df43d6b5776ad079c5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "87b4850a-c758-4fab-9a1e-ecb1b4c63475": {"doc_hash": "5228095da636ddfcc3d687c6f3452adc467f4f512b4aeb832c42ff55208842e2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "96837ef3-aca2-4770-8a35-a45512d8933e": {"doc_hash": "977bafc0145353526f1e0330189554428ad2c7f94d13ddf812dd461cba750aa7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0447c400-ef50-4eba-a24e-705feb56ff1e": {"doc_hash": "85977eab22efdd0c06838c41cd2a59670a72717a776c02ffcf2275c9a12bc7e3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "88967155-702f-4964-8133-c9a222e68814": {"doc_hash": "4025401bf4ab9a4d755154d52f145dd245fc937ad56eb9201dc7c4c76d6f3e31", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b52d020a-5105-44ce-b632-73e4991c6ad9": {"doc_hash": "06456d6d019547897f53d0bb7bae42f88b4ff6e8a36bd0d47a1c34dc175ecfc6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05a54519-9a1d-4805-b2ee-3c0a098017ae": {"doc_hash": "06474db6130cbec9268e40b3d7e934af2db97e74653bdfcc6309d7db437dc9e8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2d72d16b-0afd-43b9-aa08-84ecc6be99a1": {"doc_hash": "82588ab84044419b7e0afcfea42dd24a62e06226e4d82be36d3a7ee83e7a9f0e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b61a1da3-7b9f-4ce8-8a65-ed7970cea39a": {"doc_hash": "6f0b878afb4129f872386c2317094a5a19ed2c6ce71cf41fddab8179a5cad14b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4b413b9c-2d66-4294-bf9a-4a68dcd20f4d": {"doc_hash": "5e8c6e38f38caa669da2d6722129737bb59db01ac266de95cba8b045446bba0a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bce8044d-2c5f-4b47-b940-432934164be5": {"doc_hash": "9987761e514fc8af26979275949586967bc4da283bccd2ce5a5353922b5bac72", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "faddcd63-45a2-4b59-9a15-6001e73bffd5": {"doc_hash": "ee36d810cae7f20d3f44ab1c0f4e2d429893dbd073e11dde7d3d9a3a9b8014a6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bef6ebfd-bed9-4f70-b384-c54cb195f2d6": {"doc_hash": "f20029ef03526483000d3d866803fe190c73f279d9d87cc6e9bfc89202b1485d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "67148d3b-4403-4ad2-ab07-5096f92208d8": {"doc_hash": "60675fd81b9e3d9d367d135a0b8705d99f44bb49c1075e2ab8ed0b477652a6ea", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2ac937e0-730d-4146-a8bb-64157b43186d": {"doc_hash": "a6baede3063c45c348c12a89effb33baf1164a634e91f7be070d81cb4432049c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5274bd39-3b99-4920-98ec-9e789953a584": {"doc_hash": "b92e4579b3557cb3fd4ad3b8c8932e42d828d95d46cc8609ad4647f7f96db3b8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1e3cd361-c2c7-46dc-97cc-426d6e654d43": {"doc_hash": "45d2d4f1f81acdcb75c2bb0aec3cd4885952d0e381d57bdde0f4b229598850e2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f79da0a9-6dbe-4ad8-9d3f-f05677b79c9f": {"doc_hash": "f163e29d50c99363ca5f498a10ff7f89093b359291964e8f5baf1b2d2b843e66", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6b25eea3-a28f-4e50-bb84-fcc5c81e8aaf": {"doc_hash": "154425763aa3f37ce3e247e19adc0fbadb597e68b0eea5682ba470205a1ddc0c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9fc453df-b504-41c4-bb7b-2613ba0a87b6": {"doc_hash": "687b32151f2041a9bc2dde10de786caf595a2f1fff764e85c02e0b2c6fcdad16", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1564fb7a-4f32-4434-9cc1-be8349036cb1": {"doc_hash": "05e6e8fded5589b96b319ae813529073deeaa096821d9a31bf6fc4854ed560d0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c136b88d-3c8a-4069-a91c-d73c9ab3b404": {"doc_hash": "9bc112a0a558a055c1d7c7064d48f5f2f6d8f77dc358fdf2cb64759dff4f0add", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7b2e88a3-7aae-4091-aa22-1e3b5f1e515a": {"doc_hash": "ce5cd3554b0f64ff2bfb8ab2b7d07f5357c3046a2474c8c2ff051b9c494bd027", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aa15c23b-76c5-4903-b338-7dfc2eefb5b7": {"doc_hash": "48de173c7360b152e16b11ffcf5ce0baee32450eb1306e9ba2ba4c8be8e77e00", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "51abb985-1a94-40c6-a410-f054012db61a": {"doc_hash": "8c9801018b31e47c0e996907f127a74084e771e3c2b3d94d475c69886b37d83d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "061676a8-df75-4ba5-b7a3-23bfabc7578d": {"doc_hash": "d90a433285a49f491f9369db1107f022aafa399454dbe5df1c026a77661df2ec", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3dfe4872-7561-484c-a63f-08bcd48373ee": {"doc_hash": "6e50589f7a7e193679cc899862591667b9ff22b27177e6c3c3a8699a08a79178", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2f0550d1-396a-4497-aeb6-47cdac842b64": {"doc_hash": "4ec995e8dc7e44b1686d370e19abc3d4dba9f085588f4e52bcd5c3d3c3c267fc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3bad592e-c66d-45b1-a543-4b31fdf70e06": {"doc_hash": "5c70bcb110673d855d293ae2b24072c447564363aef0ab5a9cffbdc1cb6fa549", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cafc24b1-13e4-485a-ac3c-c0e829b72ec6": {"doc_hash": "27d9bfc2cdd3ee2f7e58a88d94defc47c5b837cd496a509c8c2cf52071060c92", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8444522e-0db6-4b4a-a522-1acc7ce1c06f": {"doc_hash": "bf5b16ff284dfd35ac14ec76a3cf2b8928f65f7f28e4aa8bcb1293f53d3eee48", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c01ac405-99ab-4db3-b9b2-25e9126c146f": {"doc_hash": "8dda3127e270f8aea8c4ef752e3a3a48c99e82979ed63b7e37ffb5edefb94373", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d87ce9c1-154b-4a81-a578-2b44a57d22a4": {"doc_hash": "d755f3146468672e233b18414f99140e22fb9dcc66e57390bc641b40929eed71", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "475248fd-ea07-4baa-9e7e-7cb236118c5c": {"doc_hash": "e4a63d55173d4685f7cb11f0892147ef6b9fc3ea6a984ee5d294efdf69d6449d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "481d6959-d34a-40e6-8d87-7d0852b956eb": {"doc_hash": "444c2acbd1ccb976937ff7c7b48172e880a1bb7f9097dc9280aecf688b243a97", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fa85d8aa-e4f6-4bcf-9748-b8315b30ca50": {"doc_hash": "c7895d3c1d9d9292ecf3b625fd629e2e6bd0657077f17f49b81d59a8779f3f72", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dca2a88a-1d33-4caa-bd52-55dfaa32ff3f": {"doc_hash": "95f87800001c7005afadc14fd81424bb5729f826bec4ccc9d8ebcd5211eaa1f9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c48b0606-a361-4a91-b630-fc839a1dbccf": {"doc_hash": "5f2d3b343793dfbfd887afd23c0c3ea4eb7e89448a886b45141531f9bf8edd4c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "125dad2a-57f3-4e5d-a886-cb1cbd8c0b1f": {"doc_hash": "d5bc8862034887527d8edcccf4131819003662a49e119abe2e73923a067279b4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "da2a1ce6-f83a-4d8f-86ea-d7b01a8dab68": {"doc_hash": "56d0ce4674d0bde01e7b4f1af043f93f400de864928f3f9324687bdc9033425a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "66cf1a8f-dbd4-45a8-b263-6c61310ce5fd": {"doc_hash": "c3c29f9ae5d341e96411d778a047061244ff71d83da300e684eeb461eeb35f40", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aed9630d-49a5-44be-9f2c-cb99cb820ee3": {"doc_hash": "09ae595982bfd9dd4e3e3af9398eeffdb0b4677b4d5dbfb88fa675c55b613574", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "414f6852-3bfd-4d37-88e5-aa657846e5c1": {"doc_hash": "5b7da078e863e7e1aa443da9538d9671d99deabb269f009dc746462ac2b5e7e3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2abefd98-dd29-40b1-9842-8a68658e0e4a": {"doc_hash": "24847aa2971306319d4bb8a8651e26d506739cb8ad04cb5cb6db513313e7a079", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ec206951-3548-4c06-923d-e79cd97e18ca": {"doc_hash": "870906ec8bda2a25d8a4a30dd8dbc5ae2ea36633dfd86179c4c7dac53b2c9587", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05486a00-46c8-4dca-b7ae-e91e04f26244": {"doc_hash": "fc24689021ad3a630387efa7e86879941ef6f5375a425617deb5e46dc1707b8a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "40a75caa-894b-497e-ba59-524b42ad7669": {"doc_hash": "ce1ea4f8af74caf7c6184907d1525c7032d52d2a6eb2c98a7d32f7ffbb67bc68", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e65580fa-7bf3-4357-872f-c2a02717e568": {"doc_hash": "985feeb56c8ee34f1ee42880756f0f34dc63b8af4ccbd8efe6a8b21aa108e30f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ca1ca75d-ee8f-4a6e-88d9-1807e1d74233": {"doc_hash": "826a85ad3db017ab79315a6750609dc85ba91b8531f540e7af23458eb67feb58", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6db48678-b624-4ef0-a167-ce8fafca69fc": {"doc_hash": "c40b1df9ed6de03f65d2421f134fbdb07dbb8c6ca7ccff8ab0958fa457d72935", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e20adbc0-8da5-4f74-a9c7-5ea9729cc8ab": {"doc_hash": "8e6b48e7d4f2a2b177677b26bd31c755122ac6d2bb21b9f677c715a1cf37101c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71c84546-1709-41e1-90e6-90999c05cf2f": {"doc_hash": "9dbc296e19e585f19722aa4f7058d3a0a0120e1c3d6c1076cf6a47613f44cc8d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8af94427-723b-4c8d-bc46-9f6a846e2a45": {"doc_hash": "88b91ad9c01f06c686e220780a14d011595e64dfd8e02581023dde934f774706", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71eb4dc9-b4fa-4737-9bd7-00e6a65eca2a": {"doc_hash": "90afea859e1143091214bd82dcd19a5795118a20fe28bf313d1b96c23e150d9a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3a82bcab-6eeb-4ded-8bcc-8318213c30de": {"doc_hash": "8b51352a6b1ee4c91a10fd2c914247aa1f677144fb18354ec668956759bf32c4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1028524-6f70-4a14-bda9-7b43cb69cd82": {"doc_hash": "ae0625e6aea5e8297754d426640c1978a16905ccf0350f5ad303d766c361974d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "947ee378-0ff1-44ed-97f3-dbd59fb70dcb": {"doc_hash": "7d31ef662094b27b3759ec128d61da67fde23b1f9590e85e515faba1cff1a491", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3cb08652-f91f-4edc-848e-fa0a8640931a": {"doc_hash": "48a09c001d4009a910d82d0765e098736e56ecf7cf68d57fa29defb0a049210a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a2369e4e-7e7e-4ac7-b699-b8a173ca1427": {"doc_hash": "5cccad82ae9926bb31f2aa3a7e498c438d8938ace126fe82beac1d0cf56c7b07", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fb87c860-ea2a-4bb0-b1fc-ab55012cfc5e": {"doc_hash": "4ee8f4fb7a1ccd7823007f47b077cdc1a134230d8f2a5b55f3119410dc2b9e5c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "678966c2-60eb-42bf-b55b-50dae83be8f9": {"doc_hash": "b8488c8d01aac14c259ebef22b70ece1a7c78cb32dc2a91dcbc064a8e8dab0ea", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a56387cd-730f-4164-b697-47d397b20fe1": {"doc_hash": "48243ce20bb1ff69c526c53bf24b7ccefb86b55bc8a7ccaeb17dd850953e9956", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6bc15824-2e9a-47da-be00-eba769033826": {"doc_hash": "6e910cf50b713db44fb78667555827c8fa38d1f45057408e35ebad7677e6ca43", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4a4f5aee-fc33-4805-960a-8d272da05a99": {"doc_hash": "8e4f00768a3d408eec80a3b1ff9889654e272dc5c37891a38e726fb5f0105ee9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f829c9a0-5f72-44f8-a014-4b8853efcc50": {"doc_hash": "becfc4ddaecd573a1b41ae660e2834024afdbe299bc191cfd390f0e39919e337", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "19b1de99-49e3-4f5e-843d-61b1ffa4983f": {"doc_hash": "ea66ce393df247a907f85b3b55de368fcbd43f17180046619224a88f4be099ab", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "63609cc1-eab1-4e6d-ac5a-0043401b23e3": {"doc_hash": "de16eb9a84119e753bfa36c28579769e454f2bc9caeb080aa093de1212997b42", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2eb932c4-3989-4c9f-8c64-fc359a23dad7": {"doc_hash": "fdcda2c583c5ca6b4d224524c8e7e61404a1549c62cb138afa3a25f6d61121f9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b6945583-cf24-408e-aa5e-ff362703c6a0": {"doc_hash": "760b720c66d61a62ead7a37b7fc1fc0d63685a0dba3f849c3220bb50b1193bf3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b86db912-7238-4799-9498-77767f44b160": {"doc_hash": "9a618326dff7bc373f990099a37ccfa6844157a4428dcbb5c0139db4b3994c93", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a6f86858-14b0-402f-96da-3454c978a1ab": {"doc_hash": "e16cf170bd00a2237f99bda41c41d32d581c558686df460454b58e5322e76273", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c0afa827-b7b1-45dd-b9df-c25df3d6af47": {"doc_hash": "b70a7ff67c4b32b1c0fad1e9b07f2cb0c26d200cfc5ee86fcdd434bb738cdef9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e28928a1-c096-483a-a880-bc82a753453a": {"doc_hash": "0b0b2fce8cf25ad32185d759c828cff59eec5fa3428aa6721dffb05ec2afb5b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "72044f95-b275-4a0b-a9c0-1c5478369b55": {"doc_hash": "7b2eb77781080ed19479f00c1d7fccf80477a3c01ef3e121286fd2f872b6a850", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e8515246-fe9e-44df-8d7b-5edbcf54b4bc": {"doc_hash": "d166be37f4a479a70c6b58c31a607911386f9af4cb634bc7bc79d4e2b6eec877", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "19f068c7-bd5c-4866-b3a8-ca8a8cdecd9a": {"doc_hash": "6d526e23e8045e657721e6b73028333367da009dd12a3194967f196d6f510441", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5d443268-3739-4f14-931e-860795a1a1cf": {"doc_hash": "9eaa87f15c2a4b0eaca848cbc899bedb8eb494f156089fb021b26266cb91b8fb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "15c2567d-9723-419b-a744-e1e6f3e45b79": {"doc_hash": "35fe5d38363f7e0e97eac82a30fc2673f61a4a2f84b6f71b78801d41daf148e4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3e963b40-b830-4136-8443-8467be1f8441": {"doc_hash": "bb38c68a81c2ad79109840f92dd95a03f836e257a4033a326c7acf019df81115", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4b95be3e-5738-496b-b9eb-9e3cfe52eca1": {"doc_hash": "49812c8ff42f2cb8f53a3a6a21a694b9bcf8bc21e24e358e838bd6932b356a20", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "48cb7584-b5a6-41f0-b0c2-16fc40a7cbe9": {"doc_hash": "a357c8b8bea1d14420f7be0fa43424e0f66af89eb785004ec9589602a360a0fa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b64977ac-d69e-43a4-b43d-d59d2b2bf6a0": {"doc_hash": "06f5b257ac1ea3c032a8f36209afb8857de062404196d319ed691a8c65239478", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fe84f56c-dc92-4def-bd18-63d7234697b6": {"doc_hash": "9b7a9e1bdcaae5a490b3d129ef09235be04aa84be1326d6936d8b528337f1308", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5120db3b-dc09-4488-8891-88007ed86109": {"doc_hash": "d63c1c46052e71067c2496817a5530a2abb0b6d1617d2253de21e64d91c324a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "767aff81-1ec3-401d-8529-ed436f419467": {"doc_hash": "bf2bf5185032a976e93c96332a588e7a155b1c08378caacc9f46f3047afcb5df", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ac0c48ab-9e45-46f8-97b8-2950438c76fd": {"doc_hash": "13712cd6423770518130d1ad957f5477e6b49ef03fee8fd7c85fe3885c15d098", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a40fbe65-f67f-45e3-a32e-1e59d9b0b18b": {"doc_hash": "cedf5423abc73b511af7dc7c89536c284dd7db7e22e6acb35f6def9ff4493c54", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b8554129-a00f-4725-bf51-6cd2c559784e": {"doc_hash": "b77044eb0dfc6c87b8c065bbec01a3e546f816d973a75497315b5621a1d1e380", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a47f7f9a-50d7-4a8c-aba7-6df1f3b069dc": {"doc_hash": "aae7282375c9ece2044a335f2a8ef7a01c798cd62dceabb6a5ecbc0cc6eec6e4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8ca1e9e1-75a5-4be4-ba6b-dedd2cc6f772": {"doc_hash": "eaf485bb95f2d8e6a3afb80c89445bb1a643343d61b0e6ffc75647285f39aaab", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c4b4b43a-da84-4f4f-bfd9-f677f36ab364": {"doc_hash": "c9707d6236564e9d1153e1a64fafcfc0d7ac4d4582d7e1e7a249e434ed0ea19b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "56afaefd-0176-4c24-ae09-06d71c495be3": {"doc_hash": "9065e20d002dc761be4531c1d49e3a2dd68e6f8596937da61b09582bc37ada28", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "30f297df-5ef6-48d5-bcca-0f7f535f9c21": {"doc_hash": "f8c61a0237984fe621eabe2b74e5682dfd2f33d32bb4f15ebe8055ab26bb9b0f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5ef6ca6a-948d-4b39-b27a-ff163cdcd525": {"doc_hash": "100cc9db46e817e23afdbb200886840b019916f88cf4d0bb0f88073696a921fd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "43c1b7ad-ebc3-4c32-8fd7-26a1fc782574": {"doc_hash": "70a598fc0c33027ef09bdf9b5e91ca463c737eca804554cc1286f39d0b114b2c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "67d0cbf3-7bc3-4f01-bb81-ca5c1411287f": {"doc_hash": "3a28d46f00b9e2a176f668f1bc116985555dface249037f254e80604002c7fff", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "96990cbf-5029-44fb-9dd0-e159a67e57f7": {"doc_hash": "4971432c0ac99f55df7ff1929a0a2dc9ef2167cf9ad2f1aebc65ce55ab2cc9f6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "83a335af-f0b7-44b7-a677-f756860967c2": {"doc_hash": "2acbaafb77fdab25d677706363af7d4a0b696bff0473bb3bbe907fc8d94570b0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b0994640-e498-4735-9eca-77a2c63727ec": {"doc_hash": "d3ac6f6461084b76eb143902e60d2a784055f32ca56bae3a47bbc989a66c7674", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "309940d4-a914-4d0d-8a4c-ca2e3963b1b7": {"doc_hash": "fd5ad108f5be6e0d5bd2e3e5082f96f8389b84e7aea3b8b585c0a40acfdcf16c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "81053dd5-84e6-49e8-853a-d76303d5c093": {"doc_hash": "e7792773b73b08bec6c30f54bb91b2cde43f07642efc4ce96878506d999bc677", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "763c1ffa-213d-4a6c-a3ae-1fe830a34b5e": {"doc_hash": "3cbe9223925647b1e2c69485618d5ba621310f202a462abc3bdd0fc3b402ae51", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6a58f428-b8a8-4d7f-8ce0-1efa9c4236ca": {"doc_hash": "ae97a6f1e27e24c67f517f6927a23f9f82c2e1c1564f10be3387c1827353b2d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5cc99833-a61f-4126-ac38-bc8f9a180af1": {"doc_hash": "590ac80935c8f0d9579dd531734562d0d4959eea59eef10efd4e66345561724a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cca21b32-49ad-4e72-b89a-92dd9367c353": {"doc_hash": "b6c9ee662109032db513c57ae4edc6be334f45178907c5091981086355797a9f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c6660ada-619c-4fc7-b50e-abe82fe92252": {"doc_hash": "d0d9eb85f5de40d5c952f7e7c42b5cc2c70739dd15886c4eaabb76e8323beedc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "390effe9-181f-445d-86e4-19ab069c48af": {"doc_hash": "bd34c6a55fc2dea6af87dfbc8ce4c44ac9677f58047edcc8d27065beea98ad7c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "947ad8de-1d44-41a1-849f-e25c828ddd1c": {"doc_hash": "64a536d151433057d5326f37259ec1c200e6c6e717d5508b9723af11b8090b38", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "11cc7453-5173-477f-8dca-9a21f251c98f": {"doc_hash": "7d5756abedaf3640ff3e58a304ad4122eee181e012254a6168ecfee52a02fa3c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3427c69e-d376-4b23-bd65-7dcd313b9e34": {"doc_hash": "307656a2fa656fe114c876964a61518dba12d4487b655d6656abca504253d9a4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "48299298-01e5-4dc3-bdc4-be12b05cfbb1": {"doc_hash": "2495dab87cca65bd9b6801a47e5040ea5fb91fd173c3ca8cf19b4a53b56b4504", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "000a6608-7202-413d-9426-976c36085d8c": {"doc_hash": "b6c9b60366d87a151c89aa43538aab36e009a1e88c7acde4df72cd9bbcb27e24", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "77660186-bd04-40a8-a31a-6028de2d0184": {"doc_hash": "05a72be1af2bf3e03633966cbf750aa4b6cc903991a38b5e110cddd989008964", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f60df681-e66b-438e-9ba3-a4f9bc9ac5e8": {"doc_hash": "3dfb7ab8688b92732030bf19c94692a9ee2e559eb9aa13f0ecfd153f79f44d2c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2739cb52-a49e-477b-97b8-ccb7b0cc266f": {"doc_hash": "e4b80ea1c2bfcd90f1cc1c498b3790c7bb1a09ba10f2f3658e284ab1e2ff87a1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "186635ee-e4a6-4b0a-a3a5-cf1ea5687cb7": {"doc_hash": "c70ea30edd6508a25f3731951af284a08729eb252b262ca3585711eedfb92ee7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e45399a6-4cc0-4b36-8a9f-219c046c452f": {"doc_hash": "161c2d31bc42346d7b1234de4cc44e4a3bb50bfba8458a914bce74eb2b3c4715", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ff950b2f-39ea-427f-8de2-ed05a8ce39b2": {"doc_hash": "927f66e76834e51f0220425a14eceb49f2087a832fd7d14ebbcf01959dd44c08", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9a9fed04-86b4-40cc-96c0-bc4f1c682b4b": {"doc_hash": "cf97f286ca8a4a5d6fda34d593a3d21b2fac6af4d28965e080fd8f0bd10d11d5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f8d890bd-1755-4d36-a154-6e4aa6171ad1": {"doc_hash": "bf94f4df239d489d80b39fecbdf10cb4dd8dfebc00c73e70940e776e5de63bbf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5d0aca5f-4dd6-421d-83b0-14fdfa0bf17c": {"doc_hash": "ef5400976fa356f50b3455e4f1065bc297014b8e4b08b27fbed1ece37485bb5a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1ac02359-9e79-4316-b592-d789bc1dc200": {"doc_hash": "a98de089e4bafa5114365fe1a7732089e7e4501c9d863c1f7e7f24fb1b87f605", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1d2de813-07ff-4bd3-821b-f8429378d8e3": {"doc_hash": "63fad77286d89939bebc9f63e1eeb42c0ea33c4c26635c4577b35f07d040c03f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d1890b5b-32db-4a9d-a16a-51c11956f22a": {"doc_hash": "3c92924406424b37b2b911cc5d2eae59010e79e98aa411d9a7babf08fa5c1c09", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "21f96d6e-ccbd-4475-b51f-465021b68b88": {"doc_hash": "e2405dcaf70ea9bb8765ff5b1f0f3ff206f4b5a768cb5e5dd3a5f884720c16c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4216794e-cc47-4e4d-a43c-e1f02651e22b": {"doc_hash": "8fec17a8d2fb1fc71eba34c1d0ec8aec4e731d25c8c39e6925ac0e4c33eab700", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8a8b1148-4bce-46e7-9a2d-086ad68be147": {"doc_hash": "dc454e98fdf360d53e0e7082a432eae854938d695177aa2ce15048e1b2e471a4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "782266ce-21cf-4d10-bb7c-2502127ae2d0": {"doc_hash": "751fe32213deddcff02bb1faf3330a52fc2eeb3acc85e223651b230f240e07b3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "77655e50-f641-49e0-9992-a59b164b8984": {"doc_hash": "036e72f091cdc10772cb995dce1718487e44d048205ccd5088bd91bb3a403aac", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "26302ad9-461d-4941-ba00-d0a42e560f91": {"doc_hash": "8d655e68db79e4a3ec3ebb988f882d46e7fcd82fbbb296e39a51ce839eb56a07", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0546a797-6360-481a-be9e-3e2b83ccb371": {"doc_hash": "727beb54a210c5685995dc8a25d5e055c1089c19e66e04471c45e3cf30633671", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9d85f9ff-6479-40a4-89da-658bba7f05f7": {"doc_hash": "b929aa5082d8de5391570ad3bfdae2cee12357242dffcbee58a5ca7872781ca4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0f492d88-1169-4c43-99b3-3549395e062a": {"doc_hash": "0ea6a2326758ad20573eb804c0e21af6b336292103907baa14d58309c46039d0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4047d843-8072-462a-aace-e9215cd8270b": {"doc_hash": "a9b0e26e454499330486c9cb194be8d261f3c8782fd7600d57cd0c4a9f3a8b71", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b6965c88-33a0-40bb-9bba-7a5855d3bc9b": {"doc_hash": "7ed436dfc9b6b9c0ba0c7aef8c021c61ed4440d53a5293670532b93411bbe0da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5605f8f7-055d-4b99-a441-e40aaafa3701": {"doc_hash": "83089e25a12df2b195c3d2be2cf9de6081b83f44c16fa2307ef8147f7057377d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "66f4e90e-dcbf-4421-8483-c6cf5bdf4a53": {"doc_hash": "7f81f591b6b1c93546d7a747253ab8ab8493db9a550fd7835b46fdaf36bb2bed", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5d5691fb-0d01-4732-a642-7e80fdb23400": {"doc_hash": "da9ff9a59f23c481d1d520fdad48bb7f3f9a638c055bf645f7a01e39e38cdfce", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1a1eda7e-64b4-4402-8612-b743245e832b": {"doc_hash": "b25041df44c690c85fb7f40a743d7f61823aa34ef43ea97b8fcab0e44fcb99e7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6855c4ce-2e50-44e1-a9dc-f67b8099207d": {"doc_hash": "c60ff89d9a05df591d5693638a762dcb30fd12fd8b83f0f2d011d416c997d1a8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "22b84708-d4ff-4aaa-bc4d-8e0e29793e46": {"doc_hash": "4953eefe13ad65ccd4e01257e275a1726df11c91ed1a44ca574cf544a38489eb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1bd8c577-2447-4056-a630-e79cab077965": {"doc_hash": "f2a662683a35f359c2dd48d4b40cc4d453aa5e99bef6bfbe658f81b55cb69153", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3ed40846-3d6d-4675-8078-bbb1e937f584": {"doc_hash": "f94e396e9d3cd6985db1f998777f119d8003ef6b8be40a3709952c2ce7e382c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1cceb7c7-b192-4c55-b54b-1fc23148c655": {"doc_hash": "66b3caff718b31e40783e98affc2fa51c2435e542e595750fd3750c37bf05ccc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aebd5e60-cf7b-457b-a181-d932fb333c7b": {"doc_hash": "6042da6a62cb08be3e70ef838fc8a66a89f5e080d0bc6cc86d12cc42e6e29444", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2db687d8-43fe-4fbe-a3fa-6e4fe19045fe": {"doc_hash": "edb004497edd499a110aafe9d797e6436ace61ee2ff95364c05c604c14628f17", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ab66d59c-7db6-4da6-9da5-912afc89b7a3": {"doc_hash": "722a19caf1c3dd8fedcb428adc6354d266636d390a430466ca005730e0f73df0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7dff9e5a-32cf-46dd-916f-11ac3089feb0": {"doc_hash": "e8dcddb9dcf7a650d6106a73297bdfe3b91a462f198dd7017e1bc814df03e9c6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d1ceb261-0b19-45bd-8519-6c972220a697": {"doc_hash": "d7dd84852a647ca61c7b9d88be77c6e34d724262b8eb0e0371700a3e4d3e8eab", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "11c5c9b1-e46d-43cb-84f4-c97212739772": {"doc_hash": "ced09a3141149a48b1577356df8c87c514634a92b5c3441c682c705dd92252c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7a33fec-4d7e-476a-ad31-670972814fda": {"doc_hash": "623cfd0d5577648c796cf1d83a75e771d3ebd35f21ec946f76953a05be1642f8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8c41a810-35b2-4fb1-9265-119835f400a8": {"doc_hash": "b2f24a97822e76f776d8046fab79d35a79fe24fd0c19536798bf922e82e1c416", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc9dbf39-8644-4c8d-9c4b-e67707bcfe53": {"doc_hash": "54c5278f2f8348062d48451137bfac5e150238b51ec9741119dd3afc699c6c51", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "da28c000-c0dc-4836-b958-30ccbd269888": {"doc_hash": "eeac6b0cac35ea426b976d094e1d5157855bcd714c338beacc088dbd91dfbc2b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "91425a1f-b8e0-44a2-84ec-de00f688aba7": {"doc_hash": "6494f4bea37866cb070e7ff739c2714717faaf2e1b4f27239301c55742fe2263", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "eba5c726-0d51-44e2-b31f-6b70447146af": {"doc_hash": "e016be7141c82ae9b9c76ee2e4925660c49a382fb8528eb4bc3c8c12521e941a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7599a51a-955c-4b0c-9012-0d1f5e4224e8": {"doc_hash": "855f5734cc277dbac3b3012a96b05b7a2f5d7953cbebe9774aa7badc99341bd2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e0315451-bf9f-4062-8889-6e79f2e22f4f": {"doc_hash": "1359c2f7b8a97c8a77b1d594a26887afbbb4c3350c861ffecf8157db47730629", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc747a31-0c1f-41bd-b32b-e7c2990b1a79": {"doc_hash": "085b4d8485fa47dc71a76fc5d5388dc0b41543780efcf46d379cffac36f06e7d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9420cf72-0628-4181-922c-ce930c6672d4": {"doc_hash": "fac5e6ce6b97c14f6abeb106eeb9de1eed47a191a1ec8a012575634231a89544", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b2c9ff83-70c0-4123-bc1c-691fcd78b441": {"doc_hash": "25e0595ef323f3a64279e656d2ad6ea20c64d370ba08c1a25a04883641c0b04e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "47523a35-e51d-4d97-bbd4-ed874b190416": {"doc_hash": "258843144ca1a7cd8c85e4caacdf062eed43dffb173de24125c41847e955097d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9dd4d050-062b-4241-a6ce-2d0b4c5f4fee": {"doc_hash": "0b4e615b7ad94f3d97cd3f0ef1dd5aef568566fbe57cea23e15220aaab2cd67c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4ed1044a-7365-4ebe-aa58-e38599af5c2a": {"doc_hash": "788e553b206c4b0701360ac58176bd04f11af7d766005e66bb135600c8e3c878", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d25db95a-4603-4bda-9c8d-7b81becbc777": {"doc_hash": "d8fd6eacd062dfca97503c6cf437ecb48435c428d31d1e179d14b6e3a201909d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0914f5d0-d00e-4514-bc1a-19db5ae65204": {"doc_hash": "f75c94e76020535bd76fdcaf838974b8f9d46312a61d6185a722a679ffc8ab14", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "48f40db8-de93-45e9-949c-302c08f5b1b5": {"doc_hash": "9fd2972b27b21bc18cf35a1404b230d9573dcf98ef2b8851f4f9d8e934333ab9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8e5cc737-31c0-4d97-9ac0-3517851ab9ad": {"doc_hash": "dc16ded32ae31fa94b43ade43da9076cebbcbdc80f454b14a775f390fab27451", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "38d05ab8-c930-44ef-8da5-0efba38dac12": {"doc_hash": "335d2e1894a5283072c0fecf6ef549cc6b4d4cf186d79592d12e62b823bc8ac3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8ec62f04-4351-4698-b7fd-e5febd360b7a": {"doc_hash": "a075b4ee88eb03b49f98b91bacf45a5063cc7c1388b5a6a651dee1dd9ace0dd9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "43231ca1-9819-44e7-9781-7630f34ed267": {"doc_hash": "9f68b2f26b4f4ecd660bb4909ac971a6230142c38dc3474249dcbc4ad13b7069", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71ab3150-af60-4570-9674-69937e43f26d": {"doc_hash": "219d02a966fe3eede8f672a623549683f57c95cb5986a835f3fd4e74b106d453", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "22e9487c-a8cd-47de-9575-c6c3e1429c2b": {"doc_hash": "12c5f72b0c4ec5e2bed80de39d339bcedcfd124dba977394f576d56912de0146", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "27302177-9f64-404f-8ceb-1db3eaaf6ba8": {"doc_hash": "c79f65051c8f2ae62cc8135e210f732474859938b0a193730bc26a1118a2df95", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f5f72e77-5e76-4cd0-a256-d0a4119d59e8": {"doc_hash": "1b321eba003163772596a329a71008eb54dc1303e5dc8d445970ba2a6ffcffcb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "106386b2-b140-48eb-be14-106d850f808b": {"doc_hash": "7e0238fe49046baf1126622355da07e39a2adc60fea603f22dd494fc47faf107", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "001f6cb1-3971-43f8-a178-bda4a9c390a7": {"doc_hash": "da28d8f7a33bcb125864a0abca40f50836e0b170cdc523b42bd8049e1b131719", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a17871c1-ddd1-4000-83c5-cdbd51343776": {"doc_hash": "6952821410a145e83fee2f951f5f87260dfc4b2b33f654b5b6c69eb7924ea97a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d3ffe228-875b-45f1-aace-9a2d42565ff1": {"doc_hash": "6f4ad335588a9be6568d0ed231a5a6513a7d90d495a45668fb2bdeddf2e221bf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "253e4f78-baf6-451a-a4b4-b971fb9d80b7": {"doc_hash": "c0658468419fb4aa6058393dc45669cff8c0b9bea0123c57d2b237dfcd7d5d5a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "66a65767-5e5b-4f5f-bafe-2c3257343ed2": {"doc_hash": "8120e5578fd0f1d689af7955ea824eacd166775d9241ceab888c28d66e0eaeee", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a8768596-a6ed-4267-ba24-425e47ad1f98": {"doc_hash": "2c508f62aab19c578c55e72936702355afb73b7581ad9d643a10d231fb069890", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "680bb00a-4799-457f-8dbb-4aa83f92af46": {"doc_hash": "57de4e1613644aaa324d73ddc88ce9c0f21bc53f45a8f6bbf1f30c9c0fc46de0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6a02af26-b602-441e-bcee-5ba8edb26a91": {"doc_hash": "139a18006365bdbbcb9c10313519e5c7a25822c8e31975e64dd7392a9d63b9f6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "42d2979a-60e9-423b-87b9-b9311463c165": {"doc_hash": "621076291ad689dc113366dd7e752926e4770fab713c4717dec4c92ec91d92a0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c23d9110-1ecd-46fa-8035-f57bb2655167": {"doc_hash": "1683edda29532427f4fb70e687273b59b6bd21b450039d18fabf606b61fdbecb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ecd55211-0c0c-44a8-8f90-bb3d187ec997": {"doc_hash": "44a62ef4b1b4192fdb24d659abc05631f308614c3c3f15fa7599b112d882bae5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "64adbe09-50f0-4bfc-ad2f-2e14b7837eee": {"doc_hash": "32e7f364f6c96288f1e892d4dba70b19641949342b62f0c6a44602c009442fb2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "de907207-2b25-480d-98ec-9aad6f854f8c": {"doc_hash": "fc7d68a981e80929356a868bc627003fb53cc49dd311544b92e0e7eb5ec47bb7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5ed97168-96d2-4e65-8e9e-3f71458e17ba": {"doc_hash": "4f4c5e12e860d2349ebf3b22685db16b7087e54ce87a87f767c980b38f2c8fc5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "abc28c9d-25f6-4ca2-a040-6056e97bbc43": {"doc_hash": "883469247413494ad61011300c0129ab5a7dcc81605d118aed598935f0a21458", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "045ad3b2-6f28-4887-9744-5ee3f68976c1": {"doc_hash": "fcd619432d6514541efbf74fe9dd6fcce738971c2ced3d5d98da17a49fbe72b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4e29d03c-97c3-4885-b168-7d32a0649e62": {"doc_hash": "9260047317df8e1afb3ca327cc293ae7267a2ce82243539387d5f9429456956c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f14b7ef6-9f46-4658-a0c1-32fd078287a1": {"doc_hash": "f58a7f3e45a7a332b4e71e069e2fd6a2c3aa786448e1ed4f26142d444995c0f9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d40055d8-573b-4687-b83a-7742bdb93756": {"doc_hash": "df5fc76ba367328f3bc0cd0a0d37d4959026b9b915fea39cbfcd3b77e43e6b56", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7e51c005-156b-499e-8bae-2a93e25a5773": {"doc_hash": "8f93e5123b9efe871615b9954fc69742a1a13e135852e9d01e73e10f80d8727b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8a08409a-016b-4987-a2ef-39150c57a72c": {"doc_hash": "42ddc4fa76ec7ae254746831b870ecf9df5619dc18a1ac7921b314ebca13b716", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "23adf559-04e2-47a7-9f5c-07cc76596be4": {"doc_hash": "abf40ee9105b47a658c696e36aa43481cfd3757c3f5826bd38208b1abb8c5184", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "16a66f34-318c-4030-b3c0-ddb1edb8d052": {"doc_hash": "fbe422ad6686515196649a6814a7b2304432906716e292cf1adb84f9cc5b1a23", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3583d7b9-692e-4715-93cd-0248f3fda28c": {"doc_hash": "0926ee938328d30151f206f6c7af8ef23a9a5a085a361eff928b33186f2e5216", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c38e818b-e389-4ea9-b503-821e08c36b18": {"doc_hash": "3caab209ac7f0acc3c9f7ac263c72ba1b02852b00f0ee725941fb3a0e194c520", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0db8ec00-bf5c-463c-b11d-0901ed9df1da": {"doc_hash": "403ac5e15945fcc78fb094719e8a3db817b6a4d6bdab61a16159ce43072acdfa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9db70564-c6fd-45bf-b165-32d10808e859": {"doc_hash": "2260a4cd59487d88f661ae3f96bd6148b6c1912afc24c90ea88f020a5c248b4f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ace7abc1-530f-4de0-bc75-39a22b8b1d26": {"doc_hash": "c0d0212c205fe72087c5cde680420c920f7730914bd315562596d9f04930d8f8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d74306bb-ff61-4409-bfae-d49cce51bbec": {"doc_hash": "d63caa12e8f2e51950e1fa55a3f71672501d09a84fbba6dd6cbcec3b9f9b485c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c9bb2c56-8ac2-4aca-aba3-dc785233e1a1": {"doc_hash": "87409d3bf530e7163d0d65fabbdd25ab7b725f7e25484d9ea55945499f365754", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "24c7fda8-a66f-4940-9ba6-c18a3af7d241": {"doc_hash": "23183c74115d42be7bdb9013683dbab433070dd7c916e2b5cd9b3b424bce4e54", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e733891b-cb41-4c46-9a74-5f91a4255ef9": {"doc_hash": "65b9443cb5c3623e13721069357e6ab9758e3f58d3943b639defd1c1d32a2c42", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bdd648af-b11d-4c89-a77b-ead5d3b84678": {"doc_hash": "e84be58c561d79d93abdc47fb38d90b4b92eb5cd4beef5483411c9c522b778f8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ebf095d8-d21d-49b6-99ba-4808a54e306f": {"doc_hash": "a8bd1604a1456b7cc99b18091d787dc2d6fd568c32f22dbb3d2783b27dda4ed5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f3196695-0cc8-4dbe-82ed-c34f05b1ff7f": {"doc_hash": "1130713a127fa62287d2447c3c97b5cb7021c2512c9d64a4bc12412d2fe2576b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "68d9f0a0-e4a0-47e4-9f0a-bd78f4faceca": {"doc_hash": "442fdb70ed43a42a6c148ca3724c44f519b4998d72c54db07379500972c4aa5c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b2041f77-d432-43c5-9ab5-ad0a6ab77075": {"doc_hash": "bb11d8d6cfcf5bc30a264f01a3e8f094c36fe9e8c2bf574c34343c8a47a47fa8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "da7cd779-832f-4061-9d35-8697dbf54c11": {"doc_hash": "69fe9ce2675462ba95a0641c73c06f29064f9174eb8c9aedfac01ae51ee339c0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "04b9f60e-b2b6-4d8b-93f7-441c6dfc37a7": {"doc_hash": "a87984fc85110c02877bcc57f399b029d41a85e3a3e2e4429d28e606bb335547", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8a6c582a-8dcc-4865-b679-820a5215f90c": {"doc_hash": "2f2ab8f0e2b29ca485a9e852b531fe9ffd287338f4c577c7357ccf838e7e3d2b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2c8b3e19-a8fa-483a-971b-97e1c61617be": {"doc_hash": "242349f00600fc65b8f08b342f81f9718cd9d2fedd11115e2035b40ea72a18a5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d2556dc2-44dd-4471-a2f6-7ced1f6efbfe": {"doc_hash": "7b83cf3de5f69803a0f23a918d5fc54c0bdf8ad046bda555cdb126734f331c08", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ba91ed42-d758-49c2-bda5-b0a726bacca9": {"doc_hash": "2658c64b3f500b361772341c7ac60e7c26a089605c621370cd0965748f8949e0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d8b29413-2b25-48bd-ade5-282692ae3792": {"doc_hash": "66633e83d250fbebb24d90016d5b4ea79f1bbfd15ddf3a2cded1fe5cc40b4277", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "21c27682-5955-4a32-a6fb-c04a94cfde8a": {"doc_hash": "b3d1473fe5bc922ae8c8feb09f73b4aebe6288e8600cb9c848a5cb88ede0470b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6b7c00b9-33ee-4694-b87b-b8214dd069f4": {"doc_hash": "5d5624859c4e7e12530cb5dd7668c0e3529450847fdfd2b3f1857f4739e113c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a35ce0ab-ed5d-44c8-91d1-34d0cbd371f9": {"doc_hash": "9e0bbd225fbf34e29b4901bca2245a1b1e4259744f238ffc6964f9d8f8b4950c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e4ecd2f7-dc55-4436-bbed-680adff77d02": {"doc_hash": "f8ee362cf12618ebd4d2efbc40e2f1bd7f34e1a0f6d03f542f075b312c65a887", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e708e432-97fe-45f5-b2be-bc4eda80c4aa": {"doc_hash": "b855f921b6e13eda674bb2524253c3de8296e434b76b32fe5716699786f47d5c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "425bd7a4-d2d9-4269-b2fd-633ac163f966": {"doc_hash": "57463d76e537597e55dc938f5e248df2a29303532a8519c3565cee7b2fd22266", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b5275792-f15c-4c51-ac74-9a2e7e03a2db": {"doc_hash": "e50da2d6d8f2a4ca83f4b0ea88c21563e2b232c4950a3a0b84057218c6836a86", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "53098ff4-fd22-45f7-951a-0e0d6e845a12": {"doc_hash": "cb1b7c09443d65e2af2803d4cbc0ffbf2076ee150433dd63f437e69f380eff31", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9db68e5e-0e74-46fb-993e-4c00810e189e": {"doc_hash": "0bc649b8eff303936fc6d4201448ec14a2a9b224ff58a4e34986d99a96a2e682", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "248ef63e-b5c9-4416-9332-03f522f7e724": {"doc_hash": "54669b952a30f840f54960e30a38eccfe3c8e91d255c7afb822cddcaa7bf9aeb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0e35d1c7-f48a-441d-b481-7511365a8509": {"doc_hash": "58915a2b947bc85bc54180add37ee0a5ff67517a28d98dab4c364370341b970d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "16308e1f-ec6c-4f13-ba43-ea3a6b7d738f": {"doc_hash": "a0b261cf4591471c25619b5425435cb28170f85ef7302fdb0035322e5e632981", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "667a2449-9d8c-46c8-863e-f61427278eae": {"doc_hash": "91567cb7a01ab7263de9f318e99e18142d0de92b0cd0b2b527ca3e9c74a620cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0064312c-4a4b-4f02-9779-5c2e5f5d6e5e": {"doc_hash": "575996d2550d3219b3ed34ec5448a889107cd289e1983880175a1a6e4714fed3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f4bf4c85-9dfa-44b2-b10f-a4b747e39a06": {"doc_hash": "28ca8b1a4fc48950f572175a7100e7c0b6a4e170d22ff6195a8a3859a4773861", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "eacb6c89-dc74-463d-a30e-5df43aff3d64": {"doc_hash": "acf97726d8b52e4d23ad686d457ce7925fe164bc0fbb879b020eef88d9dc4d6f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34b797ef-3165-40c3-8dbd-acfcc557568a": {"doc_hash": "45a8655f91328280bcd03d5dea0984e0e75b17dfb4f1d6325bdfdd8148d37ed3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d50d261f-a209-4ce5-a1ff-d1171c9b28ee": {"doc_hash": "57c34faa557bdc73b183095975245cf0a6340856f4a6990f028a4498216880c3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "81db6315-8432-45e2-8879-5cd91155bcaf": {"doc_hash": "f81430eb631d2b9503b7d3492a5fe9c155e4fc4a3cfe54617b3ecd29a0bca9dc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "41e7cd3e-9ed4-4deb-ad7c-e7467efd2b83": {"doc_hash": "64fe268106a1106bb3471df1acc4363a7bd97ce20cf52d9d18f6b72728e69057", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4fc31684-1bc4-418f-b38a-dc94785046c8": {"doc_hash": "249416772da929c1db6550787220a50d31c6e6466bf90973455cffb36ad84fdd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3649bb31-bd76-4030-82b6-95cadf37ae7a": {"doc_hash": "9aacddc401e0b94d02a0786cd8d974cd5eec9532bf097b870941963d6a619f3f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2597414d-0204-44d5-8eec-d0e8d3404ee0": {"doc_hash": "2d31d42d1aca0c03157c10d193824739fd62b5cea5c8a7f5371ff2d8b7a907e0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "db929336-e5d7-481c-8e4a-21da44be1847": {"doc_hash": "78722f6d87b5c1aace86ba053bd9b12f9e250ad4cccb82eb0ce980d040189d81", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "60fc4b1c-4d23-43cf-b411-19de6829c9a7": {"doc_hash": "a63fac11ec3ba6ef1efc5b444c8cef993a31667cb21e835315412053b3bea7c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "31847507-d132-4d7f-85de-bba84bd473a4": {"doc_hash": "a4f78ead2bb9567c57a6889969fe2ba2d44b2f7c5b6fff7459a22649d3264826", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "813a307d-9a47-423e-90ac-b928e2cba932": {"doc_hash": "feb7b34e953a91a4486e16f19d310d8b6f392c89c749c1fba076c69cee801717", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5418be51-5dc6-4f1b-b529-dcac1409f794": {"doc_hash": "ac7475c19498df5bb5a4d2fe4685d9bda505b3e62fad9b91fb475c13d14640b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1531d2a-4b0f-45ea-990c-4ad55223b1ea": {"doc_hash": "f52365f907a0682f2b511962780fc13cde9a265c55a192ba8ec90ed7ed215991", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "886bae7f-d5e4-4599-9068-149b9aba7cfd": {"doc_hash": "75a575bb018dba250135dd8d640683529989fd624d3959a183ab433d26dca62c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9196d551-02b7-4475-8225-9b5819c83bd2": {"doc_hash": "bcce907b37eaf34446ef4d7231de1c8de95603af7c8238a4a35f19ff832d19d4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b00ef1f1-4b89-4e7f-9469-0cb5636d756e": {"doc_hash": "07d107f1de91a3f3994301b3f63f3d47f34cd13ebcc1b274d3619e7ce8fb6a49", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "981dab3c-a21b-491e-9cbe-bbbad113a603": {"doc_hash": "4e6859de9efee110d53ac2646222000d42738e170b66b3a546d25828a51e2af1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c7871f1d-0db7-453e-8e60-9715e3f5e00f": {"doc_hash": "02adb2ee3bd28b2dde7ff82932ba3acbeca2745b1cd3d2d68be5a705d5580987", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bf9035aa-08a8-4a4f-b733-422df79a6c56": {"doc_hash": "165b49f5a3d713c42e019b1f5ac36c6c0847b0f8df508be42e5bbde32bdeccd3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "23d6206d-8082-4b44-ab59-4ea99d41fc82": {"doc_hash": "3d7d193a008ba5694c126928ab362ed8d7ea3c08be9fbad1ba80178b0d79af7e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c3778740-2ecf-499d-ad9e-2f322f26310a": {"doc_hash": "5731930c339cf7e2d4dfed2d38654c62577179abbacf5cb1bc528091730c1354", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "74bce78b-d6c2-48d8-a36a-7940c0db39ec": {"doc_hash": "83717ce878f86cb3795def20b916ecad276b19e1c84357fe1d6a4578f2ea57f9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9c7e101f-82f2-4766-b22f-a6751e7689ef": {"doc_hash": "08c67c3eb1774123c3cb9561891bd010ecad2ee36c6b755e1a4305f206e04d49", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "045a461d-2d31-46b9-acff-6c32d3caaa2a": {"doc_hash": "3defaf956a045ed9c3e036a0189780af2c5d257aeb045caf36a2b6a8b32f8e33", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "36ac9247-16e9-42ae-9472-fe09961a1d5d": {"doc_hash": "399854569de305b24f2840c822fc90ba09fa47e1363258bab716fbff87f3066e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6446370c-c87f-4702-8ae9-6afc2b12d2c5": {"doc_hash": "7b03d1a102eadfa325196df47bcbbe72efacce7ae41f8e17341263852f9302aa", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "eb66a005-d3a5-4352-8c25-aa47e88e482a": {"doc_hash": "f1a8a2ab7948bc258bd7adb62d86640d2bdc4fa64aaf630f55ba4d34924b705c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "19100ef3-8ef9-4f7d-a7fb-60aed00a1ce1": {"doc_hash": "1763964c9e7bce4fd69f812b816df5b99a1fc5507c5a68f7e3c4aebe90a9fe11", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "486c0019-6504-44fc-8911-9add390eb7d2": {"doc_hash": "d0e486382f2b971377301c0f6a778bbe2fa4364beaa17d45eca32a79dc01f4cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2d52e9cd-5a9e-4e77-a344-26f9698af66e": {"doc_hash": "79091901f6e3e0fe2a6b1750961ea5bb90ceaca966fcaea788317c84058b9796", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1c03e208-3d14-4297-96ea-142888be73c4": {"doc_hash": "1baca2f81a02aaa4dde414a1db4bf9ae3f79d4d7b327db893c2f251b0fa5fb7c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d879cb82-8ebd-46d5-92b0-3af8cc1b01e9": {"doc_hash": "c6802362b224777a1fb9471246c0513f79ae7d0a70a04180abb1c6f4a7d080d9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "996603be-4676-4730-b4d6-e7dbcafd2922": {"doc_hash": "82a2eedd41322ff4f0a1fde0c4c54e88f6d76fcca97fc3ca865024c9100c0551", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f4642ef8-0ff3-4576-aa14-b941443160cd": {"doc_hash": "87d15c5664572293a02689bb5675ee657d7466a44f37a595fdf439111af96e3d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d232f529-5d94-4d1b-9733-c5245b958a1e": {"doc_hash": "e8ac53b339c7fafeebfd15fa4b02b14e63d89f34bebd8fd4626b9f9252494668", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c37036e6-41fb-4683-a628-3ee96908532b": {"doc_hash": "609840f7a9297eeb6b983688a3b6d5b394cf7674a9da0117e6a906a2fe12d94d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9025da05-71f7-4cf2-9fc4-f7ff91537f75": {"doc_hash": "bc121ffacfcdba3f40d1977e15135c665c6fb9a0e2fc5750e5df6ec72ecf8a49", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3e2cf798-fbc6-4928-901b-1aa4c57bc8f0": {"doc_hash": "51fdbc6497ba50be50851b6ef1f4fd160e7bb1934d2d8634eb85114e3d05995a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5abd97ce-f4b6-432e-8e53-680c08d05aa7": {"doc_hash": "b56edf67096e211c1776fbe2619c8bb12dc30f9fec69da3234c317763515b5e8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e76f4752-9984-458b-a40c-59d3710926fa": {"doc_hash": "ed96941d4ff6ceef7629bd976887fb323e5354c33c48a75f32699d77c397f8de", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c08da10b-a26c-46b3-a724-abbb45309992": {"doc_hash": "8270c1c49673d1662b81af70f6058f9cbfd5ad0613861d431f873023fe314b96", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0f61a73c-cc3d-41cd-a030-e5f46a2a7ebe": {"doc_hash": "7b4fbea8cf7f4eb032c93eb1edb0fcbdd2f078ec7a1a8c2fd43abe2104fb03ba", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c3190644-ecc2-4f22-bea2-711608b48ffb": {"doc_hash": "b3e8212c4027c539e65d6ffb08474cfbb6c46e1204354527e1957b3f29185a33", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "953ca428-db89-43b4-b37d-7bb891e7a789": {"doc_hash": "d30e0873e652da4a165710196da0013a7a4b1fa987cd1dd0f47f1bf13aa7ad86", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a4a35d77-349d-402c-a989-55cb4dd1a74e": {"doc_hash": "d853718f44f0980dfdf0a622e6aecfbdb33576cd279de4ab88d8d656fb06b239", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "85cbed95-3a65-48b3-9ab8-741a78ff2dc5": {"doc_hash": "9e4c6f3f590993c2e791e091e91814f369dac7a1aa8441ac69fdc8e2168fc248", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f5368940-59b1-4af8-bcbd-875d313adefe": {"doc_hash": "f43e3747eb0c68cd05c25ef3124b63c21d296211c3b882b178be412cfedaadcc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a72be609-5449-4ccd-9353-56d5015b1483": {"doc_hash": "86fbb351a192c720d02d615b5081be1570f0fd3dd8c72f50f5df5ecbd52c8597", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1fe0c994-054e-4e17-b75a-047b17cf4257": {"doc_hash": "7f0b9a578d86f1819beb0e9fe4ba2f156f0690d065a0834714e4dbb7ca732ef0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "036439f6-28c0-4dbb-b034-d86e102865b6": {"doc_hash": "e42ee67f3164bebce110c0ad711619277ab51accb5cace4dee1af14e26b511a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c356ac83-6212-4ea0-87c5-2a1584ef7371": {"doc_hash": "54cd226634175bd553858afeddea2fab61abb7c9f2623aeee964cdb56bb32af0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3e6d2791-57ea-46f8-a154-f39d7eeca33a": {"doc_hash": "a9f2fba582ed5a5968dcb4a88e182639cdcfdc8e4a9995b7200e49a110381e41", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "be12061d-c339-41d5-a725-b1b761246fe9": {"doc_hash": "28b0f1cd523aca4adfc63e3d17454e20def0a4e65b30216372086efa6be5c976", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "05990626-3785-4ef1-844e-45f999542d2d": {"doc_hash": "5c3740d76b558aa7bb87c51b6a8c693bb415201c7ac856524ae1fe2d02a6a05e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c3079d2-27b0-4122-9ef3-85c815673b26": {"doc_hash": "503bc03b9a9b3604610dd58623d0db3ef52fa95b75ebb9962da00a04cf348ef4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "62aee4e5-719f-4cac-9e2c-1ea5b6de4808": {"doc_hash": "797781efee58935baa1408568e79b993f6aa4141e8b80bf9c19fe1bfad4560f7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "50e5382e-3eb5-4c44-b5d3-64f996be4bd5": {"doc_hash": "d439f22f05458786dc4ba06998cffdc2abba108f82b6f6b881290a050e6f46af", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8317b39b-fd52-42a1-8f79-02a8c4e92988": {"doc_hash": "3ce8fa75960e2fd184f779734c9b6265295f45556f8f16015ea30096726b2d8a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "06c1170c-73d8-4e88-b1e3-00638664879e": {"doc_hash": "a88af526b760c640211bd9ed66cf2a377966fe856aafd6d387f154a3ba920629", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "806437f0-72b9-457a-b683-ba712c14c97d": {"doc_hash": "517204a81ba757ca150c7d58b23df8cc6ba1e602e0590fbe4fa61c2b17af390e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ac832dbe-5943-4694-ab96-02a6d03e2204": {"doc_hash": "49c65a6316df62387df5b7a85eb60e8d4b19f37017436d7075b7a8de4b2c3ee2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "483af7e0-68cb-41c0-a4ec-982c7635c4c1": {"doc_hash": "975a9ffdb38706b9eb1f1d635c54dd1fe2cd47f013501ef0369870a90c8ce4a9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9dee31f6-711d-4562-a7c9-fa2d3e8826e0": {"doc_hash": "c1f0b2082fd10ea734dd3a2cf183b2aadf292448049097a71b3855ea1ec44c60", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "159aea85-dce2-4b86-86ed-6cd3d59b7aa0": {"doc_hash": "5344e064a1942fb7d615ee184156d355f151dd3418c5882436c6b0c62863dd3e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f7175249-330f-4982-a8b6-49e818e46192": {"doc_hash": "f730f96aa9db34697bad60ddf82cdc85ca57ac7252136d69ddca19210333b8c9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b92817bf-e21b-4050-b8dc-3ef0942e8b87": {"doc_hash": "0abadb5b75a56c7379b9f27d58ad6c4955f337ae21dc19f162ee44ba67156f93", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2141f505-6b7c-426e-9e8f-75bea104e189": {"doc_hash": "32da15422e796cf5bc8aca061502cb97824d83a21b489b951f9f32a895a2930d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dd0952fc-0ec1-4b1e-9fcd-34e2edd75c95": {"doc_hash": "836d93ff3bdd45e756dd02b3627b8e0b3fe2388fca5c970811df668b23923fbb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fc05a839-1526-405e-bc0d-c9db68b70a69": {"doc_hash": "41b6524c9a56391a1950706d250979ee771db665ffa17511638d57662dfc2c91", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce4c7308-dfd5-44e8-ac3c-651142fd198b": {"doc_hash": "cc24800c6abd974ca8bbbdb603118f6d994b3ad7a782bb72b3468044505a77da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "38bb51ea-ed38-425d-9d8e-0879484c7244": {"doc_hash": "2675549827e486d9fe3d78e5737fdad8ec89d4eeaade222eb8a8ae8b95eff157", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7b1ef5ac-01c3-48de-8e03-1f1fe1f19f2c": {"doc_hash": "b5d6b3e24e30f9388e37912efe59b115e69398ad36148c3ad57fcdee5f25dd1a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "12bbb73f-c986-4d54-87fd-8eaddb7b328d": {"doc_hash": "f7e633abf96241dae13d45f94d847a687ca27254b4bc729597af6faa3318fa3c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a047b31b-9d4d-4a54-8655-3d6678bb2012": {"doc_hash": "a080805356d8308dbaedc8138f256ef2be8aec2fa6f4b97660c5df8c0d6a2cbd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "36e25f8b-3335-4416-b31d-56463460581f": {"doc_hash": "8da8b0b4acbca4bbe463902ff6b3f5764524768230a3a57031bd6df2e8ba7bc4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "43f35ef4-c925-4805-a9a7-ce4a644fc6b1": {"doc_hash": "5be38965c0e26d54189747d385678187f4112177a8689fcc5438c26edefc3a40", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "140006f4-6fdd-43cb-a206-a6d014a09d52": {"doc_hash": "e2d71fd03c80932bd5760d64a1d1584440d1096b79cc41dfba110062d77aaac2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8376fe5a-a9a9-4f28-84fe-8e4c5f5450f5": {"doc_hash": "1c1742efe88e03741fab3c9c4b3ea85ca61dd73b2f6d5b8a37ceeb468a41aaed", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "53b084ab-ce9e-4f03-b286-cbf5cf6360e9": {"doc_hash": "8fd4aa7e2d7e766088e7cd6cee6e0ab893f5faa9dd43e6f9d717d33be2b09084", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "988dd123-75e2-4b1b-8c20-a291bc8d4bb6": {"doc_hash": "09ba06d32c7d885a68abc3a9b863937473de900f40dd616728be2bed04402dce", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1839e755-9175-4ce7-9cd0-6e45c0ecf866": {"doc_hash": "76734fd9ec3550a287065210edf32d61917495b9c51c912e212ccafb9e453341", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "faa74ab6-88d5-4dfb-9306-7e1e4c50b860": {"doc_hash": "ce8e7b9e428ee36cf13c2b9991fa03cacbbf0b06ab23662a536cdb603c94656a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ccac6340-cfb3-47cf-be69-3f510b738b3d": {"doc_hash": "f80e55d11eb5cb6224acd7b353dfa93a4785fe08134646ccf01b08fb6a3bfd8a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "73ddaeae-8b44-47f2-8c40-b8ee339a6e19": {"doc_hash": "1237f78381ef6066fa998e9b81a5b52e0c604e976c2125fd39b649f0032c3686", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "91263be8-7686-46a6-a603-a32487ddcaf0": {"doc_hash": "c373c25c1f4f61dfb1ab5df7aff5ff6698c455a17fbc4d5745101a8e30297389", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b6a1bc31-92d9-43fc-9a8e-6c76205a2c43": {"doc_hash": "cdf326fe5e216f48b66101ade3fab640a3de099d2f6acdd5027abee7cb035dcd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0e1013dc-a8da-4d06-8987-fa24c705f089": {"doc_hash": "aadefb0370c11ece55c96664fcf32578d6482c07164c95e209d28398b617bf73", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "db277a18-4625-4dc6-b4a8-8730834b4731": {"doc_hash": "abfe0e3634034d6a5d689982d1d8a10617fdf9f9687c137aac349d4234277b59", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6e1a0495-6688-48ab-ba04-a58a789f4e40": {"doc_hash": "ec5694897a9b3e54fcf8572a599533e3c438b30a13532a966bcb0105b4ee4fd8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "51d165a7-247e-4681-8750-306bd9ed4e64": {"doc_hash": "702db71adff7980462d1e09bc977d2c700d431cf5841c285b2b1d4e2526c0449", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "85e3a887-8202-4340-87e7-3976cc669eb9": {"doc_hash": "b029f2f745920ea09002179ee5482600f488a56f59307ce36c4d8afc9400b3d7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9e57d03a-52c5-4ad6-9428-cabbfd7b8afa": {"doc_hash": "72a5987b811c74422e49b690f8b97590f51bca2658c0477e4675e183077691be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e52b9fbe-92c4-4dd1-a6d0-e8f6948d9fa6": {"doc_hash": "b0aff35b9ff03e97a4216d8470b57ab3937519299325fa75ef5e9852a3d72b1a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "42e59f48-8a00-4041-a5ad-40ae1c940b5f": {"doc_hash": "a7a79020ea2495f9eeab9bfe46c1c64dfad23ebd0914c1873d04af4b619103ce", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "57520d17-ccf5-4cce-a0d9-a5ffd5bc6cd3": {"doc_hash": "cb4cb6c33199fe385ff8df1ea2256330a57f54dd1c627db51da70cf7f83b063d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1ffd2b39-c596-41b8-ac0d-1e969954738f": {"doc_hash": "5d7dffa14f0aae9f9628822baccd6ea3994d6594caf1d1e097ac8a7f980f7d42", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cd8f391a-ed6e-4fc8-a165-cb190d33f53c": {"doc_hash": "19e552338bb08321623713de5779be111665e3bca527d5ad177f72b0a7a371c3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34998ad4-e382-44ca-9c55-f632a23b38be": {"doc_hash": "44a701bc2801ba90f0cff53fbc887cced76cab3ff66d094dedbe749b5b0ac874", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a05af080-f08e-4d8a-b40b-903355108fc0": {"doc_hash": "ba65b20a758659259c8c353b87d263cd924abd76ef3529f6f1b11322e9fa42bc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "76f52a40-3497-4f9a-928c-98d8ff168013": {"doc_hash": "e4331aa10085ca5bfb6f4ed24928519a3a12b918e8b1de789abaca013597f848", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "24d04f73-751d-448f-a57a-32fccfb2b9db": {"doc_hash": "ff928dba1eb393f94ab27c77654967a060a8c34554a6190b38860f60e7f99664", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cdff50f6-a834-4989-b9da-0d748ce3549f": {"doc_hash": "e72d472909a5d7ea8834eedf9316f28c4b5cc53058db965df029626bf7cdeb3e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "15c0fe70-9029-4a4a-ace5-e89ff8bb3fa9": {"doc_hash": "dc2630d3a479a7feb5c36453eba5dcf65ec3116950c473b2183874a46b8ab6dc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b6d257b0-a0fa-42d8-890a-05c3a481d19e": {"doc_hash": "c4d50d5792bbdf596e8f03c2004c0f247327959720ed859a2a4872b9ba6fc41c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "45a1f74b-89a7-4fb0-9a0d-97813e384752": {"doc_hash": "ba8e9914e2e804bf23d4bbc5a4bada4cd4a43584e53c1314dd56e7a2ef9028b3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "33f8a5fd-d234-4686-8391-a88fc9fc8071": {"doc_hash": "84ecb7556db64587f8da08a9ae6a996b178c65d18f4fa372bb2c8f2b17fba366", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c49870a4-6f90-4ba1-8284-71f50fc44648": {"doc_hash": "c4122287c30e27e4ac977c0c9b06ce29327810718899d351510e90bbaa31323b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b70c4ece-4df7-4e36-ba13-2a61e8af8496": {"doc_hash": "c855e82bfcd87472d6e47900a2f61168e0054da5368fc4e1ae1999ea522ed277", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a4bfd1df-35c7-4a1f-9f2b-0879aaa72f92": {"doc_hash": "e579d7056499ae6e3790feb03e62f34ccdaef4c7e9358efb06ade3f7641798cf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e9491c64-bd5c-4b01-bc47-965b9a554608": {"doc_hash": "cb99d397d296ce52a41db2692247114660e0e791d99b039f723970a10646e0da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "974cd26e-5d92-4cb0-83c6-a95f6707f776": {"doc_hash": "dab0c2f5e330dee0ba841ab33f5c5fe85a7da91ab5f6b89f56dd622967f2ca73", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "db24354e-7418-4f49-9bef-a9045abc8997": {"doc_hash": "8e3e29b3848ac470ec22c779107a7231dfef301ce7fcd4c018e3fbc9512c88dd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e99628c7-a914-43de-bd30-cc83dc916fd2": {"doc_hash": "fa70fd027ad32139721a02bea322647b25d2821ca4cf358903a6d6af40094f99", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "50a3cbc2-6043-4f42-bd0e-1ef54cb19488": {"doc_hash": "1074aef5cc50df391f507b0c0854f4372a7795bc1196fe4927ba511bec495027", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e15defcf-bc2f-4a6f-aa5f-2fd134fb9cd5": {"doc_hash": "69a4221c7b22ff5135d516e21a7ed86d7bc6fb7e22810127f12dcc5540217ddf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bf18ad90-53ce-418d-930d-65f6f1a0bcd0": {"doc_hash": "f8cff82edd85d718d64388d9712c7e9e6e33e4daad50a6476390ddb8c6632470", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a689d000-6ca2-44d7-8e67-3f47adfcfb43": {"doc_hash": "2d5ed281f04da1ade3b8eae40ee20233d3d160d18470c6d20f72a349ba284920", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "00144e89-5f0f-441a-b0c8-1e3e3995bc94": {"doc_hash": "8c52b927036a01191039ea9050fdeaf2d7256ed184abb57857f32f7b354fea09", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "59572897-d94d-43a2-8325-ba212892feda": {"doc_hash": "87f0f937d2fe5fef4743ee62b328a1786dadb34156f623b01a0f800d45e47f0b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5a5269c6-ec6e-4fc9-9814-3285dc1c8d36": {"doc_hash": "c67cc5b075c42fb0895bf4c9303e29ef5c35e85e93b457eb5b7c4de4754de243", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c78181a-c306-441b-8583-691822a41bf4": {"doc_hash": "36cac6599e540c30df198d2d5be9d3891a45dbf81975811b66198a653bffc609", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0aa6b616-21ff-4e70-89bb-59cbb5ae1567": {"doc_hash": "fa6903554ca39a96145e2cc0ddbfdbf35d362b2f4c18e5e35379b400cfeb0107", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5b828379-8d3c-4430-91ad-8d141ebf4f7f": {"doc_hash": "e6ae5325e7e1ba043578d5ed10bf0ffdac64d3f357665858028ea86981e648e4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5b9c1f39-6444-4579-a3da-bcd5642e693b": {"doc_hash": "567b42ed3b87aabf438eacbfc5ecf89fe1f775af02af76a71b70dc09c40f5a5f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b0cb0d4e-b07c-468d-bd9c-de169917be6b": {"doc_hash": "ef51a73cf71885e0ddb4f66b896f9877a98fcb47a26a8c547e19b8b5f52fc1f0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "813c10e2-0e96-4790-a16b-43762dfd1924": {"doc_hash": "5d0ea923b669ccdfc112b08e5da05e8886a0153a253d811665b92e28741ffac6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "584755b3-219b-4f5a-ad7b-90fcb0f65251": {"doc_hash": "900b84ca4b01b83a7f7db7015c5bb22ef6c054befc0706dd6651b0a2028ee261", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d1bb85ec-7943-414e-98f0-5cd6c7c0741c": {"doc_hash": "26de31de0afe489d8d75d40522e0cb9b9b10fc2084e48ee36d37a620221169da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5967e69c-7a5c-4dd2-8b8e-5af3c138ed2d": {"doc_hash": "f87180bc4cb44cba4f5ff8f93ace316880846085d7f5e014f6d003da68fd5c6c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4651ea7a-c4bd-47ef-aa63-f8306dd2a51c": {"doc_hash": "b6a3a6661486ad0dc02db379990941574c16def62727798beaef88c907131195", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "56b9f13d-435f-488e-9852-47e4c8d7126c": {"doc_hash": "5a8dc95224c3816972655af92e9f68a593503afb369adf601d2890f5240bb8b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b9ca7d85-aa85-4444-a428-a61d46c1dd36": {"doc_hash": "42dd2107f50a5126f985d2de2d2587af2dd7fef58dd46a70f8dec3755aa04c26", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0f0da2c7-e3f2-4ab7-b461-87b0cd46446c": {"doc_hash": "345a5941b4d9b0e22a0f1539a92101f8d2698e51a2d7aeb2ab48a14dd9fa64a6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c7c38912-82a6-419a-80f6-429e33a54db7": {"doc_hash": "b30f99b1eeb6d3bd8badc8d1d60dda331bce9f78ec8bc2131468ddeb15dbef0b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "73afcb45-6b14-42f3-aaaf-21db287ad69c": {"doc_hash": "7f91aba1dc9842c72eb8d479f19c6b8635ee7c4bee28ec82d09158621df23464", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9cbf181b-2938-42ee-8216-d5878852215d": {"doc_hash": "5d4fb677247d87ec801e5503bef1e34f1ba83e6aa3cb5a2e5b8077081f063669", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4ec10542-8263-4502-9a33-e6777a4c864b": {"doc_hash": "4f8474333288598965dcfdb3438ba0d4f49da32c665842211836b80392dfc3b4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c620612-f331-4555-9f1d-890e94d90fe4": {"doc_hash": "d79d89544bd19c4a2a88caa9269fb91f01f5039c622ea8120155677a3b9b97d7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9bb746ca-72e7-412d-a40b-59b749229ca0": {"doc_hash": "646b2e68c5c54ccc70a0c3652ae193b3afd3f51f90a4274aae1fa80a7f24aa20", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f96dad05-c284-40d2-9e9b-3dab4385443f": {"doc_hash": "1c15088a0c5d664a3f1c9692b15d18d3f196d1d4404910b47aa374dbc7e80cbf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "73928e31-c4d0-45d5-8359-58986944f5a7": {"doc_hash": "f5292d754597375b9a60eb5d84c859fc9efb59bab617d504f805af12d7359c4a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "93e55c30-567c-45de-a520-21a3efdf972f": {"doc_hash": "829036ff1e422e400a8308fd5e109a5b6d66092608736f3eeba3a47a58588b03", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2a2a2697-3ee1-4d68-a492-838052cddde1": {"doc_hash": "afea85e775e92b1e048efe98dac30cbb4530fdc0261a56098c00c231d4c1d3d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a75f2a90-1ef2-4d2b-8828-d0a3b156d7f6": {"doc_hash": "3585862c9f76fdccbbd41d93e0e55008f5ad031b6fa6895176c45e3230b20c15", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "24534822-123c-40b4-92af-5798878732cb": {"doc_hash": "20ad2c11c7dcc132c555e5086eeb37a625e2620ff9c78acdcdb65709141b3624", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2791e58b-90d4-404d-8fbf-a9c0b9d7f922": {"doc_hash": "b8d84cd79189f25d26816396766b0cd03113dec54a1aec6d3ff1ebda9c40b676", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c6403cdc-3c1f-4437-966f-351f6ca4502c": {"doc_hash": "7389470049f66d80b0cb90571a67b0ec2a22e87bcb6d842e52cc3f53d20df7c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8036ee0f-0813-495e-bb00-927a2957120d": {"doc_hash": "5f3c1e6db1f470267bea9df77aacf4b8211abca2c57302a4fac64c034b7cd174", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d1595fca-1858-474c-9241-9a8e4ec16eaf": {"doc_hash": "90106b5c4b5fc5f8399eefe7a63023bc619366305bc7d7d9ba17c17aa3cc5f4c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "78e66879-7230-4afe-897c-ee084a19aea2": {"doc_hash": "018faf7ba81f04c537ca10e357c43a8c231c5925a4d2379928f2a16bf3799c6c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bedb5c17-0426-44d2-97ed-727c4dbc6000": {"doc_hash": "7a0279de358bd25fe007bbf382ea6d7dd5a72a3e2970f5fc7f5871414939af2b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3569e415-a56b-4c8a-b86a-861fc8fb176c": {"doc_hash": "8e15b93bef096616643de9fcafd59c93a3ffc2e9d5727270dfffbfc72a08c77b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ccbbefd2-87f7-4e1e-8f4a-3ed7a9414709": {"doc_hash": "3f255bb563b9f18bb55f10a05cb073fb897a8348422ddf85769b53027e35eb57", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d4877d31-5783-4e88-b7f8-7386209924cf": {"doc_hash": "afb5a6ce1d38728a0bff8008a2254f0eea55add1d1f365f86e88ff8a916be023", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5c0bdcda-9b01-431f-8416-1a582e1fdb5c": {"doc_hash": "383a2062ca396ccd247721b5348731d99fa677589fde9027d3d592db02d92f0d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "67e6b7d3-3d72-4b63-8c95-9107c5a906c3": {"doc_hash": "87beda9f2620069e16c99a7682eb21b82d9344674255fd6c1559fa3f415177bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3c49d9b3-1b14-47c1-8229-24c4d7cb5ed7": {"doc_hash": "f3484c0953e27fe200f85a4f8e672ef76d2e77433c6faebe3e3ec7f34908e4da", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9fd27f5b-9868-4174-a4b1-ce43c1be643f": {"doc_hash": "d13d4ada20bf1aff3f583b39ee1e51402ccd8612f40d55c80fe7f553ba7fbbd3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e76ea3c9-7375-428e-aad4-f5f066ca7f32": {"doc_hash": "d2ecac52246964ab5f69eb9bad785a0e96edd4abaec09012ae87d62d365d8207", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "72014f62-55d3-482a-8197-ebb024819a70": {"doc_hash": "69d0c1b8bf9e89e628b10eaec145bfc405e1665913989949e2ea238b80fdbdb7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1499875-ca34-43a2-b152-b09d57a6ac58": {"doc_hash": "eaa91026a3d3cc7d0a37c54697623447c10ade22d5fe061732acd9deec306a2d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "681757a4-813b-4fb9-9f92-9e01a50201f5": {"doc_hash": "5bcd203a3aac5ad9021d8ab8c0988994224b81735e2e18172d96509012b216b7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2c7e4194-0fab-4eec-9efd-1c326aa0b777": {"doc_hash": "f92c305ba27c05db9248529fff14e18fd15e9433fb966453fe6e02b67b8c44e4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bcdeea6a-e4bb-49ca-a491-3775697c5e72": {"doc_hash": "20ffeba7672d818954b3ac2316f14f31dbe98202b1fafeef8bc76626758e7306", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a0960ac9-2508-423d-b53a-b5a8f772d7c1": {"doc_hash": "5a9291d13da54e1f369684d35a7ec56d16856fdd4c0c4ff32b791f3ffbd70275", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "938857c3-d73a-45d4-a4d1-11c5f8bdaeaf": {"doc_hash": "0b74430c742af17aa726524dc14a19655e09753bd990b8488e32368624e41e36", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f8f692ec-0efd-46de-8df1-3a45b2f887d8": {"doc_hash": "eb2dae21b086a3d1ed798efb264d9861adff7c9d12db93aa1df812e4ca2e5c94", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a092dd18-756b-4467-9d44-48510d3e22bf": {"doc_hash": "15c331dc5bb3f2a68adfb278b6d0eafba1fa5bc07394c982bef81d64d26df89d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0ac89fe7-ab93-40b5-80b7-94718959a9b9": {"doc_hash": "199c894a9fa72f523f1220582967a9ed19127bbe204231fa0b72bd8bdd3fb0cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7fdcb17d-2bc9-42df-bf24-105c80a6ee55": {"doc_hash": "e38fc36ff550b76aca9c40721da1e4d8b953e4c86daad3b634e4cfe6994055d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6bf6e923-a934-4311-89eb-647baee3c115": {"doc_hash": "c5737778263df9c7f5af020dc8ff8c2fda95cc0801ef3a602cf845658ac13a13", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bd8c120e-e2fe-4106-8586-1ccfae357dfc": {"doc_hash": "a2f0e5c066ffc642302828170c2211618b61e52ef124ae4167febee9fc35a17f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ea5ea067-d7f1-481f-a82c-a62ca7905c96": {"doc_hash": "592a0791d99abf0234245b0547921dd6405a23e6fbdc117c72afc84dac8757c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d24823ec-4012-4ae6-ba9f-0dfeacb1f087": {"doc_hash": "bde7496098c27c50c29175cfe9bd02dad7e541b6d99ba9e46dbb3010bd3003cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4729ec77-c20b-4c29-a61f-5e6544341bfc": {"doc_hash": "f14792366a76a18c92dd77a171c3f3e2307231bc54819591c76ef21dce5393fc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b9cd2f56-28ff-4764-8c3f-449417d5df3a": {"doc_hash": "b2cfa145b1e89aeccce7809bbbedb6ec0e182c5e4337fb83c77a8b37fc5659f9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d741bdb0-1a61-481b-9470-dcb7d2f9a146": {"doc_hash": "d90ddbabe81ec7060faef009548f2caa6fc58739948e8994b4e92aa684d4d89d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0ba386b5-b581-4105-a3ec-1c22b2efaa3c": {"doc_hash": "7e05132c0a3cb7296452802b3cb2fec8a6a94da75a26f1ff58e5b45c5b2de45d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f79d2855-b614-4407-ac49-9c6c2abdb972": {"doc_hash": "5e4905b71d7bc178de2d76b473dd2d34f0ad5ac18b49f53a1fdd19f1d4e34e67", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "638ed9ee-f501-4a80-b8bc-ec068a943c7e": {"doc_hash": "bf5db1d3f548216332dc701eb34fda3ce36f692fd4189f79166c87f36f06b128", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b645caa9-960b-49a0-a710-6ba66e0f164a": {"doc_hash": "8f9642dcc7ddf7e007c9174e8c10cdd16ba710699cc2f194ab52d3e14504af73", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e872eb4a-4ae2-4812-b94d-9bcfd27177b3": {"doc_hash": "a0e02af9195528cb7a395b0336d39861e6c409324a4a649fbe62d7e1c36a7a63", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b583da9e-a428-4aca-9160-29ba00e06366": {"doc_hash": "da709de4e9b965f154722572ea3116314dc54c60213b8e93693363eb0387e636", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "974a026e-037c-4a09-920c-6abaf54b26cf": {"doc_hash": "d828691ff997f90b3940b56e17d757593ecdab41258a3ff14cf4512bd503908b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1e56b62-4138-40df-aaf5-b57872f3f658": {"doc_hash": "f69519a74daf5dbde0cbe20630cf09bc62041e84b2a3f23626e4c5e1b08b04c7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "174d4890-4228-419f-b0e1-d465f8e99a66": {"doc_hash": "79323450443e2ce0024676578c38799b766ddb0bc3d67dcc14b4a9c67fa64dde", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "90a96e5e-49cd-46c1-8711-ca568b1492ae": {"doc_hash": "b7f2212524f35eeea69fd2409fb9cf61497654f192648dc0c2c9d26f158dc1a3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ac38785b-10fb-451c-83c4-94bb88dd85b9": {"doc_hash": "b0c99a07ca9c90bb87a60d2c7fc17322b6d78f91010a4d88c80028490734058c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3f78cb43-532f-4787-a503-1b144206efac": {"doc_hash": "e45d36bce8fdef32e482efbc6323a053fb97ef198f4f9db4d284c55c42ae32f6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dd01a768-8656-4c3e-afe8-0ee0fcd655d1": {"doc_hash": "105419839b0aac03fe73306f83a1f5c8d8ecba3ebfeeafe75a75a092a2c5f8d7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "831c3f3d-b3f0-46f2-865d-68a51c1479e0": {"doc_hash": "15105aab7c609195b344c9ecc4fe2fd15c8c77222b20975e6c5f578e03d47667", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4b7417ae-d64b-4de3-857b-b80159c8729b": {"doc_hash": "1756ee04aa5a7947ceba7b87bd4920f25578d13bb47224ea2c312c1290aaddf5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a8510e15-5938-4574-bfa2-f59c09c24720": {"doc_hash": "bc1ea4516e91bcf6ce705f05171d7b577580b2cadca472c4ebd6e304920f7a46", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9449a6cb-7b07-41c9-a08d-b2403ae2cd56": {"doc_hash": "d95781138ac139b833ad176e45bf6900d8bcfc247c56fd32b2d9b7853effca61", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "34bb3d3b-b81d-4ad7-86c1-4d82531d8357": {"doc_hash": "bdc60edabf3decf4ca317662978bd7200c5d53f70d438e753329e4181940e451", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "a9cd3974-b3ca-49d4-be9e-1a129071e688": {"doc_hash": "93e71b27d60794339810fb9c190f6ca755a71ecfeb0f370f26ce7dd9a5dba736", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "556d9b4a-480c-4e01-befd-67b343ab47a4": {"doc_hash": "4b075aa159d4531b793de4e13e438792e751f9d46e94cc6670252c88d27cd153", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7ea07c97-a101-401f-8d53-62da562ddb15": {"doc_hash": "320ef3e1f09c371aeb46d5e91c2086d20632f3e0f041be1ac04a386350eb4a8c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d982a7d1-7b44-483c-a0a6-7a666abfb93d": {"doc_hash": "fd3409a9cc0866049043dca05d8661a9547cad46d18445d0d49d8793a47bdc17", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3057ef2b-8ff5-4272-b805-fe636b928267": {"doc_hash": "9f2b135bfb38fab7584afed99f8fd16d893256effe9c4c48177c97aa14b43b85", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4693db18-ba74-49f4-bacd-6cf1626373b0": {"doc_hash": "2c1b5aa0c158931992e6511e32a511093d1cb51fe0a35d2c65718b8ad5a630f7", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "89b31dc2-6a43-4fcf-a6bc-acdec66ef4ee": {"doc_hash": "552ab8530d89d14537be072a5f31b0feb77071fb9eaee0b53df3fe7ee43c4af2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "86027618-8e26-4ff4-b12e-ad9ed4b9f8b4": {"doc_hash": "79f9c1b4f8a2646ade039432af69bc92290ab06e197dc6a04105a117ec48065a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d451a3a0-dda6-4b2a-ae33-afa359c0ca5b": {"doc_hash": "b5878cf9b1cd63d072ddf1c3491a7688985a5f4aed3938584ca12dda6856358b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "45ca0967-3c77-47a5-8993-9a4232e13b19": {"doc_hash": "bcb82b15232e39b2b0086ea55467d66e9298e57efa619f26df1bd152590019a6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2ded2690-0de0-4e04-b0b7-e9071efb3fe0": {"doc_hash": "5c310756d9435ebb96492ea33fcb4f041c46a9de16777bd5611bc1d6c1cd05eb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "456c363b-2a88-415b-9557-973043a2a564": {"doc_hash": "605014b6c177d073ca5db4258e1b1085908a5ca78889471c6ee9064850c9aeba", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1cce2b2e-8118-4760-8a5a-35da1ce27be3": {"doc_hash": "fd12e0d04506508dd8ba8c854ecf44057664b45d0a6af6b98d6e8f4e6f436a1e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "80ea5e02-c629-4fb9-a58a-2f29a437aaa3": {"doc_hash": "c19ec7e7a9cfb73ca6c09d03d1d96b6548559caca4767fdc1adcba468051411a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f5d5d2d8-799e-4c7a-a0eb-2d0d6dda4dea": {"doc_hash": "5b12c95325b65dcb0d5d63ce2cea0c37ec565500169ccbf699b08d0ffed66b60", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "075cffad-6fb6-4894-88d1-8f24952f4138": {"doc_hash": "bea89394126a7bdb040ddfdad28b60bdbbc529cbb4608b8bd75f701660c2bfe5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7f5b1c25-9d8f-4465-ae17-8979cbaa6175": {"doc_hash": "af25eca2c356ed601d251ad9bdbfce53210f8a1f2767c8535dc53920654ecc97", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d2bc43ed-be91-40ab-b1a5-e2301fdc270d": {"doc_hash": "b0562444df64dc104b287bdd36d314161e32439cb8850276f3652246d22f12b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "06ea554c-146c-45ec-af51-7761d7ee206f": {"doc_hash": "8a624dac6097d6728ce2ae585521b002491590031115700a86701aa3526b36b3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d7cc81c8-38f0-4a54-b6b0-728c2f719db0": {"doc_hash": "0e1f93a863c7560af116aff4929981e4efa464a29fa363fe3affd8ed80d294d1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8db971a7-0f30-493a-b4a5-380812af993b": {"doc_hash": "d0b5179618f3591aff370afec773f78a5f30aeebc1977e37116656ee185b8910", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "62944b56-7e18-4acb-af99-1a931358eefd": {"doc_hash": "c658007d43eaec168505a35dca63d1501428eb70e1c70cda46c89af716438984", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0b88b2f5-15f5-4458-811e-ffbc52c3559c": {"doc_hash": "bd6839a87208ea90a4bc777a47de8b557ccc4be7162704268d283c0b2e3d697f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3991509b-9aa0-4a23-9fcc-346bff0372a0": {"doc_hash": "9ef29cbda9419dafb9aa1e3a555550e33066ac1a69dd02a9f5c14785064a461f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "29350feb-f59d-4294-a66e-123c75ad6ac8": {"doc_hash": "2f4eb87bc8a9a62fb18f0e61d17418f4dd2119735769843e83622acb70ebb334", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "88d5f841-e6be-4d4b-9394-fde1d5d05b35": {"doc_hash": "ece31cfa963245aaacd02cefa1bc9cb9be1ecf5fdb9f1420dbef71c119187e3d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e3573a6a-0c97-4fae-b8c6-0810078d3cb7": {"doc_hash": "03dc3d8a02b895fdd6e1552260a12a930e87398cb7326a8031564374f613d419", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6a5dc048-ecd5-4c2a-b105-c3a9e3816a44": {"doc_hash": "e5f29f3665ddd110a9131ed7e0e4d07e95e4664675f5499b1a04405178cc1179", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "106f8f6f-3505-4517-88b9-9e4e89f95ee4": {"doc_hash": "e04952421afc39ffe8addd8d9bb7d12c84e35373890ba17f3f9e0cccf3e4e72a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e17941f9-2821-4325-bb8a-a6ef8e00f2ac": {"doc_hash": "056e8e79fa86fb3f084fbe53b31b4f6c88a3de15be27ca03d6ba0833724f4001", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ce8f15d9-e8f1-4797-a647-777bded18d1a": {"doc_hash": "65af30df546d5c832f3fde2f7080ca7bffb61c2daa6f9a2ae30741733d8c0ecc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ec5e80d5-dcc6-4fcd-b8e9-883d3e4bfaf0": {"doc_hash": "16cd93abdaf9570d1805c57a0c05cf40c886c5bfc4bba7e6e6933f0a69cff68c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e6e1e529-70b2-4995-97e7-aa612a9b7394": {"doc_hash": "bdda8ac130606917e055970d95863e6f4432711d3ee2bc4a7a51f92ff6e7d385", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5f485876-2dd8-4235-b075-4f6cd0a1ee28": {"doc_hash": "b3ba6b1aad39d6e3988f5892540a7e6ee4ea59ac5f4d8db77ff49a51abe8df8e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8437023a-c72f-4b5a-9bec-9e8f71870a88": {"doc_hash": "999f52c0d08c84e7cbd4d1f68d9f04d51f47840c4338480e773157a82d555106", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "20914875-5287-4017-bda8-ff397680c2aa": {"doc_hash": "c0024be2da7aa703212afc188d7ef66856af6e9d0bb830c0620f028a6fd1eb2f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6777f02a-c8ce-4635-b656-c9f666a29d75": {"doc_hash": "1d1f68ca442d9bf539484f9720a208d99e8808124222b374b9fbdbc5a3ead6c8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3f057c9d-0bb4-4271-9118-9b7baa1ab27b": {"doc_hash": "b38a1c6ac60a90156b8f3955eb8d5987f02d1537ab5c42a28de215f32ae795b6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3a87b8d3-9235-4854-9848-a4c9a59cf5c0": {"doc_hash": "bee4c3deceb57596b6023885255e3d2e402bb18b6464482425b2a5ded5ddd115", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "52301843-60f8-4a0e-aa58-7ff6459d792c": {"doc_hash": "dea06b8823e43c6e531434fd7f1763beccd5656f9c7aa6f69030e3f2bd4ee41c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "96a4cd1a-a00a-4251-ad73-a2ba7b92443a": {"doc_hash": "6f7e7409a848c8ed81f82ed338382fea189163c37bb7cac27f3f69a8c2abadb5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "edc5a098-92d3-4c91-ab1f-526b58a262cd": {"doc_hash": "8d5ac3fc18c3ee3be1cf91c1e8bdddec39b411b359dea7564d165ef434bcd533", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "0cb36919-016f-4e17-9b43-459be044fd5f": {"doc_hash": "7e8945aa385842737d8325a347632deaf050f1a4ab9e24fdfb31ba72a534a908", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "69cecb57-f209-412a-9f0a-62b0265c3892": {"doc_hash": "a58ea5bb1eccd1a2485f6af47af6d648c7ca7e1941c001fb475837b43bd09bf2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "32c16a02-1744-42f8-8ed6-4028d40afb40": {"doc_hash": "5a8b5e9ce823fa6c9b7e038e533ba8166f39f5125707ba90a076ee36b5259e36", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "df93f6eb-cb13-4819-a8b0-123aa5603296": {"doc_hash": "3c0aa2a710c02a26e3215c054517d44fe24db7641c1a8840667d7f0e4189ee89", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "55609287-cfe5-4ac4-9a6a-aa2417c116ff": {"doc_hash": "d47677d70e7db6155b73d7bd90ed4210f3cb54af534827bd9d0d7a009532bfa4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "092f426a-49e9-4482-9cb5-7354d2dbe5a9": {"doc_hash": "66ebe96bfaa5b4be2fe4307fa4e2165257ccd2a61f63ad902a045d51f9ea3555", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "82228b95-118b-406e-9fae-d08005309494": {"doc_hash": "9449b785bb80e9cd64aafa10c1a93e7d1bc67447eff4d495e31cec6ce9ca9bbf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "97c76e3a-8fa7-4e96-b197-2f792ac8301f": {"doc_hash": "7cb9e98c198889b3e34f0e41d80569f8baa46d57c1571880f049678bf1a472ce", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4bf9eda9-d53d-47fb-9975-642655f25f25": {"doc_hash": "e6f338a322e2a005adcc87c8f622fb82c7989182fe37c7059d229f07ea44e41b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b88a26c6-e70b-4dde-a6ea-66711dc4b43c": {"doc_hash": "1a78d08c5a2a2868b79229538bed04fbd7591e76c1da978070bc551810496d3f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3192ccd6-4abc-4f3f-8daf-2e920f1e9dba": {"doc_hash": "1c7c21e5a31313fce0b370f64fdc50117cc3cbb11a9bd079ece10fa1ba9126b0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f6871e8e-f078-48e3-8ec4-2ac2e6267d6a": {"doc_hash": "79db52b3b4b7bb75eff6d6761e13dff4b9d7bf2403b4a4c72f845abfc8af553a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4e7553d9-9c5d-40b1-b2f3-83add72bec55": {"doc_hash": "51023b22c7eb2984eb4ef677104bcc3f5e8acd2d881722fe074cb46b5760d954", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e024c975-8bb4-457f-9b90-efed3e561f01": {"doc_hash": "4fbc2e9d0ca44eab8d65f27534676182debdf0d2b061dea685f163564866084a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ac9974a9-ed25-4308-bbed-375935d9386b": {"doc_hash": "1a1cb7f0e60fbef39b858964a53c21787cae5b191acdb527ff7d8b99ae95c8c0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "503f5d7f-c2d6-4f98-919e-cc69ace960e1": {"doc_hash": "13fc9dd6f6d26b147553e766f4571e794bcda38f647e270018947f62ac8b5a12", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "3901e68f-9e3b-4c84-ac14-94398986c2b9": {"doc_hash": "09412c0ca45a15ef22101e455e6a8317a61c8faef59f94b9828c161cf3bf00cb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "7572482d-074f-4eff-86b5-92787676732b": {"doc_hash": "de5f4bef7c089900fea58edf7dc7af11a512c1bec3c6fad09f46f1d1116a16b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9eb13424-bde8-4840-a0ba-171544869942": {"doc_hash": "0b1c161a4db18946b0488e1301dc70794ba6aa4e936557246929882dd8ee521a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "148ac85c-50eb-4473-83f6-675a73eaf64e": {"doc_hash": "73b5a870b74564c43858739b1a118029c3cae84d7f1704c7e0971c05a4515250", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cced59cb-44d6-4db7-8973-9eea13d50115": {"doc_hash": "5fd642f749b3addf9bdf79fb8456515ad4dbb884cbf8f87a672458f20a8d5d18", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "14fbb3bd-9e68-46a0-bd1a-84bfa96932e6": {"doc_hash": "4b0b8c3c1e03bb003518728e0a9710db744ffd6c82ef6eb9feaa35284c42e25d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "13389e96-7e79-4bd1-8f0f-2a6d597f01a5": {"doc_hash": "8ec8c16465cba9ed19a030606c43b2d8899595facea577571e6f66581e7e14e5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ecd53ca3-1391-4ba5-ac65-ca84f8beb345": {"doc_hash": "2151d458e53b9085d639ec71f5148e6b1629559b70b83628c5774f99c824310f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "95ae8d35-4be3-4fd2-91e4-29338e4586de": {"doc_hash": "2118ae4217a989d85154880caf97937a8f78543f232a7e69c136b50b2fca71cc", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "449f8f94-4501-4ca4-b1c9-4a0176084c1e": {"doc_hash": "86598a8c8cce4d6ee7b005162b0f43fe4bbe523ef2fe9955cdbe15da4ec43e7f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5a8f51cb-e301-4044-887d-c6ddfbbe21bb": {"doc_hash": "a28e6ce3764b428ecfb0798e9e74b443fd7495b1e58244281084aaada20ee2c5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "404d6436-a659-46bb-81cd-b6bb4c108d61": {"doc_hash": "6c248bd26d8332a3a85724344273c8c220cbb19a8fb7767119399b4485dc2a55", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b34dc602-aba9-42c0-acbc-680ca38d9c29": {"doc_hash": "a70b690931a9937712d7012e1017b4a5f8c612c1baeb8053cf872175a80e975a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1b18ee40-d686-49d1-b016-4f49d989702e": {"doc_hash": "a306d4c11428ff61959d375519972ff5148d8df369ea84567e88c7145d1ecb4d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "456bc4c0-caba-4b61-8c57-0f23c853c325": {"doc_hash": "6c7c3c46cc2395f43f19d5bffbe1993022678326f0f35e283bded5e11184ad3c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "975cbfe9-fe15-4ffe-aca5-2132a9eccbd0": {"doc_hash": "f82d934cee7e121d760d785c5d963a583e0f54aef45ceffabd025881e3ec353a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b98728dd-cc6d-4e3b-bbdb-89c6564135d2": {"doc_hash": "e1617544c84dee0a15f4055caed8944ff165d38d2065ba81161a17db1abf2e70", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "30614234-0405-4a61-8c54-6e5a8248066a": {"doc_hash": "b93f3eb56122f5f75f7943b770eb7b988420e9cfdfd9a37384267ea2fb14be4b", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f55993db-e6fa-412b-b34e-ac145a31fb3d": {"doc_hash": "f4abf2166391bf0ebb63113447017d9a53d267b9a3312f2b232f28b84984e01f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "fd72f30e-3b27-42bc-8405-2759cf77a3c0": {"doc_hash": "a2be86a2505e869a5e0745c5b9644e1383a1c4e7dedfe9cc45276f59b6e9a7bd", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f458666b-6802-464d-a7fc-1a8196dcb427": {"doc_hash": "34dbedd35edde5c2ceaf324c3aa85b6e4d7ac4a3d75af4cab59daa034dd2372a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e1b66ea9-5e5b-40d9-990c-cb8397348290": {"doc_hash": "82f252a22b38d1cadfc51800d6b53da1e25165b5288b5435cee600f92368c2bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5e2653b3-a362-419c-ac6a-e3b4d1da75e6": {"doc_hash": "6a0ab16e219250221f08a82ec84c154effb19694e7ecb180fe7533b0d12648ed", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8b6052c7-7fb6-427a-9fc8-3a291d23b160": {"doc_hash": "737e500883be4c0711bac6ab05d189756265b310c6a6df7d36e99a83ea961783", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dc9645aa-8074-4f14-bc0d-6cbdd930bf1c": {"doc_hash": "271c070d8a1f1378b809f0c1b9cede2d5f0e479b331d9202b420abe24b2b47b9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "04fadd0f-6b63-4e2f-9026-b269df16071b": {"doc_hash": "dc5c8b497f0401032c13b86901732e7f2b7d111d0cc7aa2b813b1733c0e5a589", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ed08c98c-3051-4faa-a11a-96e4d51e6ac5": {"doc_hash": "4879d5aa7a233bfb7f6920d9467f8e499dc99121ce28883553122c579b6b9af5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "323058ff-3d7d-4085-828f-003e34bef42a": {"doc_hash": "26e66cddb75f653e524166348ce18054bc06031d415234761204ba007cb5b9ec", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c1d8a81a-9e9b-4f96-af57-9c4d61fc35b1": {"doc_hash": "3c01ff98162c1c0a756f30dbf4228aa05d1ae47f34dbcd00598f96725e1dff7f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "4f9394b7-9edc-44b3-85d0-513bd780bd5c": {"doc_hash": "18fa68040419df560240617ee1eeb3e1f189a365a538b2369afb793f04fbcdb4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aff2c8f6-84b0-4907-ac79-93e1232ba57f": {"doc_hash": "4d005df03d04b6f2195c86db03e8f3f16214fd951e150d7c8781fee93f933c74", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "dedeccc2-fb53-4096-a5bb-f184d7beb0eb": {"doc_hash": "2f8645b6f8913e964b0326b138ac4b4fbbe3d2745e530302057240154be65d60", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b3dfb152-d8bc-412d-a81f-79b021046514": {"doc_hash": "d719ac6f36b443ddf615da6d31d04a5f8b0e8d28b7b01aefdd98bedff76d7499", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2f7ce1c3-94e0-468c-97e2-51e5a7a45ea6": {"doc_hash": "22618594bb021a700e6f182ef8e859af7b504f44cd306f8c9157d4702d1de440", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "ad9c1328-5059-43fe-837f-bde8d2ed4e06": {"doc_hash": "1666fc1a79f64c2548ab6059ab182d4662d5e6d5728afbdcaff30adff74cb23f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e710a4de-2f71-47bf-ac32-545d19f392ae": {"doc_hash": "3784c2bb5d63dc2430b6c987b09eb5a0a5f2a2c634f0d0bb593ce8f4a99f833f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "646065e0-cef4-4c9e-a69e-9187e18e22b0": {"doc_hash": "a0d3e1409613ba1146d4a006b5c5af8b50571f7ce1ae079fcf22239a7c773f24", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f9f5ef21-6892-4279-9bbc-0b07d6ee9fa0": {"doc_hash": "86f49823d1bc231daeb01658b529500b049a2f6c54f11c86143d1ae81d7603b2", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "c83e3706-1a49-4f94-b916-41b3419a1261": {"doc_hash": "0c8c0abec7b5c8a17bd4909fa70a4d0309ad03c0d6f16ed35bfbe6bd1af16677", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "d42d685d-b589-47e3-8d02-67adcc472cdb": {"doc_hash": "252b8bf5044c3f654eac09d5f202f3b8d8b7263ab708d5d9b47a67308447ea63", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cfe43c0d-e80e-4d05-8934-a390d641518a": {"doc_hash": "b84cea8c3f0b52256eb80914930f3bdf390951e4175864e2f4857df29d8ef1b5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "499b8f90-f3d1-40a9-b8b6-0bb19a8ebf5a": {"doc_hash": "7e53772bbdbefdb7a28b6bc77c7690e65a4b3644597c0c66d513145029d32fae", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1966f0e4-66e7-46f7-86d4-76997f35dee9": {"doc_hash": "4267f75c4d5f70785003105dda910a122359fa54bacb41832ed67cd2806d20b9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "515369e7-4a85-49b7-8b2a-f7202e2f21ea": {"doc_hash": "bed669c35fc9ab8600999990beedcd95b6bdd0780ac8fa313250871ff262ff2f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6ad73579-dc6a-4310-8f75-2597e2242a5f": {"doc_hash": "2d5fcc856d9a6cdfda05f03ab8296ff82ebb878b4a11fc2e09bdd4686cd8a90e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f3bb7aca-d752-4cf7-9be1-fd2d6c4e0ec1": {"doc_hash": "8cf9c37f74446d5def9db74ede00cb57cfe25f73e67b4f841431f0707973edeb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "351e68ac-3bf0-4a46-a915-59a0d2374df1": {"doc_hash": "b5105e5f7500b3422d17e75170a8b904b7b5900f15fa36247e367ed7e1cb10d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "29c7f02d-3796-4491-92fe-1c585f9e8f2b": {"doc_hash": "7a114d5e1aba31fd0487e3133651665a6af732b3135a8eefb00267aa8816b9d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e6179728-fbf4-4645-846f-e1af36b96463": {"doc_hash": "d408eb6e4f0875260891a4d2f8363ffaf2bf9888324573668bf78ad89fcaf30a", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b9b07785-83ec-4e85-84e7-8edaeb20d0e0": {"doc_hash": "d25609eab28586aebabc6c843008191e2416659de883a9d502a546f45a1767d9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "2111ec83-98f0-4a41-8fe3-c5bc6b5feb00": {"doc_hash": "56f09be1ab195d6c2ff6c792981d31a8f9e42c34951b63c07770ffb2289bf256", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "22c6178a-bae1-4bf7-8df2-7f00dfe98432": {"doc_hash": "cb1cc543345ad5e2a370cd3fbed09047c5aa2224e4480e0d761b13270b6b280e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "081ad426-207f-4a53-bf00-923228c651a0": {"doc_hash": "0aa92f8d3514f6d454fba1faf76d8eb826ee9413af9cdb74cbcb79219c051749", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "46ac44c9-4524-4f94-a6a0-b7236f1106ae": {"doc_hash": "ca3f5b510665e7f9459e81820bdabb238b4531ca4139ccf9a15bac5a38ff04e6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b4f5de82-74d8-4623-a260-fb7726f4ef7b": {"doc_hash": "af773e071251ec5d38c189dc29a22c929930d9756f2e9181b253c2ded843d6d8", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f9ae7e82-b483-4397-ab7d-8091f6c17856": {"doc_hash": "a87e0caa8cbeb7f8b88a3edc9caedfc8dbd4252b176d8a37ca32885c4c3f2bac", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "b77488c8-a55e-4fa6-98e6-d472a0116b16": {"doc_hash": "d3dd7d76f042952b8a5680a4764b0151f9ea27833fe1936167b73e281bfc5cb5", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "5e3f47a7-9902-4888-be33-e3284937586c": {"doc_hash": "87b3f325c32784af09fdb9f472fa8eedd16ddd56830861ec1b5a20c1fa378914", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "40026c82-8d94-4376-ab1d-7253bbdcdf21": {"doc_hash": "ceffcce9a156707cc459c10c694f98a45beaad0828fccc18d8b7a6fa0d0415bb", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "026943cc-2075-4b42-b7b0-0e1a8a9d012d": {"doc_hash": "f387967c25088edea94a0cc56b32c14ba5450c2bfbb7f68e9b397289ebe489b9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "1e7057dc-5d05-4b40-94fe-13bedbfde968": {"doc_hash": "fb80ad9ea8c8379501fe47f893a405f5a00dfd9a4811c0fd9a604a3ca9a81f64", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "75bc8274-b40f-45a1-bc74-a757d6fb745b": {"doc_hash": "603d03e0d7f7ed3541b946a8b5f15ad213a4c091e6e85a1b379a0d7b4e3af88c", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "67ff9938-531a-4a3c-8d79-ff2c1664e3e0": {"doc_hash": "6f6c24a0d8dcda6d7531ea48d3186eec75c08b231c0629bd8684526b620444d3", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "49115b6f-6f37-4d36-806e-455f701f2813": {"doc_hash": "cc86633ca405e1563fa43d8972ac2b276cb101003b601784fe77fceaf1df17d6", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "df8d6fbc-54c9-42b5-9ed8-f365d87ecd8f": {"doc_hash": "349dc3e4b4165a3a29dac81c11ba5efdbaea903821ff1685e0a2a7419976a6e0", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "6f5b6bdd-1ff6-44dd-8a15-28430704c275": {"doc_hash": "14fd1386350bcec549a9ec1f47097090a8c6164a1fef645b8e401b911f11640d", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "152f83d6-9bac-435c-a543-5d8cfc530222": {"doc_hash": "88d7c1bb3579e8b2fac8f973e7bcac45980581c4b18a8900f1e7bed04fad34cf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "aee159c9-8b6a-4140-bd4f-bbacc497f107": {"doc_hash": "c559efab23cc09b88aecf5cc9119ea02810be057588fd207cbedd491ffd28df9", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e70a977f-b705-4649-9b0c-2eec3437f1f2": {"doc_hash": "3a33a77131b17c4a2efee7018482de815c52b556c27d79d9af9db998bfa656be", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "e9ab35e7-dbe0-41e1-9a00-dc42a70042e9": {"doc_hash": "def44bf154afba9652434f9dffb9fcfa2da69659640491b0d2eb18602e068009", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "71a11b33-674f-4d03-ba38-ee4da780d165": {"doc_hash": "a5448745837ff8d3dce1d64504a68ae2746889d33e3e87bded1e7ed0347075f1", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "944f4b86-c160-40a0-876a-dcafe3ba8ece": {"doc_hash": "a02e1da84b88d08d41b79a099f6a7d3d53f05df7aa927ca662b16ed1b427af5f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "bf50d883-9666-47ed-96c0-0e51fdf14b53": {"doc_hash": "855cd81076131deae39f118c63c9fb3abc5c615eb1f45a6c921924a20de92c3f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "257e06d8-fc8c-4d72-848a-3e7a332514cd": {"doc_hash": "a946b2dd8b89ad4aa67d8c81620ce6215cf5e336dad6049c8f8e24314a1bee3e", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "207594ed-6fa3-4d9f-a89b-60006cb33b39": {"doc_hash": "1ee45c5462430a1f1ab4caac7976a57e58e37d270b9b0158f936a56599b38db4", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "efcfbe81-8975-4a93-b642-c057da714e6d": {"doc_hash": "b78319d5835142c8659ad1d4a43659fbd665d21b26e7aa625dc6d6ad5b04d454", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "32a70077-ae54-409a-9458-a499650611b0": {"doc_hash": "9ae042c75ae8ffb90c34f3c6ec56b2e5f07c1fcfc2e1e57397b64fa916a4f110", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "f2428f66-997f-408c-97c8-dcdd027eda8e": {"doc_hash": "82f30e5108a5d2d777419023f34291662d4aea117418f6519595f2d360600aee", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "9fd16349-17db-4153-9780-491a7b14cb5d": {"doc_hash": "451d808d99382d4a13d7774585ee48c2b3059b9bec4be6f61a840defff501adf", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "8e8c4898-41dc-4a4b-9bba-36a2061b8891": {"doc_hash": "33ed61f542a6692131e69c670729c934e1add761df45a3a021210e3db9ef1717", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "92cde42c-411d-4344-adf0-3abfd68f0c0c": {"doc_hash": "af66cf38dc9d62f8c2723cd4a77eca99ed8827329c02a36d341b3a59fb260074", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}, "cd25c083-e856-4329-8c4c-6c6962ae9780": {"doc_hash": "7b44e8ec52be6db7d72746127d05a880848226685b198229059dc5e171faff0f", "ref_doc_id": "87e184ca-9a81-4558-ae8b-60c96e312094"}}, "docstore/data": {"e0e6979e-8a6a-4c5f-b82e-5186805f23e5": {"__data__": {"id_": "e0e6979e-8a6a-4c5f-b82e-5186805f23e5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d65d4d81-9002-465f-8c7d-920c2b9f81db", "node_type": "1", "metadata": {}, "hash": "f4f653753036a2756502d61822c83c79407f796b3f9df0105b9f7bc8f3d377db", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Developer Guide for version 2.x\nAWS SDK for Java 2.x\nCopyright \u00a9 2024 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAWS SDK for Java 2.x: Developer Guide for version 2.x\nCopyright \u00a9 2024 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.\nAmazon's trademarks and trade dress may not be used in connection with any product or service\nthat is not Amazon's, in any manner that is likely to cause confusion among customers, or in any\nmanner that disparages or discredits Amazon. All other trademarks not owned by Amazon are\nthe property of their respective owners, who may or may not be affiliated with, connected to, or\nsponsored by Amazon.", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 732, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d65d4d81-9002-465f-8c7d-920c2b9f81db": {"__data__": {"id_": "d65d4d81-9002-465f-8c7d-920c2b9f81db", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e0e6979e-8a6a-4c5f-b82e-5186805f23e5", "node_type": "1", "metadata": {}, "hash": "592359f7fd1879cd2a559e9f0729446fb7e8e9adccdcf3397cb01d4ff594e44c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9828bafc-474d-4158-8726-abeef5a5924c", "node_type": "1", "metadata": {}, "hash": "74faaa3c902833306ea64c2a49b87f8e25d932bb97b110ebb6bce877bd2353bb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Developer Guide for version 2.x\nAWS SDK for Java 2.x\nCopyright \u00a9 2024 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAWS SDK for Java 2.x: Developer Guide for version 2.x\nCopyright \u00a9 2024 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.\nAmazon's trademarks and trade dress may not be used in connection with any product or service\nthat is not Amazon's, in any manner that is likely to cause confusion among customers, or in any\nmanner that disparages or discredits Amazon. All other trademarks not owned by Amazon are\nthe property of their respective owners, who may or may not be affiliated with, connected to, or\nsponsored by Amazon.\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTable of Contents\nDeveloper Guide - AWS SDK for Java 2.x ...................................................................................... 1\nGet started with the SDK ........................................................................................................................... 1\nDevelop mobile applications ...................................................................................................................... 1\nMaintenance and support for SDK major versions ................................................................................ 1\nAdditional resources ..................................................................................................................................... 2\nContribute to the SDK ................................................................................................................................. 2\nGet started tutorial ......................................................................................................................... 3\nStep 1: Set up for this tutorial .................................................................................................................. 3\nStep 2: Create the project .......................................................................................................................... 3\nStep 3: Write the code ................................................................................................................................ 8\nStep 4: Build and run the application ................................................................................................... 12\nSuccess .................................................................................................................................................... 13\nCleanup................................................................................................................................................... 13\nNext steps .................................................................................................................................................... 13\nSetup.............................................................................................................................................. 15\nSetup overview ........................................................................................................................................... 15\nSet up authentication ............................................................................................................................... 16\nSetup for single sign-on access for the SDK ........................................................................................ 16\nSign in using the AWS CLI ....................................................................................................................... 17\nInstall Java and a build tool .................................................................................................................... 18\nAdditional authentication options .......................................................................................................... 18\nSet up an Apache Maven project ............................................................................................................ 18\nPrerequisites........................................................................................................................................... 18\nCreate a Maven project ....................................................................................................................... 19\nConfigure the Java compiler for Maven ........................................................................................... 19\nDeclare the SDK as a dependency .................................................................................................... 21\nSet dependencies for SDK modules .................................................................................................. 21\nBuild your project ................................................................................................................................. 24\nSet up a Gradle project ............................................................................................................................ 24\nSet up a GraalVM Native Image project ................................................................................................ 31\nPrerequisites........................................................................................................................................... 31\nCreate a project using the archetype ............................................................................................... 31\nBuild a native image ............................................................................................................................ 32\nUse the SDK ................................................................................................................................... 34\niii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWork with service clients .......................................................................................................................... 34\nCreate a service client .......................................................................................................................... 34\nDefault client configuration ............................................................................................................... 35\nConfigure service clients ..................................................................................................................... 35\nClose the service client ........................................................................................................................ 36\nMake requests............................................................................................................................................. 36\nUse requests to override client configuration................................................................................ 37\nHandle responses ....................................................................................................................................... 38\nHandle exceptions...................................................................................................................................... 39\nUse waiters.................................................................................................................................................. 40\nSet timeouts................................................................................................................................................ 40\nExecution interceptors............................................................................................................................... 41\nConfigure SDK authentication ................................................................................................................. 42\nConfigure access to temporary credentials ..................................................................................... 42\nDefault credentials provider chain .................................................................................................... 44\nUse a specific credentials provider .................................................................................................... 46\nUse profiles............................................................................................................................................ 48\nLoad temporary credentials from an external process ................................................................. 51\nSupply temporary credentials in code ............................................................................................. 56\nRead IAM role credentials on Amazon EC2 ..................................................................................... 59\nUse AWS Regions ....................................................................................................................................... 61\nExplicitly configure an AWS Region .................................................................................................. 61\nDetermine Region from environment .............................................................................................. 62\nCheck for service availability .............................................................................................................. 63\nChoose a specific endpoint ................................................................................................................. 63\nReduce SDK startup time for AWS Lambda ......................................................................................... 64\nUse an AWS CRT-based HTTP client ................................................................................................. 64\nRemove unused HTTP client dependencies .................................................................................... 64\nConfigure service clients to shortcut lookups ................................................................................ 65\nInitialize the SDK client outside of the Lambda function handler .............................................. 66\nMinimize dependency injection ........................................................................................................ 67\nUse a Maven Archetype targeting AWS Lambda ............................................................................ 67\nLambda SnapStart................................................................................................................................ 67\nVersion 2.x changes that affect startup time ................................................................................. 68\nAdditional resources............................................................................................................................. 68\nHTTP clients ................................................................................................................................................ 68\niv\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAvailable clients .................................................................................................................................... 68\nClient recommendations ..................................................................................................................... 69\nSmart defaults ....................................................................................................................................... 74\nConfigure the Apache-based HTTP client ....................................................................................... 75\nConfigure the URLConnection-based HTTP client ......................................................................... 81\nConfigure the Netty-based HTTP client ........................................................................................... 87\nConfigure AWS CRT-based HTTP clients .......................................................................................... 93\nConfigure HTTP proxies .................................................................................................................... 106\nException handling.................................................................................................................................. 111\nWhy unchecked exceptions?", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 12330, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9828bafc-474d-4158-8726-abeef5a5924c": {"__data__": {"id_": "9828bafc-474d-4158-8726-abeef5a5924c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d65d4d81-9002-465f-8c7d-920c2b9f81db", "node_type": "1", "metadata": {}, "hash": "f4f653753036a2756502d61822c83c79407f796b3f9df0105b9f7bc8f3d377db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d9aee546-43f1-4309-8c76-361455b0f096", "node_type": "1", "metadata": {}, "hash": "08fdb894a8287aa0b8c6d5db4bd069e2c1868df545a87cd9b3b224bf9eef46cb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "............................................................................................................. 111\nAwsServiceException (and subclasses) ........................................................................................... 112\nSdkClientException ............................................................................................................................. 113\nExceptions and retry behavior ......................................................................................................... 113\nRetries ......................................................................................................................................................... 113\nRetry strategies ................................................................................................................................... 114\nSpecify a strategy ............................................................................................................................... 117\nCustomize a strategy ......................................................................................................................... 119\nMigrating from RetryPolicy to RetryStrategy ................................................................... 121\nLogging...................................................................................................................................................... 121\nLog4j 2 configuration file ................................................................................................................. 121\nAdd logging dependency .................................................................................................................. 121\nSDK-specific errors and warnings ................................................................................................... 122\nRequest/response summary logging .............................................................................................. 123\nDebug-level SDK logging .................................................................................................................. 124\nEnable wire logging ........................................................................................................................... 126\nSet the JVM TTL for DNS name lookups ............................................................................................ 131\nHow to set the JVM TTL ................................................................................................................... 132\nBest practices ............................................................................................................................................ 132\nReuse an SDK client ........................................................................................................................... 133\nClose input streams ........................................................................................................................... 133\nTune HTTP configurations ................................................................................................................ 133\nUse OpenSSL for Netty ..................................................................................................................... 134\nConfigure API timeouts ..................................................................................................................... 134\nUse metrics.......................................................................................................................................... 135\nTroubleshooting ....................................................................................................................................... 135\nConnection reset ................................................................................................................................. 136\nv\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConnection timeout........................................................................................................................... 136\nRead timed out ................................................................................................................................... 137\nConnection pool timeout .................................................................................................................. 137\nClasspath errors.................................................................................................................................. 141\nSignature errors .................................................................................................................................. 142\nConnection pool shut down ............................................................................................................. 143\nUse SDK features ......................................................................................................................... 146\nGeneral features ....................................................................................................................................... 146\nService-specific features ......................................................................................................................... 146\nWork with paginated results ................................................................................................................. 146\nSynchronous pagination.................................................................................................................... 147\nAsynchronous pagination.................................................................................................................. 150\nPoll for resource states ........................................................................................................................... 155\nPrerequisites........................................................................................................................................ 155\nUsing waiters ....................................................................................................................................... 156\nConfigure waiters............................................................................................................................... 157\nCode examples .................................................................................................................................... 157\nUse asynchronous programming .......................................................................................................... 158\nUse asynchronous client APIs .......................................................................................................... 158\nHandle streaming in asynchronous methods ............................................................................... 161\nConfigure advanced asynchronous options .................................................................................. 165\nWork with HTTP/2 ................................................................................................................................... 166\nUse SDK metrics ....................................................................................................................................... 166\nPrerequisites........................................................................................................................................ 167\nHow to enable metrics collection ................................................................................................... 167\nCustomize metrics publisher ............................................................................................................ 169\nWhen are metrics available? ............................................................................................................ 171\nWhat information is collected? ........................................................................................................ 171\nHow can I use this information? 171\nService client metrics . 172\nWork with AWS services . 177\nCloudWatch. 177\nGet metrics from CloudWatch . 178\nPublish custom metric data to CloudWatch . 180\nWork with CloudWatch alarms . 182\nUse Amazon CloudWatch Events . 186\nvi\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAWS database services . 189\nAmazon DynamoDB . 190\nAmazon RDS. 190\nAmazon Redshift. 191\nAmazon Aurora Serverless v1 . 191\nAmazon DocumentDB . 191\nDynamoDB . 192\nUse AWS account-based endpoints . 192\nWork with tables in DynamoDB . 193\nWork with items in DynamoDB . 203\nMap objects to DynamoDB items . 210\nAmazon EC2 . 343\nManage Amazon EC2 instances . 343\nUse AWS Regions and Availability Zones . 350\nWork with security groups in Amazon EC2 . 357\nWork with Amazon EC2 instance metadata . 362\nIAM. 368\nManage IAM access keys . 368\nManage IAM Users . 374\nCreate IAM policies . 379\nWork with IAM policies . 386\nWork with IAM server certificates . 392\nKinesis . 397\nSubscribe to Amazon Kinesis Data Streams . 397\nLambda. 408\nInvoke a Lambda function . 408\nList Lambda functions . 409\nDelete a Lambda function . 410\nAmazon S3. 411\nS3 clients in the SDK . 411\nUse access points or Multi-Region Access Points . 414\nPre-signed URLs. 415\nCross-Region access . 424\nChecksums. 425\nUse a performant S3 client . 429\nConfigure parallel transfer support . 432\nvii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTransfer files and directories . 434\nS3 Event Notifications . 442\nAmazon SNS. 449\nCreate a topic . 449\nList your Amazon SNS topics .", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d9aee546-43f1-4309-8c76-361455b0f096": {"__data__": {"id_": "d9aee546-43f1-4309-8c76-361455b0f096", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9828bafc-474d-4158-8726-abeef5a5924c", "node_type": "1", "metadata": {}, "hash": "74faaa3c902833306ea64c2a49b87f8e25d932bb97b110ebb6bce877bd2353bb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55918571-ab4c-4d7e-a944-fc0274e1922f", "node_type": "1", "metadata": {}, "hash": "56f403c27ec526298850cfefad94fd9a2c84a7248a2ae1ede44321dd55313209", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "374\nCreate IAM policies . 379\nWork with IAM policies . 386\nWork with IAM server certificates . 392\nKinesis . 397\nSubscribe to Amazon Kinesis Data Streams . 397\nLambda. 408\nInvoke a Lambda function . 408\nList Lambda functions . 409\nDelete a Lambda function . 410\nAmazon S3. 411\nS3 clients in the SDK . 411\nUse access points or Multi-Region Access Points . 414\nPre-signed URLs. 415\nCross-Region access . 424\nChecksums. 425\nUse a performant S3 client . 429\nConfigure parallel transfer support . 432\nvii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTransfer files and directories . 434\nS3 Event Notifications . 442\nAmazon SNS. 449\nCreate a topic . 449\nList your Amazon SNS topics . 450\nSubscribe an endpoint to a topic . 451\nPublish a message to a topic . 452\nUnsubscribe an endpoint from a topic . 453\nDelete a topic . 454\nAmazon SQS. 455\nUse automatic request batching . 456\nQueue operations . 461\nMessage operations. 464\nAmazon Transcribe . 468\nSet up the microphone . 468\nCreate a publisher . 469\nCreate the client and start the stream . 471\nMore information . 467\nCode examples. 474\nACM. 477\nActions . 477\nAPI Gateway. 494\nActions . 477\nScenarios. 498\nAWS community contributions . 499\nApplication Auto Scaling . 500\nActions . 477\nApplication Recovery Controller . 508\nActions . 477\nAurora . 511\nBasics. 512\nActions . 477\nScenarios. 498\nAuto Scaling . 546\nBasics. 512\nActions . 477\nviii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nScenarios. 498\nAWS Batch . 608\nActions . 477\nScenarios. 498\nAmazon Bedrock. 657\nActions . 477\nAmazon Bedrock Runtime . 663\nScenarios. 498\nAI21 Labs Jurassic-2 . 664\nAmazon Titan Image Generator . 670\nAmazon Titan Text . 672\nAmazon Titan Text Embeddings . 683\nAnthropic Claude . 686\nCohere Command. 697\nMeta Llama. 712\nMistral AI . 723\nStable Diffusion. 734\nCloudFront . 737\nActions . 477\nScenarios. 498\nCloudWatch. 756\nBasics. 512\nActions . 477\nScenarios. 498\nCloudWatch Events. 831\nActions . 477\nCloudWatch Logs . 837\nActions . 477\nAmazon Cognito Identity . 847\nActions . 477\nAmazon Cognito Identity Provider . 855\nActions . 477\nScenarios. 498\nAmazon Comprehend . 882\nActions . 477\nScenarios. 498\nix\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFirehose. 894\nActions . 477\nScenarios. 498\nAmazon DocumentDB . 904\nServerless examples. 904\nDynamoDB . 906\nBasics. 512\nActions . 477\nScenarios. 498\nServerless examples. 904\nAWS community contributions . 499\nAmazon EC2 . 994\nBasics. 512\nActions . 477\nScenarios. 498\nAmazon ECR . 1091\nBasics. 512\nActions . 477\nAmazon ECS . 1131\nActions . 477\nElastic Load Balancing - Version 2 . 1145\nActions . 477\nScenarios. 498\nMediaStore. 1189\nActions . 477\nOpenSearch Service. 1204\nBasics. 512\nActions . 477\nEventBridge . 1234\nBasics. 512\nActions . 477\nScenarios. 498\nEventBridge Scheduler . 1268\nActions . 477\nScenarios. 498\nForecast. 1293\nx\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions . 477\nAWS Glue. 1306\nBasics. 512\nActions . 477\nHealthImaging . 1338\nActions . 477\nScenarios. 498\nIAM. 1368\nBasics. 512\nActions . 477\nScenarios. 498\nAWS IoT. 1452\nBasics. 512\nActions .", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "55918571-ab4c-4d7e-a944-fc0274e1922f": {"__data__": {"id_": "55918571-ab4c-4d7e-a944-fc0274e1922f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d9aee546-43f1-4309-8c76-361455b0f096", "node_type": "1", "metadata": {}, "hash": "08fdb894a8287aa0b8c6d5db4bd069e2c1868df545a87cd9b3b224bf9eef46cb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e2b42c71-346f-4308-a90f-bc4cc7f113c7", "node_type": "1", "metadata": {}, "hash": "d5f6a38f54543b4ad3dfa616e3a03630f65af2a483a70abbb7e5a6e33f7d0f2a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "1145\nActions . 477\nScenarios. 498\nMediaStore. 1189\nActions . 477\nOpenSearch Service. 1204\nBasics. 512\nActions . 477\nEventBridge . 1234\nBasics. 512\nActions . 477\nScenarios. 498\nEventBridge Scheduler . 1268\nActions . 477\nScenarios. 498\nForecast. 1293\nx\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions . 477\nAWS Glue. 1306\nBasics. 512\nActions . 477\nHealthImaging . 1338\nActions . 477\nScenarios. 498\nIAM. 1368\nBasics. 512\nActions . 477\nScenarios. 498\nAWS IoT. 1452\nBasics. 512\nActions . 477\nAWS IoT data . 1492\nActions . 477\nAWS IoT SiteWise . 1495\nBasics. 512\nActions . 477\nAmazon Keyspaces . 1540\nBasics. 512\nActions . 477\nKinesis . 1566\nActions . 477\nServerless examples. 904\nAWS KMS . 1579\nBasics. 512\nActions . 477\nLambda. 1635\nBasics. 512\nActions . 477\nScenarios. 498\nServerless examples. 904\nAWS community contributions . 499\nAmazon Lex. 1671\nScenarios. 498\nxi\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAWS Marketplace Catalog API . 1672\nAMI products . 1673\nChannel partner offers . 1697\nContainer products . 1714\nEntities . 1720\nOffers. 1725\nProducts . 1785\nResale authorization. 1790\nSaaS products . 1831\nUtilities. 1857\nAWS Marketplace Agreement API . 1861\nAgreements . 1861\nMediaConvert. 1914\nActions . 477\nMigration Hub. 1936\nActions . 477\nAmazon MSK . 1949\nServerless examples. 904\nAmazon Personalize . 1951\nActions . 477\nAmazon Personalize Events . 1980\nActions . 477\nAmazon Personalize Runtime . 1984\nActions . 477\nAmazon Pinpoint. 1988\nActions . 477\nAmazon Pinpoint SMS and Voice API . 2032\nActions . 477\nAmazon Polly . 2036\nActions . 477\nScenarios. 498\nAmazon RDS. 2043\nBasics. 512\nActions . 477\nScenarios. 498\nServerless examples. 904\nxii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAmazon RDS Data Service . 2085\nScenarios. 498\nAmazon Redshift. 2087\nBasics. 512\nActions . 477\nScenarios. 498\nAmazon Rekognition. 2125\nActions . 477\nScenarios. 498\nRoute 53 domain registration . 2194\nBasics. 512\nActions . 477\nAmazon S3 . 2217\nBasics. 512\nActions . 477\nScenarios. 498\nServerless examples. 904\nAmazon S3 Control . 2396\nBasics. 512\nActions . 477\nS3 Directory Buckets . 2440\nActions . 477\nScenarios. 498\nS3 Glacier. 2492\nActions . 477\nSageMaker AI. 2508\nActions . 477\nScenarios. 498\nSecrets Manager. 2537\nActions . 477\nAmazon SES . 2539\nActions . 477\nScenarios. 498\nAmazon SES API v2 . 2555\nActions . 477\nScenarios. 498\nxiii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAmazon SNS . 2573\nActions . 477\nScenarios. 498\nServerless examples. 904\nAmazon SQS . 2640\nActions . 477\nScenarios. 498\nServerless examples. 904\nStep Functions. 2682\nBasics. 512\nActions . 477\nScenarios. 498\nAWS STS. 2707\nActions . 477\nAWS Support. 2710\nBasics. 512\nActions . 477\nSystems Manager. 2733\nBasics. 512\nActions . 477\nAmazon Textract . 2775\nActions .", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e2b42c71-346f-4308-a90f-bc4cc7f113c7": {"__data__": {"id_": "e2b42c71-346f-4308-a90f-bc4cc7f113c7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "55918571-ab4c-4d7e-a944-fc0274e1922f", "node_type": "1", "metadata": {}, "hash": "56f403c27ec526298850cfefad94fd9a2c84a7248a2ae1ede44321dd55313209", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "29fac197-b5a5-4a95-a5d5-0796081c45ca", "node_type": "1", "metadata": {}, "hash": "46afd2fe19565b2adcbb8addc95115013bc75d2429148042730573109fbe1961", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "477\nAmazon SES . 2539\nActions . 477\nScenarios. 498\nAmazon SES API v2 . 2555\nActions . 477\nScenarios. 498\nxiii\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAmazon SNS . 2573\nActions . 477\nScenarios. 498\nServerless examples. 904\nAmazon SQS . 2640\nActions . 477\nScenarios. 498\nServerless examples. 904\nStep Functions. 2682\nBasics. 512\nActions . 477\nScenarios. 498\nAWS STS. 2707\nActions . 477\nAWS Support. 2710\nBasics. 512\nActions . 477\nSystems Manager. 2733\nBasics. 512\nActions . 477\nAmazon Textract . 2775\nActions . 477\nScenarios. 498\nAmazon Transcribe . 2787\nActions . 477\nScenarios. 498\nAmazon Transcribe Streaming . 2798\nActions . 477\nScenarios. 498\nAmazon Translate. 2817\nScenarios. 498\nSecurity . 2820\nData protection. 2820\nTransport Layer Security (TLS) . 2821\nCheck TLS versions . 2822\nEnforce TLS versions . 2822\nxiv\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMigrate to TLS 1.2 . 2823\nIdentity and Access Management . 2823\nAudience. 2823\nAuthenticating with identities . 2824\nManaging access using policies . 2827\nHow AWS services work with IAM . 2830\nTroubleshooting AWS identity and access . 2830\nCompliance Validation . 2832\nResilience . 2833\nInfrastructure Security . 2833\nMigrate to version 2 . 2835\nWhat\u2019s new in version 2 . 2835\nHow to migrate . 2836\nMigration tool (preview release) . 2836\nStep-by-step instructions. 2841\nWhat's different between 1.x and 2.x . 2859\nPackage name change . 2859\nAdding version 2.x to your project . 2860\nImmutable POJOs. 2861\nSetter and getter methods . 2861\nModel class names . 2862\nLibraries and utilities . 2862\nClient changes . 2864\nCredentials provider changes . 2909\nRegion changes . 2917\nOperations, requests and responses changes . 2919\nException changes . 2920\nSerialization changes. 2921\nService-specific changes . 2922\nProfile file changes . 2928\nExternal configuration . 2929\nWaiters. 2932\nS3 Transfer Manager . 2936\nEC2 metadata utility . 2944\nCloudFront presigning . 2952\nS3 URI parsing . 2956\nxv\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIAM Policy Builder API . 2958\nDynamoDB mapping/document APIs . 2964\nS3 Event Notifications . 2992\nWorking with Amazon S3 . 2997\nUse the SDK for Java 1.x and 2.x side-by-side . 2998\nOpenPGP key. 3000\nCurrent key . 3000\nHistorical keys . 3004\nDocument history. 3007\nxvi\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeveloper Guide - AWS SDK for Java 2.x\nThe AWS SDK for Java provides a Java API for AWS services. Using the SDK, you can build Java\napplications that work with Amazon S3, Amazon EC2, DynamoDB, and more.\nThe AWS SDK for Java 2.x is a major rewrite of the version 1.x code base. It\u2019s built on top of Java 8+\nand adds several frequently requested features. These include support for non-blocking I/O and\nthe ability to plug in a different HTTP implementation at runtime.\nWe regularly add support for new services to the AWS SDK for Java. For a list of changes and\nfeatures in a particular version, view the change log.\nGet started with the SDK\nIf you\u2019re ready to get hands-on with the SDK, follow the Get started tutorial tutorial.\nTo set up your development environment, see Setup.\nIf you\u2019re currently using version 1.x of the SDK for Java, see Migrate to version 2 for specific\nguidance.", "mimetype": "text/plain", "start_char_idx": null, "end_char_idx": null, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "29fac197-b5a5-4a95-a5d5-0796081c45ca": {"__data__": {"id_": "29fac197-b5a5-4a95-a5d5-0796081c45ca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e2b42c71-346f-4308-a90f-bc4cc7f113c7", "node_type": "1", "metadata": {}, "hash": "d5f6a38f54543b4ad3dfa616e3a03630f65af2a483a70abbb7e5a6e33f7d0f2a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c249a192-586e-4261-94d2-639cdae37e12", "node_type": "1", "metadata": {}, "hash": "d4a8aeba65f30e5e9202f91e55adbc4910f91b04dba8186fed20865930b47012", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Using the SDK, you can build Java\napplications that work with Amazon S3, Amazon EC2, DynamoDB, and more.\nThe AWS SDK for Java 2.x is a major rewrite of the version 1.x code base. It\u2019s built on top of Java 8+\nand adds several frequently requested features. These include support for non-blocking I/O and\nthe ability to plug in a different HTTP implementation at runtime.\nWe regularly add support for new services to the AWS SDK for Java. For a list of changes and\nfeatures in a particular version, view the change log.\nGet started with the SDK\nIf you\u2019re ready to get hands-on with the SDK, follow the Get started tutorial tutorial.\nTo set up your development environment, see Setup.\nIf you\u2019re currently using version 1.x of the SDK for Java, see Migrate to version 2 for specific\nguidance.\nFor information on making requests to Amazon S3, DynamoDB, Amazon EC2 and other AWS\nservices, see Use the SDK for Java and Work with AWS services.\nDevelop mobile applications\nIf you\u2019re a mobile app developer, Amazon Web Services provides the AWS Amplify framework.\nMaintenance and support for SDK major versions\nFor information about maintenance and support for SDK major versions and their underlying\ndependencies, see the following topics in the AWS SDKs and Tools Reference Guide:\n\u2022 AWS SDKs and Tools Maintenance Policy\n\u2022 AWS SDKs and Tools Version Support Matrix\nGet started with the SDK 1\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAdditional resources\nIn addition to this guide, the following are valuable online resources for AWS SDK for Java\ndevelopers:\n\u2022 AWS SDK for Java 2.x API Reference\n\u2022 Java developer blog\n\u2022 Java development topic in AWS re:Post\n\u2022 SDK source on GitHub\n\u2022 AWS SDK Code Examples library\n\u2022 @awsforjava (Twitter)\nContribute to the SDK\nDevelopers can also contribute feedback through the following channels:\n\u2022 Submit issues on GitHub:\n\u2022 Submit Developer Guide documentation issues\n\u2022 Submit SDK issues\n\u2022 Join an informal chat about the SDK on the AWS SDK for Java 2.x gitter channel\nAdditional resources 2\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGet started with the AWS SDK for Java 2.x\nThe AWS SDK for Java 2.x provides Java APIs for Amazon Web Services (AWS). Using the SDK, you\ncan build Java applications that work with Amazon S3, Amazon EC2, DynamoDB, and more.\nThis tutorial shows you how to use Apache Maven to define dependencies for the SDK for Java 2.x\nand then write code that connects to Amazon S3 to upload a file.\nFollow these steps to complete this tutorial:\n\u2022 Step 1: Set up for this tutorial\n\u2022 Step 2: Create the project\n\u2022 Step 3: Write the code\n\u2022 Step 4: Build and run the application\nStep 1: Set up for this tutorial\nBefore you begin this tutorial, you need the following:\n\u2022 Permission to access Amazon S3\n\u2022 A Java development environment that is configured to access AWS services using single sign-on\nto the AWS IAM Identity Center\nUse the instructions in ??? to get set up for this tutorial. After you have configured your\ndevelopment environment with single sign-on access for the Java SDK and you have an active AWS\naccess portal session, continue with Step 2 of this tutorial.\nStep 2: Create the project\nTo create the project for this tutorial, you run a Maven command that prompts you for input on\nhow to configure the project. After all input is entered and confirmed, Maven finishes building out\nthe project by creating a pom.xml and creates stub Java files.\n1. Open a terminal or command prompt window and navigate to a directory of your choice, for\nexample, your Desktop or Home folder.\nStep 1: Set up for this tutorial 3\nAWS SDK for Java 2.x Developer Guide for version 2.x\n2. Enter the following command at the terminal and press Enter.\nmvn archetype:generate \\\n-DarchetypeGroupId=software.amazon.awssdk \\\n-DarchetypeArtifactId=archetype-app-quickstart \\\n-DarchetypeVersion=2.27.21\n3. Enter the value listed in the second column for each prompt.\nPrompt Value to enter\nDefine value for property s3\n'service':\nDefine value for property apache-client\n'httpClient' :\nDefine value for property false\n'nativeImage' :\nDefine value for property identity-center\n'credentialProvider'\nDefine value for property org.example\n'groupId':\nDefine value for property getstarted\n'artifactId':\nDefine value for property \n'version' 1.0-SNAPSHOT:\nDefine value for property \n'package' org.example:\n4. After the last value is entered, Maven lists the choices you made.", "mimetype": "text/plain", "start_char_idx": 72861, "end_char_idx": 77289, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c249a192-586e-4261-94d2-639cdae37e12": {"__data__": {"id_": "c249a192-586e-4261-94d2-639cdae37e12", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "29fac197-b5a5-4a95-a5d5-0796081c45ca", "node_type": "1", "metadata": {}, "hash": "46afd2fe19565b2adcbb8addc95115013bc75d2429148042730573109fbe1961", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "df45b317-8fbb-434f-bae7-2ff4234217ce", "node_type": "1", "metadata": {}, "hash": "ea1d4bbc785d5dae010cf38dae4a8f0f114b3eb6d2b5152e43e5185ec6551c5d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Enter the following command at the terminal and press Enter.\nmvn archetype:generate \\\n-DarchetypeGroupId=software.amazon.awssdk \\\n-DarchetypeArtifactId=archetype-app-quickstart \\\n-DarchetypeVersion=2.27.21\n3. Enter the value listed in the second column for each prompt.\nPrompt Value to enter\nDefine value for property s3\n'service':\nDefine value for property apache-client\n'httpClient' :\nDefine value for property false\n'nativeImage' :\nDefine value for property identity-center\n'credentialProvider'\nDefine value for property org.example\n'groupId':\nDefine value for property getstarted\n'artifactId':\nDefine value for property \n'version' 1.0-SNAPSHOT:\nDefine value for property \n'package' org.example:\n4. After the last value is entered, Maven lists the choices you made. Confirm by entering Y or re-\nenter values by entering N.\nStep 2: Create the project 4\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMaven creates the project folder named getstarted based on the artifactId value that you\nentered. Inside the getstarted folder, find a README.md file that you can review, a pom.xml file,\nand a src directory.\nMaven builds the following directory tree.\ngetstarted\n### README.md\n### pom.xml\n### src\n### main\n# ### java\n# # ### org\n# # ### example\n# # ### App.java\n# # ### DependencyFactory.java\n# # ### Handler.java\n# ### resources\n# ### simplelogger.properties\n### test\n### java\n### org\n### example\n### HandlerTest.java\n10 directories, 7 files\nThe following shows the contents of the pom.xml project file.\npom.xml\nThe dependencyManagement section contains a dependency to the AWS SDK for Java 2.x and the\ndependencies section has a dependency for Amazon S3. The project uses Java 1.8 because of the\n1.8 value in the maven.compiler.source and maven.compiler.target properties.\n\n\n4.0.0\norg.example\nStep 2: Create the project 5\nAWS SDK for Java 2.x Developer Guide for version 2.x\ngetstarted\n1.0-SNAPSHOT\njar\n\nUTF-8\n1.8\n1.8\n3.2.1\n3.6.1\n1.6.0\n2.27.21 <-------- SDK version\npicked up from archetype version.\n1.7.28\n5.8.1\n\n\n\n\nsoftware.amazon.awssdk\nbom\n${aws.java.sdk.version}\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ns3 <-------- S3 dependency\n\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nsoftware.amazon.awssdk\napache-client\n\n\n\nStep 2: Create the project 6\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\nsoftware.amazon.awssdk\nsso <-------- Required for identity center\nauthentication.", "mimetype": "text/plain", "start_char_idx": 76507, "end_char_idx": 80223, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "df45b317-8fbb-434f-bae7-2ff4234217ce": {"__data__": {"id_": "df45b317-8fbb-434f-bae7-2ff4234217ce", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c249a192-586e-4261-94d2-639cdae37e12", "node_type": "1", "metadata": {}, "hash": "d4a8aeba65f30e5e9202f91e55adbc4910f91b04dba8186fed20865930b47012", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4f057cc4-8680-4708-816c-ff7c92e8f032", "node_type": "1", "metadata": {}, "hash": "667e2b2f49aac205c0e22c65109ed9e017ce1c7b414915af95335b6d9a1079f7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\n\nsoftware.amazon.awssdk\nssooidc <-------- Required for identity center\nauthentication.\n\n\nsoftware.amazon.awssdk\napache-client <-------- HTTP client specified.\n\n\ncommons-logging\ncommons-logging\n\n\n\n\norg.slf4j\nslf4j-api\n${slf4j.version}\n\n\norg.slf4j\nslf4j-simple\n${slf4j.version}\n\n\n\norg.slf4j\njcl-over-slf4j\n${slf4j.version}\n\nStep 2: Create the project 7\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\norg.junit.jupiter\njunit-jupiter\n${junit5.version}\ntest\n\n\n\n\n\norg.apache.maven.plugins\nmaven-compiler-plugin\n${maven.compiler.plugin.version}\n\n\n\n\nStep 3: Write the code\nThe following code shows the App class created by Maven. The main method is the entry point into\nthe application, which creates an instance of the Handler class and then calls its sendRequest\nmethod.\nApp class\npackage org.example;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class App {\nprivate static final Logger logger = LoggerFactory.getLogger(App.class);\npublic static void main(String... args) {\nlogger.info(\"Application starts\");\nHandler handler = new Handler();\nhandler.sendRequest();\nStep 3: Write the code 8\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Application ends\");\n}\n}\nThe DependencyFactory class created by Maven contains the s3Client factory method that\nbuilds and returns an S3Client instance. The S3Client instance uses an instance of the Apache-\nbased HTTP client. This is because you specified apache-client when Maven prompted you for\nwhich HTTP client to use.\nThe DependencyFactory is shown in the following code.\nDependencyFactory class\npackage org.example;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\n/**\n* The module containing all dependencies required by the {@link Handler}.\n*/\npublic class DependencyFactory {\nprivate DependencyFactory() {}\n/**\n* @return an instance of S3Client\n*/\npublic static S3Client s3Client() {\nreturn S3Client.builder()\n.httpClientBuilder(ApacheHttpClient.builder())\n.build();\n}\n}\nThe Handler class contains the main logic of your program. When an instance of Handler is\ncreated in the App class, the DependencyFactory furnishes the S3Client service client. Your\ncode uses the S3Client instance to call the Amazon S3 service.\nMaven generates the following Handler class with a TODO comment. The next step in the tutorial\nreplaces the TODO with code.\nStep 3: Write the code 9\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHandler class, Maven-generated\npackage org.example;\nimport software.amazon.awssdk.services.s3.S3Client;\npublic class Handler {\nprivate final S3Client s3Client;\npublic Handler() {\ns3Client = DependencyFactory.s3Client();\n}\npublic void sendRequest() {\n// TODO: invoking the api calls using s3Client.\n}\n}\nTo fill in the logic, replace the entire contents of the Handler class with the following code. The\nsendRequest method is filled in and the necessary imports are added.\nHandler class, implemented\nThe code first creates a new S3 bucket with the last part of the name generated using\nSystem.currentTimeMillis() in order to make the bucket name unique.\nAfter creating the bucket in the createBucket() method, the program uploads an object using\nthe putObject method of S3Client. The contents of the object is a simple string created with\nthe RequestBody.fromString method.\nFinally, the program deletes the object followed by the bucket in the cleanUp method.", "mimetype": "text/plain", "start_char_idx": 80224, "end_char_idx": 84602, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4f057cc4-8680-4708-816c-ff7c92e8f032": {"__data__": {"id_": "4f057cc4-8680-4708-816c-ff7c92e8f032", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "df45b317-8fbb-434f-bae7-2ff4234217ce", "node_type": "1", "metadata": {}, "hash": "ea1d4bbc785d5dae010cf38dae4a8f0f114b3eb6d2b5152e43e5185ec6551c5d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c7974532-f799-4bd4-872e-602718275823", "node_type": "1", "metadata": {}, "hash": "86aa12f5fab696a7e1d7142e0b9cc2bbcd4dcdcb1074c42ec77a132736f97446", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "}\nTo fill in the logic, replace the entire contents of the Handler class with the following code. The\nsendRequest method is filled in and the necessary imports are added.\nHandler class, implemented\nThe code first creates a new S3 bucket with the last part of the name generated using\nSystem.currentTimeMillis() in order to make the bucket name unique.\nAfter creating the bucket in the createBucket() method, the program uploads an object using\nthe putObject method of S3Client. The contents of the object is a simple string created with\nthe RequestBody.fromString method.\nFinally, the program deletes the object followed by the bucket in the cleanUp method.\npackage org.example;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport software.amazon.awssdk.services.s3.model.CreateBucketRequest;\nimport software.amazon.awssdk.services.s3.model.DeleteBucketRequest;\nimport software.amazon.awssdk.services.s3.model.DeleteObjectRequest;\nimport software.amazon.awssdk.services.s3.model.HeadBucketRequest;\nimport software.amazon.awssdk.services.s3.model.PutObjectRequest;\nStep 3: Write the code 10\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.s3.model.S3Exception;\npublic class Handler {\nprivate final S3Client s3Client;\npublic Handler() {\ns3Client = DependencyFactory.s3Client();\n}\npublic void sendRequest() {\nString bucket = \"bucket\" + System.currentTimeMillis();\nString key = \"key\";\ncreateBucket(s3Client, bucket);\nSystem.out.println(\"Uploading object...\");\ns3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key)\n.build(),\nRequestBody.fromString(\"Testing with the {sdk-java}\"));\nSystem.out.println(\"Upload complete\");\nSystem.out.printf(\"%n\");\ncleanUp(s3Client, bucket, key);\nSystem.out.println(\"Closing the connection to {S3}\");\ns3Client.close();\nSystem.out.println(\"Connection closed\");\nSystem.out.println(\"Exiting...\");\n}\npublic static void createBucket(S3Client s3Client, String bucketName) {\ntry {\ns3Client.createBucket(CreateBucketRequest\n.builder()\n.bucket(bucketName)\n.build());\nSystem.out.println(\"Creating bucket: \" + bucketName);\ns3Client.waiter().waitUntilBucketExists(HeadBucketRequest.builder()\n.bucket(bucketName)\n.build());\nSystem.out.println(bucketName + \" is ready.\");\nStep 3: Write the code 11\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.printf(\"%n\");\n} catch (S3Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void cleanUp(S3Client s3Client, String bucketName, String keyName) {\nSystem.out.println(\"Cleaning up...\");\ntry {\nSystem.out.println(\"Deleting object: \" + keyName);\nDeleteObjectRequest deleteObjectRequest =\nDeleteObjectRequest.builder().bucket(bucketName).key(keyName).build();\ns3Client.deleteObject(deleteObjectRequest);\nSystem.out.println(keyName + \" has been deleted.\");\nSystem.out.println(\"Deleting bucket: \" + bucketName);\nDeleteBucketRequest deleteBucketRequest =\nDeleteBucketRequest.builder().bucket(bucketName).build();\ns3Client.deleteBucket(deleteBucketRequest);\nSystem.out.println(bucketName + \" has been deleted.\");\nSystem.out.printf(\"%n\");\n} catch (S3Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Cleanup complete\");\nSystem.out.printf(\"%n\");\n}\n}\nStep 4: Build and run the application\nAfter the project is created and contains the complete Handler class, build and run the\napplication.\n1. Make sure that you have an active IAM Identity Center session. To do so, run the AWS Command\nLine Interface command aws sts get-caller-identity and check the response. If you\ndon't have an active session, see this section for instructions.\n2. Open a terminal or command prompt window and navigate to your project directory\ngetstarted.\n3. Use the following command to build your project:\nStep 4: Build and run the application 12\nAWS SDK for Java 2.x Developer Guide for version 2.x\nmvn clean package\n4. Use the following command to run the application.\nmvn exec:java -Dexec.mainClass=\"org.example.App\"\nTo view the new bucket and object that the program creates, perform the following steps.\n1. In Handler.java, comment out the line cleanUp(s3Client, bucket, key) in the\nsendRequest method and save the file.\n2. Rebuild the project by running mvn clean package.\n3. Rerun mvn exec:java -Dexec.mainClass=\"org.example.App\" to upload the text object\nonce more.\n4.", "mimetype": "text/plain", "start_char_idx": 83945, "end_char_idx": 88387, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c7974532-f799-4bd4-872e-602718275823": {"__data__": {"id_": "c7974532-f799-4bd4-872e-602718275823", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4f057cc4-8680-4708-816c-ff7c92e8f032", "node_type": "1", "metadata": {}, "hash": "667e2b2f49aac205c0e22c65109ed9e017ce1c7b414915af95335b6d9a1079f7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "adc20649-cce2-4e46-acfc-47c7b5b8f21e", "node_type": "1", "metadata": {}, "hash": "971c3a36344b3d777921abbd307fff1904d15850582d68b251e29023aa7f9cbe", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "2. Open a terminal or command prompt window and navigate to your project directory\ngetstarted.\n3. Use the following command to build your project:\nStep 4: Build and run the application 12\nAWS SDK for Java 2.x Developer Guide for version 2.x\nmvn clean package\n4. Use the following command to run the application.\nmvn exec:java -Dexec.mainClass=\"org.example.App\"\nTo view the new bucket and object that the program creates, perform the following steps.\n1. In Handler.java, comment out the line cleanUp(s3Client, bucket, key) in the\nsendRequest method and save the file.\n2. Rebuild the project by running mvn clean package.\n3. Rerun mvn exec:java -Dexec.mainClass=\"org.example.App\" to upload the text object\nonce more.\n4. Sign in to the S3 console to view the new object in the newly created bucket.\nAfter you view the file, delete the object, and then delete the bucket.\nSuccess\nIf your Maven project built and ran without error, then congratulations! You have successfully built\nyour first Java application using the SDK for Java 2.x.\nCleanup\nTo clean up the resources you created during this tutorial, do the following:\n\u2022 If you haven't done so already, in the S3 console, delete any objects and any buckets created\nwhen you ran the application.\n\u2022 Delete the project folder (getstarted).\nNext steps\nNow that you have the basics down, you can learn about the following:\n\u2022 Working with Amazon S3\nSuccess 13\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Working with other Amazon Web Services, such as DynamoDB, Amazon EC2, and various\ndatabase services\n\u2022 Use the SDK\n\u2022 Security for the AWS SDK for Java\nNext steps 14\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSet up the AWS SDK for Java 2.x\nThis section provides information about how to set up your development environment and projects\nto use the AWS SDK for Java 2.x.\nSetup overview\nTo successfully develop applications that access AWS services using the AWS SDK for Java, the\nfollowing conditions are required:\n\u2022 The Java SDK must have access to credentials to authenticate requests on your behalf.\n\u2022 The permissions of the IAM role configured for the SDK must allow access to the AWS services\nthat your application requires. The permissions associated with the PowerUserAccess AWS\nmanaged policy are sufficient for most development needs.\n\u2022 A development environment with the following elements:\n\u2022 Shared configuration files that are set up in at least one of the following ways:\n\u2022 The config file contains IAM Identity Center single sign-on settings so that the SDK can get\nAWS credentials.\n\u2022 The credentials file contains temporary credentials.\n\u2022 An installation of Java 8 or later.\n\u2022 A build automation tool such as Maven or Gradle.\n\u2022 A text editor to work with code.\n\u2022 (Optional, but recommended) An IDE (integrated development environment) such as IntelliJ\nIDEA, Eclipse, or NetBeans.\nWhen you use an IDE, you can also integrate AWS Toolkits to more easily work with AWS\nservices. The AWS Toolkit for IntelliJ and AWS Toolkit for Eclipse are two toolkits that you can\nuse for Java development.\n\u2022 An active AWS access portal session when you are ready to run your application. You use the\nAWS Command Line Interface to initiate the sign-in process to IAM Identity Center's AWS access\nportal.\nSetup overview 15\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImportant\nThe instructions in this setup section assume that you or organization uses IAM Identity\nCenter. If your organization uses an external identity provider that works independently of\nIAM Identity Center, find out how you can get temporary credentials for the SDK for Java to\nuse. Follow these instructions to add temporary credentials to the ~/.aws/credentials\nfile.\nIf your identity provider adds temporary credentials automatically to the ~/.aws/\ncredentials file, make sure that the profile name is [default] so that you do not need\nto provide a profile name to the SDK or AWS CLI.\nSet up authentication\nThe Authentication and access topic in the AWS SDKs and Tools Reference Guide describes the\ndifferent options to authenticate. We recommend that you follow the instructions to set up access\nto the IAM Identity Center so the SDK can acquire credentials. After following the instructions, your\nsystem is set up to allow the SDK to authenticate requests.\nSetup for single sign-on access for the SDK\nAfter you complete Step 2 in the programmatic access section so that the SDK can use IAM Identity\nCenter authentication, your system should contain the following elements.\n\u2022 The AWS CLI, which you use to start an AWS access portal session before you run your\napplication.\n\u2022 An ~/.aws/config file that contains a default profile.", "mimetype": "text/plain", "start_char_idx": 87670, "end_char_idx": 92347, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "adc20649-cce2-4e46-acfc-47c7b5b8f21e": {"__data__": {"id_": "adc20649-cce2-4e46-acfc-47c7b5b8f21e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c7974532-f799-4bd4-872e-602718275823", "node_type": "1", "metadata": {}, "hash": "86aa12f5fab696a7e1d7142e0b9cc2bbcd4dcdcb1074c42ec77a132736f97446", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ebc1d360-26a7-4392-9653-bf887a7543f6", "node_type": "1", "metadata": {}, "hash": "ae5e7153b1545f1f67b839627d52450f1c109e1865863408d5d9ad98f04e4b06", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If your identity provider adds temporary credentials automatically to the ~/.aws/\ncredentials file, make sure that the profile name is [default] so that you do not need\nto provide a profile name to the SDK or AWS CLI.\nSet up authentication\nThe Authentication and access topic in the AWS SDKs and Tools Reference Guide describes the\ndifferent options to authenticate. We recommend that you follow the instructions to set up access\nto the IAM Identity Center so the SDK can acquire credentials. After following the instructions, your\nsystem is set up to allow the SDK to authenticate requests.\nSetup for single sign-on access for the SDK\nAfter you complete Step 2 in the programmatic access section so that the SDK can use IAM Identity\nCenter authentication, your system should contain the following elements.\n\u2022 The AWS CLI, which you use to start an AWS access portal session before you run your\napplication.\n\u2022 An ~/.aws/config file that contains a default profile. The SDK for Java uses the profile's\nSSO token provider configuration to acquire credentials before sending requests to AWS. The\nsso_role_name value, which is an IAM role connected to an IAM Identity Center permission set,\nshould allow access to the AWS services used in your application.\nThe following sample config file shows a default profile set up with SSO token provider\nconfiguration. The profile's sso_session setting refers to the named sso-session section.\nThe sso-session section contains settings to initiate an AWS access portal session.\n[default]\nsso_session = my-sso\nSet up authentication 16\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsso_account_id = 111122223333\nsso_role_name = SampleRole\nregion = us-east-1\noutput = json\n[sso-session my-sso]\nsso_region = us-east-1\nsso_start_url = https://provided-domain.awsapps.com/start\nsso_registration_scopes = sso:account:access\nFor more details about the settings used in the SSO token provider configuration, see SSO token\nprovider configuration in the AWS SDKs and Tools Reference Guide.\nIf your development environment is not set up for programmatic access as previously shown,\nfollow Step 2 in the SDKs Reference Guide.\nSign in using the AWS CLI\nBefore running an application that accesses AWS services, you need an active AWS access portal\nsession in order for the SDK to use IAM Identity Center authentication to resolve credentials. Run\nthe following command in the AWS CLI to sign in to the AWS access portal.\naws sso login\nSince you have a default profile setup, you do not need to call the command with a --profile\noption. If your SSO token provider configuration is using a named profile, the command is aws\nsso login --profile named-profile.\nTo test if you already have an active session, run the following AWS CLI command.\naws sts get-caller-identity\nThe response to this command should report the IAM Identity Center account and permission set\nconfigured in the shared config file.\nNote\nIf you already have an active AWS access portal session and run aws sso login, you will\nnot be required to provide credentials.\nSign in using the AWS CLI 17\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHowever, you will see a dialog that requests permission for botocore to access your\ninformation. botocore is the foundation for the AWS CLI .\nSelect Allow to authorize access to your information for the AWS CLI and SDK for Java.\nInstall Java and a build tool\nYour development environment needs the following:\n\u2022 Java 8 or later. The AWS SDK for Java works with the Oracle Java SE Development Kit and with\ndistributions of Open Java Development Kit (OpenJDK) such as Amazon Corretto, Red Hat\nOpenJDK, and Adoptium.\n\u2022 A build tool or IDE that supports Maven Central such as Apache Maven, Gradle, or IntelliJ.\n\u2022 For information about how to install and use Maven, see https://maven.apache.org/.\n\u2022 For information about how to install and use Gradle, see https://gradle.org/.\n\u2022 For information about how to install and use IntelliJ IDEA, see https://www.jetbrains.com/\nidea/.\nAdditional authentication options\nFor more options on authentication for the SDK, such as the use of profiles and environment\nvariables, see the configuration chapter in the AWS SDKs and Tools Reference Guide.\nSet up an Apache Maven project\nYou can use Apache Maven to set up and build AWS SDK for Java projects, or to build the SDK\nitself.\nPrerequisites\nTo use the AWS SDK for Java with Maven, you need the following:\n\u2022 Java 8.0 or later. You can download the latest Java SE Development Kit software from http://\nwww.oracle.com/technetwork/java/javase/downloads/.", "mimetype": "text/plain", "start_char_idx": 91383, "end_char_idx": 95962, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ebc1d360-26a7-4392-9653-bf887a7543f6": {"__data__": {"id_": "ebc1d360-26a7-4392-9653-bf887a7543f6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "adc20649-cce2-4e46-acfc-47c7b5b8f21e", "node_type": "1", "metadata": {}, "hash": "971c3a36344b3d777921abbd307fff1904d15850582d68b251e29023aa7f9cbe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8e40d97a-b776-484c-921b-1ae55f524854", "node_type": "1", "metadata": {}, "hash": "3398c1ecf6a030c9cf717eb74615ff108fe28f691d65edb32cff749e13b771af", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 For information about how to install and use Maven, see https://maven.apache.org/.\n\u2022 For information about how to install and use Gradle, see https://gradle.org/.\n\u2022 For information about how to install and use IntelliJ IDEA, see https://www.jetbrains.com/\nidea/.\nAdditional authentication options\nFor more options on authentication for the SDK, such as the use of profiles and environment\nvariables, see the configuration chapter in the AWS SDKs and Tools Reference Guide.\nSet up an Apache Maven project\nYou can use Apache Maven to set up and build AWS SDK for Java projects, or to build the SDK\nitself.\nPrerequisites\nTo use the AWS SDK for Java with Maven, you need the following:\n\u2022 Java 8.0 or later. You can download the latest Java SE Development Kit software from http://\nwww.oracle.com/technetwork/java/javase/downloads/. The AWS SDK for Java also works with\nOpenJDK and Amazon Corretto, a distribution of the Open Java Development Kit (OpenJDK).\nDownload the latest OpenJDK version from https://openjdk.java.net/install/index.html.\nDownload the latest Amazon Corretto 8 or Amazon Corretto 11 version from the Corretto page.\nInstall Java and a build tool 18\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Apache Maven. If you need to install Maven, go to http://maven.apache.org/ to download and\ninstall it.\nCreate a Maven project\nTo create a Maven project from the command line, run the following command from a terminal or\ncommand prompt window.\nmvn -B archetype:generate \\\n-DarchetypeGroupId=software.amazon.awssdk \\\n-DarchetypeArtifactId=archetype-lambda -Dservice=s3 -Dregion=US_WEST_2 \\\n-DarchetypeVersion=2.X.X \\\n-DgroupId=com.example.myapp \\\n-DartifactId=myapp\nNote\nReplace com.example.myapp with the full package namespace of your application. Also\nreplace myapp with your project name. This becomes the name of the directory for your\nproject.\nTo use the latest version of the archetype, replace 2.X.X with the latest from Maven\ncentral.\nThis command creates a Maven project using the archetype templating toolkit. The archetype\ngenerates the scaffolding for an AWS Lambda function handler project . This project archetype is\npreconfigured to compile with Java SE 8 and includes a dependency to the version of the SDK for\nJava 2.x specified with -DarchetypeVersion.\nFor more information about creating and configuring Maven projects, see the Maven Getting\nStarted Guide.\nConfigure the Java compiler for Maven\nIf you created your project using the AWS Lambda project archetype as described previously, the\nconfiguration of the Java compiler is already done for you.\nTo verify that this configuration is present, start by opening the pom.xml file from the project\nfolder you created (for example, myapp) when you executed the previous command. Look on\nCreate a Maven project 19\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlines 11 and 12 to see the Java compiler version setting for this Maven project, and the required\ninclusion of the Maven compiler plugin on lines 71-75.\n\n\n1.8\n1.8\n\n\n\n\norg.apache.maven.plugins\nmaven-compiler-plugin\n${maven.compiler.plugin.version}\n\n\n\n\nIf you create your project with a different archetype or by using another method, you must ensure\nthat the Maven compiler plugin is part of the build and that its source and target properties are\nboth set to 1.8 in the pom.xml file.\nSee the previous snippet for one way to configure these required settings.\nAlternatively, you can configure the compiler configuration inline with the plugin declaration, as\nfollows.\n\n\n\n\norg.apache.maven.plugins\nmaven-compiler-plugin\n\n1.8\n1.8\n\n\n\n\n\nConfigure the Java compiler for Maven 20\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeclare the SDK as a dependency\nTo use the AWS SDK for Java in your project, you need to declare it as a dependency in your\nproject\u2019s pom.xml file.\nIf you created your project using the project archetype as described previously, the latest version of\nthe SDK is already configured as a dependency in your project.", "mimetype": "text/plain", "start_char_idx": 95133, "end_char_idx": 99557, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8e40d97a-b776-484c-921b-1ae55f524854": {"__data__": {"id_": "8e40d97a-b776-484c-921b-1ae55f524854", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ebc1d360-26a7-4392-9653-bf887a7543f6", "node_type": "1", "metadata": {}, "hash": "ae5e7153b1545f1f67b839627d52450f1c109e1865863408d5d9ad98f04e4b06", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8889ad8a-fa7a-40c3-806e-7cac3cad03c4", "node_type": "1", "metadata": {}, "hash": "b91be1989a2da19e01da84acd72ac4f15eae87a7f2a50401480a75fd91a07f35", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "See the previous snippet for one way to configure these required settings.\nAlternatively, you can configure the compiler configuration inline with the plugin declaration, as\nfollows.\n\n\n\n\norg.apache.maven.plugins\nmaven-compiler-plugin\n\n1.8\n1.8\n\n\n\n\n\nConfigure the Java compiler for Maven 20\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeclare the SDK as a dependency\nTo use the AWS SDK for Java in your project, you need to declare it as a dependency in your\nproject\u2019s pom.xml file.\nIf you created your project using the project archetype as described previously, the latest version of\nthe SDK is already configured as a dependency in your project.\nThe archetype generates a BOM (bill of materials) artifact dependency for the\nsoftware.amazon.awssdk group id. With a BOM, you do not have to specify the maven version\nfor individual artifact dependencies that share the same group id.\nIf you created your Maven project in a different way, configure the latest version of the SDK for\nyour project by ensuring that the pom.xml file contains the following.\n\n\n2.X.X\n\n\n\n\nsoftware.amazon.awssdk\nbom\n${aws.java.sdk.version}\npom\nimport\n\n\n\n\nNote\nReplace 2.X.X in the pom.xml file with the latest version of the AWS SDK for Java 2.x.\nSet dependencies for SDK modules\nNow that you have configured the SDK, you can add dependencies for one or more of the AWS SDK\nfor Java modules to use in your project.\nDeclare the SDK as a dependency 21\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAlthough you can specify the version number for each component, you don\u2019t need to because\nyou already declared the SDK version in the dependencyManagement section using the bill of\nmaterials artifact. To load a different version of a given module, specify a version number for its\ndependency.\nIf you created your project using the project archetype as described previously, your project is\nalready configured with multiple dependencies. These include dependences for AWS Lambda\nfunction handlers and Amazon S3, as follows.\n\n\n\nsoftware.amazon.awssdk\ns3\n\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nsoftware.amazon.awssdk\napache-client\n\n\n\n\nsoftware.amazon.awssdk\nurl-connection-client\n\n\ncom.amazonaws\naws-lambda-java-core\n${aws.lambda.java.version}\n\n\n\nSet dependencies for SDK modules 22\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIn the pom.xml example above, the dependencies are from different groupIds. The s3\ndependency is from software.amazon.awssdk, whereas the aws-lambda-java-core\ndependency is from com.amazonaws. The BOM dependency management configuration\naffects artifacts for software.amazon.awssdk, so a version is needed for the aws-\nlambda-java-core artifact.\nFor the development of Lambda function handlers using the SDK for Java 2.x, aws-\nlambda-java-core is the correct dependency. However, if your application needs to\nmanage Lambda resources, using operations such as listFunctions, deleteFunction,\ninvokeFunction, and createFunction, your application requires the following\ndependency.\nsoftware.amazon.awssdk\nlambda\nNote\nThe s3 dependency excludes the the netty-nio-client and apache-client transitive\ndependencies. In place of either of those HTTP clients, the archetype includes the url-\nconnection-client dependency, which helps reduce the startup latency for AWS\nLambda functions.\nAdd the modules to your project for the AWS service and features you need for your project. The\nmodules (dependencies) that are managed by the AWS SDK for Java BOM are listed on the Maven\ncentral repository.", "mimetype": "text/plain", "start_char_idx": 98723, "end_char_idx": 103171, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8889ad8a-fa7a-40c3-806e-7cac3cad03c4": {"__data__": {"id_": "8889ad8a-fa7a-40c3-806e-7cac3cad03c4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8e40d97a-b776-484c-921b-1ae55f524854", "node_type": "1", "metadata": {}, "hash": "3398c1ecf6a030c9cf717eb74615ff108fe28f691d65edb32cff749e13b771af", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "85c32ff5-b949-4689-ad89-3c0224ad4dd7", "node_type": "1", "metadata": {}, "hash": "25bbee0c032f5983cb6770305b5d2d8fb89eba48ff286f090a2e1e17e68f9f1e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "For the development of Lambda function handlers using the SDK for Java 2.x, aws-\nlambda-java-core is the correct dependency. However, if your application needs to\nmanage Lambda resources, using operations such as listFunctions, deleteFunction,\ninvokeFunction, and createFunction, your application requires the following\ndependency.\nsoftware.amazon.awssdk\nlambda\nNote\nThe s3 dependency excludes the the netty-nio-client and apache-client transitive\ndependencies. In place of either of those HTTP clients, the archetype includes the url-\nconnection-client dependency, which helps reduce the startup latency for AWS\nLambda functions.\nAdd the modules to your project for the AWS service and features you need for your project. The\nmodules (dependencies) that are managed by the AWS SDK for Java BOM are listed on the Maven\ncentral repository.\nNote\nYou can look at the pom.xml file from a code example to determine which dependencies\nyou need for your project. For example, if you\u2019re interested in the dependencies for the\nDynamoDB service, see this example from the AWS Code Examples Repository on GitHub.\n(Look for the pom.xml file under /javav2/example_code/dynamodb.)\nSet dependencies for SDK modules 23\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBuild the entire SDK into your project\nTo optimize your application, we strongly recommend that you pull in only the components you\nneed instead of the entire SDK. However, to build the entire AWS SDK for Java into your project,\ndeclare it in your pom.xml file, as follows.\n\n\n\nsoftware.amazon.awssdk\naws-sdk-java\n2.X.X\n\n\n\nBuild your project\nAfter you configure the pom.xml file, you can use Maven to build your project.\nTo build your Maven project from the command line, open a terminal or command prompt window,\nnavigate to your project directory (for example, myapp), enter or paste the following command,\nthen press Enter or Return.\nmvn package\nThis creates a single .jar file (JAR) in the target directory (for example, myapp/target). This\nJAR contains all of the SDK modules you specified as dependencies in your pom.xml file.\nSet up a Gradle project\nYou can use Gradle to set up and build AWS SDK for Java projects.\nThe initial steps in the following example come from Gradle's Getting Started guide for version 8.4.\nIf you use a different version, your results may differ slightly.\nTo create a Java application with Gradle (command line)\n1. Create a directory to hold your project. In this example, demo is the directory name.\nBuild your project 24\nAWS SDK for Java 2.x Developer Guide for version 2.x\n2. Inside the demo directory, execute the gradle init command and supply the values\nhighlighted in red as shown in the following command line output. For the walk through, we\nchoose Kotlin as the build script DSL language, but a complete example for Groovy is also\nshown at the end of this topic.\n> gradle init\nStarting a Gradle Daemon (subsequent builds will be faster)\nSelect type of project to generate:\n1: basic\n2: application\n3: library\n4: Gradle plugin\nEnter selection (default: basic) [1..4] 2\nSelect implementation language:\n1: C++\n2: Groovy\n3: Java\n4: Kotlin\n5: Scala\n6: Swift\nEnter selection (default: Java) [1..6] 3\nGenerate multiple subprojects for application? (default: no) [yes, no] no\nSelect build script DSL:\n1: Kotlin\n2: Groovy\nEnter selection (default: Kotlin) [1..2] \nSelect test framework:\n1: JUnit 4\n2: TestNG\n3: Spock\n4: JUnit Jupiter\nEnter selection (default: JUnit Jupiter) [1..4] 4\nProject name (default: demo): \nSource package (default: demo): \nEnter target version of Java (min. 7) (default: 11): \nGenerate build using new APIs and behavior (some features may change in the next\nminor release)? (default: no) [yes, no] \nSet up a Gradle project 25\nAWS SDK for Java 2.x Developer Guide for version 2.x\n> Task :init\nTo learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.4/\nsamples/sample_building_java_applications.html\nBUILD SUCCESSFUL in 3m 43s\n2 actionable tasks: 2 executed\n3.", "mimetype": "text/plain", "start_char_idx": 102289, "end_char_idx": 106501, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "85c32ff5-b949-4689-ad89-3c0224ad4dd7": {"__data__": {"id_": "85c32ff5-b949-4689-ad89-3c0224ad4dd7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8889ad8a-fa7a-40c3-806e-7cac3cad03c4", "node_type": "1", "metadata": {}, "hash": "b91be1989a2da19e01da84acd72ac4f15eae87a7f2a50401480a75fd91a07f35", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e9f9fa2a-b624-475c-a19e-d09d8a160190", "node_type": "1", "metadata": {}, "hash": "62113e3edfbbdf02cf657509688ff4184dba7f6b04af2b84f9abc92e7e674d6b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "7) (default: 11): \nGenerate build using new APIs and behavior (some features may change in the next\nminor release)? (default: no) [yes, no] \nSet up a Gradle project 25\nAWS SDK for Java 2.x Developer Guide for version 2.x\n> Task :init\nTo learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.4/\nsamples/sample_building_java_applications.html\nBUILD SUCCESSFUL in 3m 43s\n2 actionable tasks: 2 executed\n3. After the init task completes, the demo directory contains the following tree structure. We\ntake a closer look at the main build file, build.gradle.kts (highlighted in red), in the next\nsection.\n### app\n# ### build.gradle.kts\n# ### src\n# ### main\n# # ### java\n# # # ### demo\n# # # ### App.java\n# # ### resources\n# ### test\n# ### java\n# # ### demo\n# # ### AppTest.java\n# ### resources\n### gradle\n# ### wrapper\n# ### gradle-wrapper.jar\n# ### gradle-wrapper.properties\n### gradlew\n### gradlew.bat\n### settings.gradle.kts\nThe build.gradle.kts file contains the following scaffolded content.\n/*\n* This file was generated by the Gradle 'init' task.\n*\n* This generated file contains a sample Java application project to get you\nstarted.\n* For more details on building Java & JVM projects, please refer to https://\ndocs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle\ndocumentation.\nSet up a Gradle project 26\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\nplugins {\n// Apply the application plugin to add support for building a CLI application\nin Java.\napplication\n}\nrepositories {\n// Use Maven Central for resolving dependencies.\nmavenCentral()\n}\ndependencies {\n// Use JUnit Jupiter for testing.\ntestImplementation(\"org.junit.jupiter:junit-jupiter:5.9.3\")\ntestRuntimeOnly(\"org.junit.platform:junit-platform-launcher\")\n// This dependency is used by the application.\nimplementation(\"com.google.guava:guava:33.3.0-jre\")\n}\n// Apply a specific Java toolchain to ease working on different environments.\njava {\ntoolchain {\nlanguageVersion.set(JavaLanguageVersion.of(11))\n}\n}\napplication {\n// Define the main class for the application.\nmainClass.set(\"demo.App\")\n}\ntasks.named(\"test\") {\n// Use JUnit Platform for unit tests.\nuseJUnitPlatform()\n}\n4. Use the scaffolded Gradle build file as the basis for your AWS project.\nSet up a Gradle project 27\nAWS SDK for Java 2.x Developer Guide for version 2.x\na. To manage SDK dependencies for your Gradle project, add the Maven bill of\nmaterials (BOM) for the AWS SDK for Java 2.x to the dependencies section of the\nbuild.gradle.kts file.\n...\ndependencies {\nimplementation(platform(\"software.amazon.awssdk:bom:2.27.21\"))\n// With the bom declared, you specify individual SDK dependencies without a\nversion.\n...\n}\n...\nNote\nIn this example build file, replace 2.27.21 with the latest version of the SDK for\nJava 2.x. Find the latest version available in Maven central repository.\nb. Specify the SDK modules your application needs in the dependencies section. As an\nexample, the following adds a dependency on Amazon Simple Storage Service.\n...\ndependencies {\nimplementation(platform(\"software.amazon.awssdk:bom:2.27.21\"))\nimplementation(\"software.amazon.awssdk:s3\")\n...\n}\n...\nGradle automatically resolves the correct version of declared dependencies by using the\ninformation from the BOM.\nThe following examples show complete Gradle build files in both the Kotlin and Groovy DSLs. The\nbuild file contains dependencies for Amazon S3, authentication, logging, and testing. The source\nand target version of Java is version 11.\nSet up a Gradle project 28\nAWS SDK for Java 2.x Developer Guide for version 2.x\nKotlin DSL (build.gradle.kts)\n/*\n* This file was generated by the Gradle 'init' task.\n*\n* This generated file contains a sample Java application project to get you\nstarted.\n* For more details on building Java & JVM projects, please refer to https://\ndocs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle\ndocumentation.\n*/\nplugins {\n// Apply the application plugin to add support for building a CLI application in\nJava.\napplication\n}\nrepositories {\n// Use Maven Central for resolving dependencies.", "mimetype": "text/plain", "start_char_idx": 106062, "end_char_idx": 110179, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e9f9fa2a-b624-475c-a19e-d09d8a160190": {"__data__": {"id_": "e9f9fa2a-b624-475c-a19e-d09d8a160190", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "85c32ff5-b949-4689-ad89-3c0224ad4dd7", "node_type": "1", "metadata": {}, "hash": "25bbee0c032f5983cb6770305b5d2d8fb89eba48ff286f090a2e1e17e68f9f1e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e2a931cc-815d-4690-a2f2-428c2ac14fda", "node_type": "1", "metadata": {}, "hash": "87249e27325e4828958c9064334c6bbcb56f2525d5ca620253b958a73b554b61", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following examples show complete Gradle build files in both the Kotlin and Groovy DSLs. The\nbuild file contains dependencies for Amazon S3, authentication, logging, and testing. The source\nand target version of Java is version 11.\nSet up a Gradle project 28\nAWS SDK for Java 2.x Developer Guide for version 2.x\nKotlin DSL (build.gradle.kts)\n/*\n* This file was generated by the Gradle 'init' task.\n*\n* This generated file contains a sample Java application project to get you\nstarted.\n* For more details on building Java & JVM projects, please refer to https://\ndocs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle\ndocumentation.\n*/\nplugins {\n// Apply the application plugin to add support for building a CLI application in\nJava.\napplication\n}\nrepositories {\n// Use Maven Central for resolving dependencies.\nmavenCentral()\n}\ndependencies {\nimplementation(platform(\"software.amazon.awssdk:bom:2.20.56\"))\nimplementation(\"software.amazon.awssdk:s3\")\nimplementation(\"software.amazon.awssdk:sso\")\nimplementation(\"software.amazon.awssdk:ssooidc\")\nimplementation(platform(\"org.apache.logging.log4j:log4j-bom:2.20.0\"))\nimplementation(\"org.apache.logging.log4j:log4j-slf4j2-impl\")\nimplementation(\"org.apache.logging.log4j:log4j-1.2-api\")\ntestImplementation(platform(\"org.junit:junit-bom:5.10.0\"))\ntestImplementation(\"org.junit.jupiter:junit-jupiter\")\n}\n// Apply a specific Java toolchain to ease working on different environments.\njava {\ntoolchain {\nlanguageVersion.set(JavaLanguageVersion.of(11))\n}\n}\napplication {\n// Define the main class for the application.\nSet up a Gradle project 29\nAWS SDK for Java 2.x Developer Guide for version 2.x\nmainClass.set(\"demo.App\")\n}\ntasks.named(\"test\") {\n// Use JUnit Platform for unit tests.\nuseJUnitPlatform()\n}\nGroovy DSL (build.gradle)\n/*\n* This file was generated by the Gradle 'init' task.\n*\n* This generated file contains a sample Java application project to get you\nstarted.\n* For more details on building Java & JVM projects, please refer to https://\ndocs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle\ndocumentation.\n*/\nplugins {\n// Apply the application plugin to add support for building a CLI application in\nJava.\nid 'application'\n}\nrepositories {\n// Use Maven Central for resolving dependencies.\nmavenCentral()\n}\ndependencies {\nimplementation platform('software.amazon.awssdk:bom:2.27.21')\nimplementation 'software.amazon.awssdk:s3'\nimplementation 'software.amazon.awssdk:sso'\nimplementation 'software.amazon.awssdk:ssooidc'\nimplementation platform('org.apache.logging.log4j:log4j-bom:2.20.0')\nimplementation 'org.apache.logging.log4j:log4j-slf4j2-impl'\nimplementation 'org.apache.logging.log4j:log4j-1.2-api'\ntestImplementation platform('org.junit:junit-bom:5.10.0')\ntestImplementation 'org.junit.jupiter:junit-jupiter'\n}\nSet up a Gradle project 30\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Apply a specific Java toolchain to ease working on different environments.\njava {\ntoolchain {\nlanguageVersion = JavaLanguageVersion.of(11)\n}\n}\napplication {\n// Define the main class for the application.\nmainClass = 'demo_groovy.App'\n}\ntasks.named('test') {\n// Use JUnit Platform for unit tests.\nuseJUnitPlatform()\n}\nFor next steps, see the Getting Started guide on the Gradle website for instructions on how to build\nand run a Gradle application.\nSet up a GraalVM Native Image project for the AWS SDK for\nJava\nWith versions 2.16.1 and later, the AWS SDK for Java provides out-of-the-box support for GraalVM\nNative Image applications. Use the archetype-app-quickstart Maven archetype to set up a\nproject with built-in native image support.\nPrerequisites\n\u2022 Complete the steps in Setting up the AWS SDK for Java 2.x.\n\u2022 Install GraalVM Native Image.\nCreate a project using the archetype\nTo create a Maven project with built-in native image support, in a terminal or command prompt\nwindow, use the following command.\nSet up a GraalVM Native Image project 31\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nReplace com.example.mynativeimageapp with the full package namespace of your\napplication. Also replace mynativeimageapp with your project name. This becomes the\nname of the directory for your project.", "mimetype": "text/plain", "start_char_idx": 109350, "end_char_idx": 113557, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e2a931cc-815d-4690-a2f2-428c2ac14fda": {"__data__": {"id_": "e2a931cc-815d-4690-a2f2-428c2ac14fda", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e9f9fa2a-b624-475c-a19e-d09d8a160190", "node_type": "1", "metadata": {}, "hash": "62113e3edfbbdf02cf657509688ff4184dba7f6b04af2b84f9abc92e7e674d6b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b80653b9-4e48-447c-86c0-2973bc925855", "node_type": "1", "metadata": {}, "hash": "b18fd919d4446ccd8057bb4f661a7eadccd8643c3e877e70ef850a0c635ab0ff", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use the archetype-app-quickstart Maven archetype to set up a\nproject with built-in native image support.\nPrerequisites\n\u2022 Complete the steps in Setting up the AWS SDK for Java 2.x.\n\u2022 Install GraalVM Native Image.\nCreate a project using the archetype\nTo create a Maven project with built-in native image support, in a terminal or command prompt\nwindow, use the following command.\nSet up a GraalVM Native Image project 31\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nReplace com.example.mynativeimageapp with the full package namespace of your\napplication. Also replace mynativeimageapp with your project name. This becomes the\nname of the directory for your project.\nmvn archetype:generate \\\n-DarchetypeGroupId=software.amazon.awssdk \\\n-DarchetypeArtifactId=archetype-app-quickstart \\\n-DarchetypeVersion=2.27.21\\\n-DnativeImage=true \\\n-DhttpClient=apache-client \\\n-Dservice=s3 \\\n-DgroupId=com.example.mynativeimageapp \\\n-DartifactId=mynativeimageapp \\\n-DinteractiveMode=false\nThis command creates a Maven project configured with dependencies for the AWS SDK for Java,\nAmazon S3, and the ApacheHttpClient HTTP client. It also includes a dependency for the\nGraalVM Native Image Maven plugin, so that you can build native images using Maven.\nTo include dependencies for a different Amazon Web Services, set the value of the -Dservice\nparameter to the artifact ID of that service. Examples include dynamodb, comprehend,\nand pinpoint. For a complete list of artifact IDs, see the list of managed dependencies for\nsoftware.amazon.awssdk on Maven Central.\nTo use an asynchronous HTTP client, set the -DhttpClient parameter to netty-nio-client.\nTo use UrlConnectionHttpClient as the synchronous HTTP client instead of apache-client,\nset the -DhttpClient parameter to url-connection-client.\nBuild a native image\nAfter you create the project, run the following command from your project directory, for example,\nmynativeimageapp:\nmvn package -P native-image\nBuild a native image 32\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThis creates a native image application in the target directory, for example, target/\nmynativeimageapp.\nBuild a native image 33\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse the AWS SDK for Java 2.x\nAfter completing the steps in Setting up the SDK, you are ready to make requests to AWS services\nsuch as Amazon S3, DynamoDB, IAM, Amazon EC2, and more.\nWork with service clients\nCreate a service client\nTo make a request to an AWS service, you must first instantiate a service client for that service by\nusing the static factory method, builder(). The builder() method returns a builder object\nthat allows you to customize the service client. The fluent setter methods return the builder\nobject, so that you can chain the method calls for convenience and for more readable code. After\nyou configure the properties you want, call the build() method to create the client.\nAs an example, the following code snippet instantiates an Ec2Client object as a service client for\nAmazon EC2.\nRegion region = Region.US_WEST_2;\nEc2Client ec2Client = Ec2Client.builder()\n.region(region)\n.build();\nNote\nService clients in the SDK are thread-safe. For best performance, treat them as long-lived\nobjects. Each client has its own connection pool resource that is released when the client is\ngarbage collected.\nA service client object is immutable, so you must create a new client for each service\nto which you make requests, or if you want to use a different configuration for making\nrequests to the same service.\nSpecifying the Region in the service client builder is not required for all AWS services;\nhowever, it is a best practice to set the Region for the API calls you make in your\napplications. See AWS region selection for more information.\nWork with service clients 34\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDefault client configuration\nThe client builders have another factory method named create(). This method creates a service\nclient with the default configuration. It uses the default provider chain to load credentials and\nthe AWS Region. If credentials or the Region can\u2019t be determined from the environment that the\napplication is running in, the call to create fails. See Using credentials and Region selection for\nmore information about how the SDK determines the credentials and Region to use.\nFor example, the following code snippet instantiates a DynamoDbClient object as a service client\nfor Amazon DynamoDB:\nDynamoDbClient dynamoDbClient = DynamoDbClient.create();\nConfigure service clients\nTo customize the configuration of a service client, use the setters on the builder() factory\nmethod.", "mimetype": "text/plain", "start_char_idx": 112880, "end_char_idx": 117535, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b80653b9-4e48-447c-86c0-2973bc925855": {"__data__": {"id_": "b80653b9-4e48-447c-86c0-2973bc925855", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e2a931cc-815d-4690-a2f2-428c2ac14fda", "node_type": "1", "metadata": {}, "hash": "87249e27325e4828958c9064334c6bbcb56f2525d5ca620253b958a73b554b61", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "71a3f8ff-3f46-4494-a96e-c91b6f73aa5f", "node_type": "1", "metadata": {}, "hash": "9f38fe8b128116bf42df1791087d2921d3808d9e70ab2ebc2803caa5bd2120bd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "See AWS region selection for more information.\nWork with service clients 34\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDefault client configuration\nThe client builders have another factory method named create(). This method creates a service\nclient with the default configuration. It uses the default provider chain to load credentials and\nthe AWS Region. If credentials or the Region can\u2019t be determined from the environment that the\napplication is running in, the call to create fails. See Using credentials and Region selection for\nmore information about how the SDK determines the credentials and Region to use.\nFor example, the following code snippet instantiates a DynamoDbClient object as a service client\nfor Amazon DynamoDB:\nDynamoDbClient dynamoDbClient = DynamoDbClient.create();\nConfigure service clients\nTo customize the configuration of a service client, use the setters on the builder() factory\nmethod. For convenience and to create more readable code, chain the methods to set multiple\nconfiguration options.\nThe following example shows an S3Client that is configured with several custom settings.\nClientOverrideConfiguration clientOverrideConfiguration =\nClientOverrideConfiguration.builder()\n.apiCallAttemptTimeout(Duration.ofSeconds(1))\n.retryPolicy(RetryPolicy.builder().numRetries(10).build())\n.addMetricPublisher(CloudWatchMetricPublisher.create())\n.build();\nRegion region = Region.US_WEST_2;\nS3Client s3Client = S3Client.builder()\n.region(region)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.overrideConfiguration(clientOverrideConfiguration)\n.httpClientBuilder(ApacheHttpClient.builder()\n.proxyConfiguration(proxyConfig.build(ProxyConfiguration.builder()))\n.build())\n.build();\nDefault client configuration 35\nAWS SDK for Java 2.x Developer Guide for version 2.x\nClose the service client\nAs a best practice, you should use a service clients for multiple API service calls during the life of an\napplication. However, if you need a service client for a one-time use or no longer need the service\nclient, close it.\nCall the close() method when the service client is no longer needed to free up resources.\nec2Client.close();\nIf you need a service client for one-time use, you can instantiate the service client as a resource in a\ntry-with-resources statement. Service clients implement the Autoclosable interface, so the JDK\nautomatically calls the close() method at the end of the statement.\nThe following example demonstrates how to use a service client for a one-off call. The StsClient\nthat calls the AWS Security Token Service is closed after it returns the account ID.\nimport software.amazon.awssdk.services.sts.StsClient;\nString getAccountID() {\ntry (StsClient stsClient = StsClient.create()) {\nreturn stsClient.getCallerIdentity().account();\n}\n}\nMake requests\nUse the service client to make requests to the corresponding AWS service.\nFor example, this code snippet shows how to create a RunInstancesRequest object to create a\nnew Amazon EC2 instance:\n// Create the request by using the fluid setter methods of the request builder.\nRunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()\n.imageId(amiId)\n.instanceType(InstanceType.T1_MICRO)\n.maxCount(1)\n.minCount(1)\n.build();\nClose the service client 36\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the configured request with the service client.\nRunInstancesResponse response = ec2Client.runInstances(runInstancesRequest);\nRather than create a request and pass in the instance, the SDK provides a fluent API that you can\nuse to create a request. With the fluent API you can use a Java lambda expressions to create the\nrequest 'in-line'.\nThe following example rewrites the previous example by using the version of the runInstances\nmethod that uses a builder to create the request.\n// Create the request by using a lambda expression.\nRunInstancesResponse response = ec2.runInstances(r -> r\n.imageId(amiId)\n.instanceType(InstanceType.T1_MICRO)\n.maxCount(1)\n.minCount(1));\nUse requests to override client configuration\nAlthough a service client is immutable, you can override many of its settings at the request level.\nWhen you build a request, you can provide an AwsRequestOverrideConfiguration instance to\nprovide the overridden settings. Some of the methods you can use to override client settings are:\n\u2022 apiCallAttemptTimeout\n\u2022 apiCallTimeout\n\u2022 credentialProvider\n\u2022 compressionConfiguration\n\u2022 putHeader\nFor an example of overriding a client setting with a request, assume that you have the following S3\nclient that uses default settings.\nS3Client s3Client = S3Client.create();\nYou want to download a large file and want to be sure the request doesn't timeout before the\ndownload finishes. To accomplish this, increase the timeout values for only a single GetObject\nrequest as shown in the following code.", "mimetype": "text/plain", "start_char_idx": 116608, "end_char_idx": 121457, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "71a3f8ff-3f46-4494-a96e-c91b6f73aa5f": {"__data__": {"id_": "71a3f8ff-3f46-4494-a96e-c91b6f73aa5f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b80653b9-4e48-447c-86c0-2973bc925855", "node_type": "1", "metadata": {}, "hash": "b18fd919d4446ccd8057bb4f661a7eadccd8643c3e877e70ef850a0c635ab0ff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bae9f5ee-61a4-43d3-bb37-bbba9cddd932", "node_type": "1", "metadata": {}, "hash": "fb2368b79e4ad316a8176ec88efd75a4f3e28fff5ef27f3af28fc2ea9bef5694", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "When you build a request, you can provide an AwsRequestOverrideConfiguration instance to\nprovide the overridden settings. Some of the methods you can use to override client settings are:\n\u2022 apiCallAttemptTimeout\n\u2022 apiCallTimeout\n\u2022 credentialProvider\n\u2022 compressionConfiguration\n\u2022 putHeader\nFor an example of overriding a client setting with a request, assume that you have the following S3\nclient that uses default settings.\nS3Client s3Client = S3Client.create();\nYou want to download a large file and want to be sure the request doesn't timeout before the\ndownload finishes. To accomplish this, increase the timeout values for only a single GetObject\nrequest as shown in the following code.\nUse requests to override client configuration 37\nAWS SDK for Java 2.x Developer Guide for version 2.x\nStandard API\nAwsRequestOverrideConfiguration overrideConfiguration =\nAwsRequestOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofSeconds(100L))\n.apiCallAttemptTimeout(Duration.ofSeconds(25L))\n.build();\nGetObjectRequest request = GetObjectRequest.builder()\n.bucket(\"DOC-EXAMPLE-BUCKET\")\n.key(\"DOC-EXAMPLE-KEY\")\n.overrideConfiguration(overrideConfiguration)\n.build();\ns3Client.getObject(request, myPath);\nFluent API\ns3Client.getObject(b -> b\n.bucket(\"DOC-EXAMPLE-BUCKET\")\n.key(\"DOC-EXAMPLE-KEY\")\n.overrideConfiguration(c -> c\n.apiCallTimeout(Duration.ofSeconds(100L))\n.apiCallAttemptTimeout(Duration.ofSeconds(25L))),\nmyPath);\nHandle responses\nThe SDK returns a response object for most service operations. Your code can process the\ninformation in the response object according to your needs.\nFor example, the following code snippet prints out the first instance id returned with the\nRunInstancesResponse object from the previous request.\nRunInstancesResponse runInstancesResponse =\nec2Client.runInstances(runInstancesRequest);\nSystem.out.println(runInstancesResponse.instances().get(0).instanceId());\nNot all operations return a response object with service-specific data, however. In these situations,\nyou can query the HTTP response status to learn if the operation was successful.\nHandle responses 38\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFor example, the code in the following snippet checks the HTTP response to see if the\nDeleteContactList operation of Amazon Simple Email Service was successful.\nSesV2Client sesv2Client = SesV2Client.create();\nDeleteContactListRequest request = DeleteContactListRequest.builder()\n.contactListName(\"ExampleContactListName\")\n.build();\nDeleteContactListResponse response = sesv2Client.deleteContactList(request);\nif (response.sdkHttpResponse().isSuccessful()) {\nSystem.out.println(\"Contact list deleted successfully\");\n} else {\nSystem.out.println(\"Failed to delete contact list. Status code: \" +\nresponse.sdkHttpResponse().statusCode());\n}\nHandle exceptions\nThe SDK uses runtime (or unchecked) exceptions, providing you fine-grained control over error\nhandling and ensuring that exception handling will scale with your application.\nAn SdkServiceException, or one of its sub-classes, is the most common form of exception the\nSDK will throw. These exceptions represent responses from the AWS service. You can also handle\nan SdkClientException, which occurs when there\u2019s a problem on the client side (i.e., in your\ndevelopment or application environment), such a network connection failure.\nThis code snippet demonstrates one way to handle service exceptions when you upload a file to\nAmazon S3. The example code catches both client and server exceptions, logs the details, and\nexists the application.\nRegion region = Region.US_WEST_2;\ns3Client = S3Client.builder()\n.region(region)\n.build();\ntry {\nPutObjectRequest putObjectRequest = PutObjectRequest.builder()\n.bucket(bucketName)\nHandle exceptions 39\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.key(key)\n.build();\ns3Client.putObject(putObjectRequest, RequestBody.fromString(\"SDK for Java test\"));\n} catch (S3Exception se) {\nSystem.err.println(\"Service exception thrown.\");\nSystem.err.println(se.awsErrorDetails().errorMessage());\n} catch (SdkClientExeption ce){\nSystem.err.println(\"Client exception thrown.\");\nSystem.err.println(ce.getMessage());\n} finally {\nSystem.exit(1);\n}\nSee Handling exceptions for more information.\nUse waiters\nSome requests take time to process, such as creating a new table in DynamoDB or creating a new\nAmazon S3 bucket. To ensure the resource is ready before your code continues to run, use a Waiter.", "mimetype": "text/plain", "start_char_idx": 120768, "end_char_idx": 125207, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bae9f5ee-61a4-43d3-bb37-bbba9cddd932": {"__data__": {"id_": "bae9f5ee-61a4-43d3-bb37-bbba9cddd932", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "71a3f8ff-3f46-4494-a96e-c91b6f73aa5f", "node_type": "1", "metadata": {}, "hash": "9f38fe8b128116bf42df1791087d2921d3808d9e70ab2ebc2803caa5bd2120bd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3a244935-fe9b-4da7-9ec2-47612fe7f853", "node_type": "1", "metadata": {}, "hash": "bf58a1c0e91aac192b56ad5f7fc7d689c3c2b813fb510ca4ab25a7e8fe5f08b2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nSystem.err.println(se.awsErrorDetails().errorMessage());\n} catch (SdkClientExeption ce){\nSystem.err.println(\"Client exception thrown.\");\nSystem.err.println(ce.getMessage());\n} finally {\nSystem.exit(1);\n}\nSee Handling exceptions for more information.\nUse waiters\nSome requests take time to process, such as creating a new table in DynamoDB or creating a new\nAmazon S3 bucket. To ensure the resource is ready before your code continues to run, use a Waiter.\nFor example, this code snippet creates a new table (\"myTable\") in DynamoDB, waits for the table to\nbe in an ACTIVE status, and then prints out the response:\nDynamoDbClient dynamoDbClient = DynamoDbClient.create();\nDynamoDbWaiter dynamoDbWaiter = dynamoDbClient.waiter();\nWaiterResponse waiterResponse =\ndynamoDbWaiter.waitUntilTableExists(r -> r.tableName(\"myTable\"));\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSee Using waiters for more information.\nSet timeouts\nYou can configure timeouts for each of your service clients using the apiCallTimeout and the\napiCallAttemptTimeout setters of the ClientOverrideConfiguration.Builder. The\nUse waiters 40\nAWS SDK for Java 2.x Developer Guide for version 2.x\napiCallTimeout setting is the amount of time to allow the client to complete the execution of\nan API call. The apiCallAttemptTimeout setting is the amount of time to wait for each HTTP\nrequest (retry) to complete before giving up.\nThe following example sets both timeouts for an S3 client.\nS3Client s3Client = S3Client.builder()\n.overrideConfiguration(b -> b\n.apiCallTimeout(Duration.ofSeconds(105L))\n.apiCallAttemptTimeout(Duration.ofSeconds(25L))).\nbuild();\nYou can also set timeouts at the request level by configuring an\nAwsRequestOverrideConfiguration and providing it to the request object with the\noverrideConfiguration method.\nThe following example uses the same timeout settings but at the request level for an S3\nPutObject operation.\nS3Client basicS3Client = S3Client.create(); // Client with default timeout settings.\nAwsRequestOverrideConfiguration overrideConfiguration =\nAwsRequestOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofSeconds(105L))\n.apiCallAttemptTimeout(Duration.ofSeconds(25L))\n.build();\nbasicS3Client.putObject(b -> b\n.bucket(\"DOC-EXAMPLE-BUCKET\")\n.key(\"DOC-EXAMPLE-KEY\")\n.overrideConfiguration(overrideConfiguration),\nRequestBody.fromString(\"test\"));\nExecution interceptors\nYou can write code that intercepts the execution of your API requests and responses at different\nparts of the request/response lifecycle. This enables you to publish metrics, modify a request\nin-flight, debug request processing, view exceptions, and more. For more information, see the\nExecutionInterceptor interface in the AWS SDK for Java API Reference.\nExecution interceptors 41\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConfigure SDK authentication\nBefore making a request to Amazon Web Services using the AWS SDK for Java 2.x, the SDK\ncryptographically signs temporary credentials issued by AWS. To access temporary credentials, the\nSDK retrieves configuration values by checking several locations.\nThis topic discusses several ways that you enable the SDK to access temporary credentials.\nTopics\n\u2022 Configure access to temporary credentials\n\u2022 Default credentials provider chain\n\u2022 Use a specific credentials provider\n\u2022 Use profiles\n\u2022 Load temporary credentials from an external process\n\u2022 Supply temporary credentials in code\n\u2022 Read IAM role credentials on Amazon EC2\nConfigure access to temporary credentials\nFor increased security, AWS recommends that you configure the SDK for Java to use temporary\ncredentials instead of long-lived credentials. Temporary credentials consist of access keys (access\nkey id and secret access key) and a session token. We recommend that you configure the SDK to\nautomatically get temporary credentials, since the token refresh process is automatic. You can,\nhowever, provide the SDK with temporary credentials directly.\nIAM Identity Center configuration\nWhen you configure the SDK to use IAM Identity Center single sign-on access as described in ??? in\nthis guide, the SDK automatically uses temporary credentials.\nThe SDK uses the IAM Identity Center access token to gain access to the IAM role that is configured\nwith the sso_role_name setting in your config file. The SDK assumes this IAM role and retrieves\ntemporary credentials to use for AWS service requests.\nFor more details about how the SDK gets temporary credentials from the configuration, see the\nUnderstanding IAM Identity Center authentication section of the AWS SDKs and Tools Reference\nGuide.", "mimetype": "text/plain", "start_char_idx": 124748, "end_char_idx": 129382, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3a244935-fe9b-4da7-9ec2-47612fe7f853": {"__data__": {"id_": "3a244935-fe9b-4da7-9ec2-47612fe7f853", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bae9f5ee-61a4-43d3-bb37-bbba9cddd932", "node_type": "1", "metadata": {}, "hash": "fb2368b79e4ad316a8176ec88efd75a4f3e28fff5ef27f3af28fc2ea9bef5694", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "89413d59-1d59-4f2b-bd2a-401f5d10a8b2", "node_type": "1", "metadata": {}, "hash": "a5b4a8581dbadd5e7c6beb069b106410237506b720a7e3d85fe9c31dca23fa67", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Temporary credentials consist of access keys (access\nkey id and secret access key) and a session token. We recommend that you configure the SDK to\nautomatically get temporary credentials, since the token refresh process is automatic. You can,\nhowever, provide the SDK with temporary credentials directly.\nIAM Identity Center configuration\nWhen you configure the SDK to use IAM Identity Center single sign-on access as described in ??? in\nthis guide, the SDK automatically uses temporary credentials.\nThe SDK uses the IAM Identity Center access token to gain access to the IAM role that is configured\nwith the sso_role_name setting in your config file. The SDK assumes this IAM role and retrieves\ntemporary credentials to use for AWS service requests.\nFor more details about how the SDK gets temporary credentials from the configuration, see the\nUnderstanding IAM Identity Center authentication section of the AWS SDKs and Tools Reference\nGuide.\nConfigure SDK authentication 42\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIt addition to the configuration that you set in the config file that works for all projects,\neach individual Java project requires that the Maven pom.xml file contains the following\ndependencies:\n\nsoftware.amazon.awssdk\nsso\n\n\nsoftware.amazon.awssdk\nssooidc\n\nThe sso and ssooidc dependencies provide the code that enables the SDK for Java 2.x to\naccess temporary credentials.\nRetrieve from AWS access portal\nAs an alternative to IAM Identity Center single sign-on configuration, you can copy and use\ntemporary credentials available in the AWS access portal. You can use the temporary credentials in\na profile or use them as values for system properties and environment variables.\nSet up a local credentials file for temporary credentials\n1. Create a shared credentials file\n2. In the credentials file, paste the following placeholder text until you paste in working\ntemporary credentials.\n[default]\naws_access_key_id=\naws_secret_access_key=\naws_session_token=\n3. Save the file. The file ~/.aws/credentials should now exist on your local development\nsystem. This file contains the [default] profile that the SDK for Java uses if a specific named\nprofile is not specified.\nConfigure access to temporary credentials 43\nAWS SDK for Java 2.x Developer Guide for version 2.x\n4. Sign in to the AWS access portal\n5. Follow these instructions under the Manual credential refresh heading to copy IAM role\ncredentials from the AWS access portal.\na. For step 4 in the linked instructions, choose the IAM role name that grants access for your\ndevelopment needs. This role typically has a name like PowerUserAccess or Developer.\nb. For step 7, select the Manually add a profile to your AWS credentials file option and\ncopy the contents.\n6. Paste the copied credentials into your local credentials file and remove the generated\nprofile name. Your file should resemble the following.\n[default]\naws_access_key_id=AKIAIOSFODNN7EXAMPLE\naws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\naws_session_token=IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZVERYLONGSTRINGEXAMPLE\n7. Save the credentials file.\nWhen the SDK for Java creates a service client, it will access these temporary credentials and use\nthem for each request. The settings for the IAM role chosen in step 5a determine how long the\ntemporary credentials are valid. The maximum duration is twelve hours.\nAfter the temporary credentials expire, repeat steps 4 through 7.\nDefault credentials provider chain\nThe default credentials provider chain is implemented by the DefaultCredentialsProvider class.\nIt sequentially checks each place where you can set the default configuration for supplying\ntemporary credentials, and then selects the first one you set.\nTo use the default credentials provider chain to supply temporary credentials, create a service\nclient builder but don't specify a credentials provider. The following code snippet creates a\nDynamoDbClient that uses the default credentials provider chain to locate and retrieve default\nconfiguration settings.\nRegion region = Region.US_WEST_2;\nDynamoDbClient ddb =\nDynamoDbClient.builder()\nDefault credentials provider chain 44\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(region)\n.build();\nCredential settings retrieval order\nThe default credentials provider chain of the SDK for Java 2.x searches for configuration in your\nenvironment using a predefined sequence.\n1.", "mimetype": "text/plain", "start_char_idx": 128438, "end_char_idx": 133114, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "89413d59-1d59-4f2b-bd2a-401f5d10a8b2": {"__data__": {"id_": "89413d59-1d59-4f2b-bd2a-401f5d10a8b2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3a244935-fe9b-4da7-9ec2-47612fe7f853", "node_type": "1", "metadata": {}, "hash": "bf58a1c0e91aac192b56ad5f7fc7d689c3c2b813fb510ca4ab25a7e8fe5f08b2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c0a129e3-b2c5-464c-a622-28b9260944f2", "node_type": "1", "metadata": {}, "hash": "5f04af87c8c6f463564e5feb4c40f76e01341f9bcefd1547a1e8f813b6efb9b6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "After the temporary credentials expire, repeat steps 4 through 7.\nDefault credentials provider chain\nThe default credentials provider chain is implemented by the DefaultCredentialsProvider class.\nIt sequentially checks each place where you can set the default configuration for supplying\ntemporary credentials, and then selects the first one you set.\nTo use the default credentials provider chain to supply temporary credentials, create a service\nclient builder but don't specify a credentials provider. The following code snippet creates a\nDynamoDbClient that uses the default credentials provider chain to locate and retrieve default\nconfiguration settings.\nRegion region = Region.US_WEST_2;\nDynamoDbClient ddb =\nDynamoDbClient.builder()\nDefault credentials provider chain 44\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(region)\n.build();\nCredential settings retrieval order\nThe default credentials provider chain of the SDK for Java 2.x searches for configuration in your\nenvironment using a predefined sequence.\n1. Java system properties\n\u2022 The SDK uses the SystemPropertyCredentialsProvider class to load temporary credentials\nfrom the aws.accessKeyId, aws.secretAccessKey, and aws.sessionToken Java\nsystem properties.\nNote\nFor information on how to set Java system properties, see the System Properties\ntutorial on the official Java Tutorials website.\n2. Environment variables\n\u2022 The SDK uses the EnvironmentVariableCredentialsProvider class to load temporary credentials\nfrom the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN\nenvironment variables.\n3. Web identity token from AWS Security Token Service\n\u2022 The SDK uses the WebIdentityTokenFileCredentialsProvider class to load temporary\ncredentials from Java system properties or environment variables.\n4. The shared credentials and config files\n\u2022 The SDK uses the ProfileCredentialsProvider to load IAM Identity Center single sign-on\nsettings or temporary credentials from the [default] profile in the shared credentials\nand config files.\nThe AWS SDKs and Tools Reference Guide has detailed information about how the SDK for\nJava works with the IAM Identity Center single sign-on token to get temporary credentials\nthat the SDK uses to call AWS services.\nDefault credentials provider chain 45\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nThe credentials and config files are shared by various AWS SDKs and Tools. For\nmore information, see The .aws/credentials and .aws/config files in the AWS SDKs and\nTools Reference Guide.\n5. Amazon ECS container credentials\n\u2022 The SDK uses the ContainerCredentialsProvider class to load temporary credentials from the\nfollowing environment variables:\nAWS_CONTAINER_CREDENTIALS_RELATIVE_URI or\nAWS_CONTAINER_CREDENTIALS_FULL_URI\nAWS_CONTAINER_AUTHORIZATION_TOKEN_FILE or\nAWS_CONTAINER_AUTHORIZATION_TOKEN\n6. Amazon EC2 instance IAM role-provided credentials\n\u2022 The SDK uses the InstanceProfileCredentialsProvider class to load temporary credentials from\nthe Amazon EC2 metadata service.\nUse a specific credentials provider\nThe SDK uses credentials providers to retrieve, manage, and supply authentication credentials\n(such as access keys and session tokens) that are needed to access AWS services.\nCredential providers simplify retrieving credentials from various sources, implement security best\npractices, and support flexible authentication strategies across AWS environments.\nSpecify a credentials provider\nTo bypass the default credentials provider chain, specify which credentials provider a service client\nshould use. When you supply a specific credentials provider, the SDK skips the process of checking\nvarious locations, which slightly reduces the time to create a service client.\nFor example, if you set your default configuration using environment variables, supply an\nEnvironmentVariableCredentialsProvider object to the credentialsProvider method on the\nservice client builder, as shown the following code snippet:\nRegion region = Region.US_WEST_2;\nUse a specific credentials provider 46\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\nFor a complete list of credential providers and provider chains, see All Known Implementing\nClasses in the API reference for AwsCredentialsProvider.\nNote\nYou can also use your own credentials provider or provider chains by implementing the\nAwsCredentialsProvider interface.\nConfigure a credentials provider\nAs an example of configuring a credentials provider implementation, you might want to have the\nSDK use a background thread to pre-fetch (retrieve in advance) credentials before they expire. That\nway you can avoid the blocking call that retrieves fresh credentials.", "mimetype": "text/plain", "start_char_idx": 132080, "end_char_idx": 136884, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c0a129e3-b2c5-464c-a622-28b9260944f2": {"__data__": {"id_": "c0a129e3-b2c5-464c-a622-28b9260944f2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "89413d59-1d59-4f2b-bd2a-401f5d10a8b2", "node_type": "1", "metadata": {}, "hash": "a5b4a8581dbadd5e7c6beb069b106410237506b720a7e3d85fe9c31dca23fa67", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "58466317-2e44-4d07-b031-73f32f4bbf4f", "node_type": "1", "metadata": {}, "hash": "03377d2469d54e984a5612e4f5ca98710b2519bd740b07506c061a9d05110193", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Note\nYou can also use your own credentials provider or provider chains by implementing the\nAwsCredentialsProvider interface.\nConfigure a credentials provider\nAs an example of configuring a credentials provider implementation, you might want to have the\nSDK use a background thread to pre-fetch (retrieve in advance) credentials before they expire. That\nway you can avoid the blocking call that retrieves fresh credentials.\nThe following shows an example that creates an StsAssumeRoleCredentialsProvider\nthat uses a background thread to pre-fetch credentials by setting the\nasyncCredentialUpdateEnabled property to true on the builder:\nS3Client s3Client = S3Client.builder()\n.credentialsProvider(StsAssumeRoleCredentialsProvider.builder()\n.asyncCredentialUpdateEnabled(true)\n.stsClient(StsClient.create())\n.refreshRequest(r -> r\n.roleArn(\"arn:aws:iam::111122223333:role/S3-listbuckets-only-role\")\n.roleSessionName(\"test-temp-session\")\n.durationSeconds(900))\n.build())\n.build();\nWhen you invoke an operation on s3Client for the first time, an AssumeRoleRequest is sent\nto the AWS Security Token Service (STS). STS returns temporary credentials that are valid for 15\nminutes (900 seconds). The s3Client instance uses the cached credentials until it's time to refresh\nthem before the 15 minutes elapse. By default, the SDK attempts to retrieve new credentials for\nUse a specific credentials provider 47\nAWS SDK for Java 2.x Developer Guide for version 2.x\na new session between 5 minutes and 1 minute before the expiration time of the current session.\nThe pre-fetch window is configurable by using the prefetchTime and staleTime properties.\nYou can configure the following session-based credentials providers similarly:\n\u2022 StsWebIdentityTokenFileCredentialsProvider\n\u2022 StsGetSessionTokenCredentialsProvider\n\u2022 StsGetFederationTokenCredentialsProvider\n\u2022 StsAssumeRoleWithWebIdentityCredentialsProvider\n\u2022 StsAssumeRoleWithSamlCredentialsProvider\n\u2022 StsAssumeRoleCredentialsProvider\n\u2022 DefaultCredentialsProvider (when it delegates to credentials provider that uses sessions)\n\u2022 ProcessCredentialsProvider\n\u2022 WebIdentityTokenFileCredentialsProvider\n\u2022 ContainerCredentialsProvider\n\u2022 InstanceProfileCredentialsProvider\nUse profiles\nUsing the shared config and credentials file, you can set up several profiles. This enables\nyour application to use multiple sets of credentials configuration. The [default] profile was\nmentioned previously. The SDK uses the ProfileCredentialsProvider class to load settings from\nprofiles defined in the shared credentials file.\nThe following code snippet demonstrates how to build a service client that uses the settings\ndefined as part of the profile named my_profile.\nRegion region = Region.US_WEST_2;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.credentialsProvider(ProfileCredentialsProvider.create(\"my_profile\"))\n.build();\nSet a different profile as the default\nTo set a profile other than the [default] profile as the default for your application, set the\nAWS_PROFILE environment variable to the name of your custom profile.\nUse profiles 48\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo set this variable on Linux, macOS, or Unix, use export:\nexport AWS_PROFILE=\"other_profile\"\nTo set these variables on Windows, use set:\nset AWS_PROFILE=\"other_profile\"\nAlternatively, set the aws.profile Java system property to the name of the profile.\nReload profile credentials\nYou can configure any credentials provider that has a profileFile() method on its builder to\nreload profile credentials. These credentials profile classes are: ProfileCredentialsProvider,\nDefaultCredentialsProvider, InstanceProfileCredentialsProvider, and\nProfileTokenProvider.\nNote\nProfile credential reloading works only with the following settings in the profile file :\naws_access_key_id, aws_secret_access_key, and aws_session_token.\nSettings such as region, sso_session, sso_account_id, and source_profile are\nignored.\nTo configure a supported credentials provider to reload profile settings, provide an instance of\nProfileFileSupplier to the profileFile() builder method. The following code example\ndemonstrates a ProfileCredentialsProvider that reloads credential settings from the\n[default] profile.\nProfileCredentialsProvider provider = ProfileCredentialsProvider\n.builder()\n.profileFile(ProfileFileSupplier.defaultSupplier())\n.build();\n// Set up a service client with the provider instance.\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.credentialsProvider(provider)\n.build();\nUse profiles 49\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/*\nBefore dynamoDbClient makes a request, it reloads the credentials settings\nby calling provider.resolveCredentials().\n*/\nWhen ProfileCredentialsProvider.resolveCredentials() is called, the SDK for\nJava reloads the settings. ProfileFileSupplier.defaultSupplier() is one of several\nconvenience implementations of ProfileFileSupplier provided by the SDK. If your use case\nrequires, you can provide your own implementation.", "mimetype": "text/plain", "start_char_idx": 136462, "end_char_idx": 141493, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "58466317-2e44-4d07-b031-73f32f4bbf4f": {"__data__": {"id_": "58466317-2e44-4d07-b031-73f32f4bbf4f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c0a129e3-b2c5-464c-a622-28b9260944f2", "node_type": "1", "metadata": {}, "hash": "5f04af87c8c6f463564e5feb4c40f76e01341f9bcefd1547a1e8f813b6efb9b6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "995591b5-a45a-4b9c-8e62-c2e7b5d22e8e", "node_type": "1", "metadata": {}, "hash": "9450eae3f1313904fd00fb5cc967f7989be91ad8800811efed6268d1748bb91f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following code example\ndemonstrates a ProfileCredentialsProvider that reloads credential settings from the\n[default] profile.\nProfileCredentialsProvider provider = ProfileCredentialsProvider\n.builder()\n.profileFile(ProfileFileSupplier.defaultSupplier())\n.build();\n// Set up a service client with the provider instance.\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.credentialsProvider(provider)\n.build();\nUse profiles 49\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/*\nBefore dynamoDbClient makes a request, it reloads the credentials settings\nby calling provider.resolveCredentials().\n*/\nWhen ProfileCredentialsProvider.resolveCredentials() is called, the SDK for\nJava reloads the settings. ProfileFileSupplier.defaultSupplier() is one of several\nconvenience implementations of ProfileFileSupplier provided by the SDK. If your use case\nrequires, you can provide your own implementation.\nThe following example shows the use of the ProfileFileSupplier.reloadWhenModified()\nconvenience method. reloadWhenModified() takes a Path parameter, which gives you\nflexibility in designating the source file for the configuration rather than the standard ~/.aws/\ncredentials (or config) location.\nThe settings will be reloaded when resolveCredentials() is called only if SDK determines the\nfile's content has been modified.\nPath credentialsFilePath = ...\nProfileCredentialsProvider provider = ProfileCredentialsProvider\n.builder()\n.profileFile(ProfileFileSupplier.reloadWhenModified(credentialsFilePath,\nProfileFile.Type.CREDENTIALS))\n.profileName(\"my-profile\")\n.build();\n/*\nA service client configured with the provider instance calls\nprovider.resolveCredential()\nbefore each request.\n*/\nThe ProfileFileSupplier.aggregate() method merges the contents of multiple\nconfiguration files. You decide whether a file is reloaded per call to resolveCredentials() or a\nfile's settings are fixed at the time it was first read.\nThe following example shows a DefaultCredentialsProvider that merges the settings of\ntwo files that contain profile settings. The SDK reloads the settings in the file pointed to by the\ncredentialsFilePath variable each time resolveCredentials() is called and the settings\nhave changed. The settings from the profileFile object remain the same.\nUse profiles 50\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPath credentialsFilePath = ...;\nProfileFile profileFile = ...;\nDefaultCredentialsProvider provider = DefaultCredentialsProvider\n.builder()\n.profileFile(ProfileFileSupplier.aggregate(\nProfileFileSupplier.reloadWhenModified(credentialsFilePath,\nProfileFile.Type.CREDENTIALS),\nProfileFileSupplier.fixedProfileFile(profileFile)))\n.profileName(\"my-profile\")\n.build();\n/*\nA service client configured with the provider instance calls\nprovider.resolveCredential()\nbefore each request.\n*/\nLoad temporary credentials from an external process\nWarning\nThe following describes a method of sourcing temporary credentials from an external\nprocess. This can potentially be dangerous, so proceed with caution. Other credential\nproviders should be preferred if at all possible. If using this option, you should make sure\nthat the config file is as locked down as possible using security best practices for your\noperating system.\nMake sure that your custom credentials tool does not write any secret information to\nStdErr. SDKs and AWS CLI can capture and log such information, potentially exposing it to\nunauthorized users.\nWith the SDK for Java 2.x, you can acquire temporary credentials from an external process for\ncustom use cases. There are two ways to configure this functionality.\nUse the credential_process setting\nIf you have a method that provides temporary credentials, you can integrate it by adding the\ncredential_process setting as part of a profile definition in the config file. The value you\nspecify must use the full path to the command file. If the file path contains any spaces, you must\nsurround it with quotation marks.\nLoad temporary credentials from an external process 51\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe SDK calls the command exactly as given and then reads JSON data from stdout.\nThe following examples show the use of this setting for file paths without spaces and file paths\nwith spaces.\nLinux/macOS\nNo spaces in file path\n[profile process-credential-profile]\ncredential_process = /path/to/credential/file/credential_file.sh --custom-command\ncustom_parameter\nSpaces in file path\n[profile process-credential-profile]\ncredential_process = \"/path/with/space to/credential/file/credential_file.sh\" --\ncustom-command custom_parameter\nWindows\nNo spaces in file path\n[profile process-credential-profile]\ncredential_process = C:\\Path\\To\\credentials.cmd --custom_command custom_parameter\nSpaces in file path\n[profile process-credential-profile]\ncredential_process = \"C:\\Path\\With Space To\\credentials.cmd\" --custom_command\ncustom_parameter\nThe following code snippet demonstrates how to build a service client that uses the temporary\ncredentials defined as part of the profile named process-credential-profile.", "mimetype": "text/plain", "start_char_idx": 140556, "end_char_idx": 145661, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "995591b5-a45a-4b9c-8e62-c2e7b5d22e8e": {"__data__": {"id_": "995591b5-a45a-4b9c-8e62-c2e7b5d22e8e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "58466317-2e44-4d07-b031-73f32f4bbf4f", "node_type": "1", "metadata": {}, "hash": "03377d2469d54e984a5612e4f5ca98710b2519bd740b07506c061a9d05110193", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c08e079c-16f8-4408-9b98-7c73c5c1e11e", "node_type": "1", "metadata": {}, "hash": "20ee2a8d448f9723d397e40b8d94afa0fc51de2c4d7ccb5b1766e969c4cb10eb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following examples show the use of this setting for file paths without spaces and file paths\nwith spaces.\nLinux/macOS\nNo spaces in file path\n[profile process-credential-profile]\ncredential_process = /path/to/credential/file/credential_file.sh --custom-command\ncustom_parameter\nSpaces in file path\n[profile process-credential-profile]\ncredential_process = \"/path/with/space to/credential/file/credential_file.sh\" --\ncustom-command custom_parameter\nWindows\nNo spaces in file path\n[profile process-credential-profile]\ncredential_process = C:\\Path\\To\\credentials.cmd --custom_command custom_parameter\nSpaces in file path\n[profile process-credential-profile]\ncredential_process = \"C:\\Path\\With Space To\\credentials.cmd\" --custom_command\ncustom_parameter\nThe following code snippet demonstrates how to build a service client that uses the temporary\ncredentials defined as part of the profile named process-credential-profile.\nRegion region = Region.US_WEST_2;\nS3Client s3Client = S3Client.builder()\n.region(region)\n.credentialsProvider(ProfileCredentialsProvider.create(\"process-credential-\nprofile\"))\nLoad temporary credentials from an external process 52\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nFor detailed information about using an external process as a source of temporary credentials,\nrefer to the process credentials section in the AWS SDKs and Tools Reference Guide.\nUse a ProcessCredentialsProvider\nAs an alternative to using settings in the config file, you can use the SDK's\nProcessCredentialsProvider to load temporary credentials using Java.\nThe following examples show various versions of how to specify an external process using the\nProcessCredentialsProvider and configuring a service client that uses the temporary\ncredentials.\nLinux/macOS\nNo spaces in file path\nProcessCredentialsProvider credentials =\nProcessCredentialsProvider\n.builder()\n.command(\"/path/to/credentials.sh optional_param1 optional_param2\")\n.build();\nS3Client s3 = S3Client.builder()\n.region(Region.US_WEST_2)\n.credentialsProvider(credentials)\n.build();\nSpaces in file path\nProcessCredentialsProvider credentials =\nProcessCredentialsProvider\n.builder()\n.command(\"/path\\\\ with\\\\ spaces\\\\ to/credentials.sh optional_param1\noptional_param2\")\n.build();\nS3Client s3 = S3Client.builder()\n.region(Region.US_WEST_2)\n.credentialsProvider(credentials)\nLoad temporary credentials from an external process 53\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nWindows\nNo spaces in file path\nProcessCredentialsProvider credentials =\nProcessCredentialsProvider\n.builder()\n.command(\"C:\\\\Path\\\\To\\\\credentials.exe optional_param1 optional_param2\")\n.build();\nS3Client s3 = S3Client.builder()\n.region(Region.US_WEST_2)\n.credentialsProvider(credentials)\n.build();\nSpaces in file path\nProcessCredentialsProvider credentials =\nProcessCredentialsProvider\n.builder()\n.command(\"\\\"C:\\\\Path\\\\With Spaces To\\\\credentials.exe\\\" optional_param1\noptional_param2\")\n.build();\nS3Client s3 = S3Client.builder()\n.region(Region.US_WEST_2)\n.credentialsProvider(credentials)\n.build();\nUse IAM Roles Anywhere for authentication\nIAM Roles Anywhere is an AWS service that allows you to obtain temporary AWS credentials for\nworkloads running outside of AWS. It enables secure access to AWS resources from on-premises or\nother cloud environments.\nBefore you can authenticate requests with IAM Roles Anywhere, you first need to gather the\nrequired information and download the credential helper tool. By following the Getting started\ninstructions in the IAM Roles Anywhere User Guide, you can create the necessary artifacts.\nLoad temporary credentials from an external process 54\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe SDK for Java doesn't have a dedicated credentials provider to retrieve temporary credentials\nfrom IAM Roles Anywhere, but you can use the credential helper tool along with one of the options\nto retrieve credentials from an external process.\nUse the credential_process setting in a profile\nThe following snippet in the shared AWS config file shows a profile named roles_anywhere that\nuses the credential_process setting:\n[profile roles_anywhere]\ncredential_process = ./aws_signing_helper credential-process \\\n--certificate /path/to/certificate \\\n--private-key /path/to/private-key \\\n--trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID \\\n--profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \\\n--role-arn arn:aws:iam::account:role/role-name-with-path\nYou need to replace the text shown in red with your values after you have assembled all the\nartifacts. The first element in the setting, aws_signing_helper, is the executable of the\ncredential helper tool and credential-process is the command.", "mimetype": "text/plain", "start_char_idx": 144738, "end_char_idx": 149482, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c08e079c-16f8-4408-9b98-7c73c5c1e11e": {"__data__": {"id_": "c08e079c-16f8-4408-9b98-7c73c5c1e11e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "995591b5-a45a-4b9c-8e62-c2e7b5d22e8e", "node_type": "1", "metadata": {}, "hash": "9450eae3f1313904fd00fb5cc967f7989be91ad8800811efed6268d1748bb91f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34160ac3-06ae-4c64-865e-51d0ce5baa9b", "node_type": "1", "metadata": {}, "hash": "d141c3e6321e69d0600b2589eebc7b2f5d5b92c3a9b3a58491fe4c0bd10ef129", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use the credential_process setting in a profile\nThe following snippet in the shared AWS config file shows a profile named roles_anywhere that\nuses the credential_process setting:\n[profile roles_anywhere]\ncredential_process = ./aws_signing_helper credential-process \\\n--certificate /path/to/certificate \\\n--private-key /path/to/private-key \\\n--trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID \\\n--profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \\\n--role-arn arn:aws:iam::account:role/role-name-with-path\nYou need to replace the text shown in red with your values after you have assembled all the\nartifacts. The first element in the setting, aws_signing_helper, is the executable of the\ncredential helper tool and credential-process is the command.\nWhen you configure a service client to use the roles_anywhere profile\u2014as shown in the\nfollowing code\u2014the SDK caches the temporary credentials and refreshes them before they expire:\nS3Client s3Client = S3Client.builder()\n.credentialsProvider(ProfileCredentialsProvider.builder()\n.profileName(\"roles_anywhere\").build())\n.build();\nConfigure a ProcessCredentialsProvider\nAs shown next, you can use a code-only approach with the ProcessCredentialsProvider\ninstead of using profile settings:\nProcessCredentialsProvider processCredentialsProvider =\nProcessCredentialsProvider.builder()\n.command(\"\"\"\n./aws_signing_helper credential-process \\\n--certificate /path/to/certificate \\\n--private-key /path/to/private-key \\\n--trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID\n\\\nLoad temporary credentials from an external process 55\nAWS SDK for Java 2.x Developer Guide for version 2.x\n--profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \\\n--role-arn arn:aws:iam::account:role/role-name-with-path\n\"\"\").build();\nS3Client s3Client = S3Client.builder()\n.credentialsProvider(processCredentialsProvider)\n.build();\nReplace the text shown in red with your values after you have assembled all the artifacts.\nSupply temporary credentials in code\nIf the default credential chain or a specific or custom provider or provider chain doesn't work for\nyour application, you can supply temporary credentials directly in code. These can be IAM role\ncredentials as described above or temporary credentials retrieved from AWS Security Token Service\n(AWS STS). If you retrieved temporary credentials using AWS STS, provide them to an AWS service\nclient as shown in the following code example.\n1. Assume a role by calling StsClient.assumeRole().\n2. Create a StaticCredentialsProvider object and supply it with the AwsSessionCredentials\nobject.\n3. Configure the service client builder with the StaticCredentialsProvider and build the\nclient.\nThe following example creates an Amazon S3 service client using temporary credentials returned\nby AWS STS for an IAM assumed role.\n// The AWS IAM Identity Center identity (user) who executes this method does not\nhave permission to list buckets.\n// The identity is configured in the [default] profile.\npublic static void assumeRole(String roleArn, String roleSessionName) {\n// The IAM role represented by the 'roleArn' parameter can be assumed by\nidentities in two different accounts\n// and the role permits the user to only list buckets.\n// The SDK's default credentials provider chain will find the single sign-on\nsettings in the [default] profile.\n// The identity configured with the [default] profile needs permission to call\nAssumeRole on the STS service.\ntry {\nSupply temporary credentials in code 56\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCredentials tempRoleCredentials;\ntry (StsClient stsClient = StsClient.create()) {\nAssumeRoleRequest roleRequest = AssumeRoleRequest.builder()\n.roleArn(roleArn)\n.roleSessionName(roleSessionName)\n.build();\nAssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);\ntempRoleCredentials = roleResponse.credentials();\n}\n// Use the following temporary credential items for the S3 client.\nString key = tempRoleCredentials.accessKeyId();\nString secKey = tempRoleCredentials.secretAccessKey();\nString secToken = tempRoleCredentials.sessionToken();\n// List all buckets in the account associated with the assumed role\n// by using the temporary credentials retrieved by invoking\nstsClient.assumeRole().", "mimetype": "text/plain", "start_char_idx": 148692, "end_char_idx": 152987, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "34160ac3-06ae-4c64-865e-51d0ce5baa9b": {"__data__": {"id_": "34160ac3-06ae-4c64-865e-51d0ce5baa9b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c08e079c-16f8-4408-9b98-7c73c5c1e11e", "node_type": "1", "metadata": {}, "hash": "20ee2a8d448f9723d397e40b8d94afa0fc51de2c4d7ccb5b1766e969c4cb10eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d610d334-8512-44a1-b56f-2cd0e9812770", "node_type": "1", "metadata": {}, "hash": "8367900273431f91de700c9ed217b7bbee9420e95aeff09949715328dbb2a98a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// The identity configured with the [default] profile needs permission to call\nAssumeRole on the STS service.\ntry {\nSupply temporary credentials in code 56\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCredentials tempRoleCredentials;\ntry (StsClient stsClient = StsClient.create()) {\nAssumeRoleRequest roleRequest = AssumeRoleRequest.builder()\n.roleArn(roleArn)\n.roleSessionName(roleSessionName)\n.build();\nAssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);\ntempRoleCredentials = roleResponse.credentials();\n}\n// Use the following temporary credential items for the S3 client.\nString key = tempRoleCredentials.accessKeyId();\nString secKey = tempRoleCredentials.secretAccessKey();\nString secToken = tempRoleCredentials.sessionToken();\n// List all buckets in the account associated with the assumed role\n// by using the temporary credentials retrieved by invoking\nstsClient.assumeRole().\nStaticCredentialsProvider staticCredentialsProvider =\nStaticCredentialsProvider.create(\nAwsSessionCredentials.create(key, secKey, secToken));\ntry (S3Client s3 = S3Client.builder()\n.credentialsProvider(staticCredentialsProvider)\n.build()) {\nList buckets = s3.listBuckets().buckets();\nfor (Bucket bucket : buckets) {\nSystem.out.println(\"bucket name: \" + bucket.name());\n}\n}\n} catch (StsException | S3Exception e) {\nlogger.error(e.getMessage());\nSystem.exit(1);\n}\n}\nPermission set\nThe following permission set defined in AWS IAM Identity Center allows the identity (user) to\nperform the following two operations\n1. The GetObject operation of the Amazon Simple Storage Service.\n2. The AssumeRole operation of the AWS Security Token Service.\nSupply temporary credentials in code 57\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWithout assuming the role, the s3.listBuckets() method shown in the example would fail.\n{\n\"Version\": \"2012-10-17\",\n\"Statement\": [\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"s3:GetObject\",\n\"sts:AssumeRole\"\n],\n\"Resource\": [\n\"*\"\n]\n}\n]\n}\nAssumed role\nAssumed role permissions policy\nThe following permissions policy is attached to the role that is assume in the previous example.\nThis permissions policy permits the ability to list all buckets in the same account as the role.\n{\n\"Version\": \"2012-10-17\",\n\"Statement\": [\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"s3:ListAllMyBuckets\"\n],\n\"Resource\": [\n\"*\"\n]\n}\n]\n}\nSupply temporary credentials in code 58\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAssumed role trust policy\nThe following trust policy is attached to the role that is assume in the previous example. The policy\nallows the role to be assumed by identities (users) in two accounts.\n{\n\"Version\": \"2012-10-17\",\n\"Statement\": [\n{\n\"Effect\": \"Allow\",\n\"Principal\": {\n\"AWS\": [\n\"arn:aws:iam::111122223333:root\",\n\"arn:aws:iam::555555555555:root\"\n]\n},\n\"Action\": \"sts:AssumeRole\",\n\"Condition\": {}\n}\n]\n}\nRead IAM role credentials on Amazon EC2\nYou can use an IAM role to manage temporary credentials for applications that are running on an\nEC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys\nwithin the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of\nits applications, you create an instance profile that is attached to the instance. An instance profile\ncontains the role and enables programs that are running on the EC2 instance to get temporary\ncredentials. For more information, see Use an IAM role to grant permissions to applications running\non Amazon EC2 instances in the IAM User Guide.\nThis topic provides information on how to set up your Java application to run on an EC2 instance\nand enable the SDK for Java to acquire IAM role credentials.\nAcquire IAM role credentials from the environment\nIf your application creates an AWS service client by using the create method (or\nbuilder().build() methods), the SDK for Java uses the default credentials provider chain. The\ndefault credentials provider chain searches the execution environment for configuration elements\nRead IAM role credentials on Amazon EC2 59\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthat the SDK can trade for temporary credentials. The the section called \u201cDefault credentials\nprovider chain\u201d section describes the full search process.\nThe final step in the default provider chain is available only when your application runs on an\nAmazon EC2 instance. In this step, the SDK uses an InstanceProfileCredentialsProvider to\nread the IAM role defined in the EC2 instance profile.", "mimetype": "text/plain", "start_char_idx": 152078, "end_char_idx": 156555, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d610d334-8512-44a1-b56f-2cd0e9812770": {"__data__": {"id_": "d610d334-8512-44a1-b56f-2cd0e9812770", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34160ac3-06ae-4c64-865e-51d0ce5baa9b", "node_type": "1", "metadata": {}, "hash": "d141c3e6321e69d0600b2589eebc7b2f5d5b92c3a9b3a58491fe4c0bd10ef129", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6af49c03-fe53-4a07-8dc1-0eeca6a3b8a1", "node_type": "1", "metadata": {}, "hash": "e516d274d12718cb263dce63de5163dae8649c8f28e606b85fa2b4564215c6d0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This topic provides information on how to set up your Java application to run on an EC2 instance\nand enable the SDK for Java to acquire IAM role credentials.\nAcquire IAM role credentials from the environment\nIf your application creates an AWS service client by using the create method (or\nbuilder().build() methods), the SDK for Java uses the default credentials provider chain. The\ndefault credentials provider chain searches the execution environment for configuration elements\nRead IAM role credentials on Amazon EC2 59\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthat the SDK can trade for temporary credentials. The the section called \u201cDefault credentials\nprovider chain\u201d section describes the full search process.\nThe final step in the default provider chain is available only when your application runs on an\nAmazon EC2 instance. In this step, the SDK uses an InstanceProfileCredentialsProvider to\nread the IAM role defined in the EC2 instance profile. The SDK then acquires temporary credentials\nfor that IAM role.\nAlthough these credentials are temporary and would eventually expire, an\nInstanceProfileCredentialsProvider periodically refreshes them for you so that they\ncontinue to allow access to AWS.\nAcquire IAM role credentials programmatically\nAs an alternative to the default credentials provider chain that eventually uses an\nInstanceProfileCredentialsProvider on EC2, you can configure a service client explicitly\nwith an InstanceProfileCredentialsProvider. This approach is shown in the following\nsnippet.\nS3Client s3 = S3Client.builder()\n.credentialsProvider(InstanceProfileCredentialsProvider.create())\n.build();\nSecurely acquire IAM role credentials\nBy default, EC2 instances run IMDS (Instance Metadata Service) that allows the SDK's\nInstanceProfileCredentialsProvider to access information such as the IAM role that has\nbeen configured. EC2 instances run two versions of IMDS by default:\n\u2022 Instance Metadata Service Version 1 (IMDSv1) \u2013 a request/response method\n\u2022 Instance Metadata Service Version 2 (IMDSv2) \u2013 a session-oriented method\nIMDSv2 is a more secure approach than IMDSv1.\nBy default, the Java SDK first tries IMDSv2 to get the IAM role, but if that fails, it tries IMDSv1.\nHowever, since IMDSv1 is less secure, AWS recommends the use of IMDSv2 only and to disable the\nSDK from trying IMDSv1.\nTo use the more secure approach, disable the SDK from using IMDSv1 by providing one of the\nfollowing settings with a value of true.\nRead IAM role credentials on Amazon EC2 60\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Environment variable: AWS_EC2_METADATA_V1_DISABLED\n\u2022 JVM system property: aws.disableEc2MetadataV1\n\u2022 Shared config file setting: ec2_metadata_v1_disabled\nWith one of these settings set to true, the SDK does not load IMDS role credentials by using\nIMDSv1 if the initial IMDSv2 call fails.\nUse AWS Regions\nAWS Regions enable service clients to access AWS services that physically resides in a specific\ngeographic area.\nExplicitly configure an AWS Region\nTo explicitly set a Region, we recommend that you use the constants defined in the Region class.\nThis is an enumeration of all publicly available regions.\nTo create a client with an enumerated Region from the class, use the client builder's region\nmethod.\nEc2Client ec2 = Ec2Client.builder()\n.region(Region.US_WEST_2)\n.build();\nIf the Region you want to use isn\u2019t one of the enumerations in the Region class, you can create a\nnew Region by using the static of method. This method allows you access to new Regions without\nupgrading the SDK.\nRegion newRegion = Region.of(\"us-east-42\");\nEc2Client ec2 = Ec2Client.builder()\n.region(newRegion)\n.build();\nNote\nAfter you build a client with the builder, it\u2019s immutable and the AWS Region cannot be\nchanged. If you need to work with multiple AWS Regions for the same service, you should\ncreate multiple clients\u2014one per Region.\nUse AWS Regions 61\nAWS SDK for Java 2.x Developer Guide for version 2.x\nLet the SDK automatically determine the Region from the environment\nWhen your code runs on Amazon EC2 or AWS Lambda, you might want to configure clients\nto use the same AWS Region that your code is running on. This decouples your code from the\nenvironment it\u2019s running in and makes it easier to deploy your application to multiple AWS Regions\nfor lower latency or redundancy.\nTo use the default credential/region provider chain to determine the Region from the environment,\nuse the client builder\u2019s create method.\nEc2Client ec2 = Ec2Client.create();\nIf you don\u2019t explicitly set an AWS Region by using the region method, the SDK consults the\ndefault region provider chain to determine the Region to use.", "mimetype": "text/plain", "start_char_idx": 155587, "end_char_idx": 160249, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6af49c03-fe53-4a07-8dc1-0eeca6a3b8a1": {"__data__": {"id_": "6af49c03-fe53-4a07-8dc1-0eeca6a3b8a1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d610d334-8512-44a1-b56f-2cd0e9812770", "node_type": "1", "metadata": {}, "hash": "8367900273431f91de700c9ed217b7bbee9420e95aeff09949715328dbb2a98a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bbd5d7b3-370d-43a1-a4c8-d1a989086c54", "node_type": "1", "metadata": {}, "hash": "072a329a050ca07e649abe770ca9da91f534b7e232701d559c75285932f59030", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If you need to work with multiple AWS Regions for the same service, you should\ncreate multiple clients\u2014one per Region.\nUse AWS Regions 61\nAWS SDK for Java 2.x Developer Guide for version 2.x\nLet the SDK automatically determine the Region from the environment\nWhen your code runs on Amazon EC2 or AWS Lambda, you might want to configure clients\nto use the same AWS Region that your code is running on. This decouples your code from the\nenvironment it\u2019s running in and makes it easier to deploy your application to multiple AWS Regions\nfor lower latency or redundancy.\nTo use the default credential/region provider chain to determine the Region from the environment,\nuse the client builder\u2019s create method.\nEc2Client ec2 = Ec2Client.create();\nIf you don\u2019t explicitly set an AWS Region by using the region method, the SDK consults the\ndefault region provider chain to determine the Region to use.\nUnderstand the default region provider chain\nThe SDK takes the following steps to look for an AWS Region :\n1. Any explicit Region set by using region on the builder itself takes precedence over anything\nelse.\n2. The AWS_REGION environment variable is checked. If it\u2019s set, that Region is used to configure the\nclient.\nNote\nThe Lambda container sets this environment variable.\n3. The SDK checks the AWS shared configuration file and shared credentials file (usually located at\n~/.aws/config and ~/.aws/credentials). If the region property is present, the SDK uses\nit.\n\u2022 If the SDK finds the region property in both files for the same profile (including the default\nprofile), the SDK uses the value in the shared credentials file.\n\u2022 The AWS_CONFIG_FILE environment variable can be used to customize the location of the\nshared config file.\n\u2022 The AWS_PROFILE environment variable or the aws.profile system property can be used\nto specify the profile that the SDK loads.\nDetermine Region from environment 62\nAWS SDK for Java 2.x Developer Guide for version 2.x\n4. The SDK attempts to use the Amazon EC2 instance metadata service (IMDS) to determine the\nRegion of the currently running Amazon EC2 instance.\n\u2022 For greater security, you should disable the SDK from attempting to use version 1 of IMDS.\nYou use the same setting to disable version 1 that are described in the the section called\n\u201cSecurely\u201d section.\n5. If the SDK still hasn\u2019t found a Region by this point, client creation fails with an exception.\nWhen developing AWS applications, a common approach is to use the shared configuration file\n(described in Credential retrieval order) to set the Region for local development, and rely on\nthe default region provider chain to determine the Region when the application runs on AWS\ninfrastructure. This greatly simplifies client creation and keeps your application portable.\nCheck for service availability in a Region\nTo see if a particular AWS service is available in a Region, use the serviceMetadata and region\nmethod on the service client.\nDynamoDbClient.serviceMetadata().regions().forEach(System.out::println);\nSee the Region class documentation for the AWS Regions you can specify, and use the endpoint\nprefix of the service to query.\nChoose a specific endpoint\nIn certain situations\u2014such as to test preview features of a service before the features graduate to\ngeneral availability\u2014you may need to specify a specific endpoint in a Region. In these situations,\nservice clients can be configured by calling the endpointOverride method.\nFor example, to configure an Amazon EC2 client to use the Europe (Ireland) Region with a specific\nendpoint, use the following code.\nEc2Client ec2 = Ec2Client.builder()\n.region(Region.EU_WEST_1)\n.endpointOverride(URI.create(\"https://ec2.eu-west-1.amazonaws.com\"))\n.build();\nSee Regions and Endpoints for the current list of regions and their corresponding endpoints for all\nAWS services.\nCheck for service availability 63\nAWS SDK for Java 2.x Developer Guide for version 2.x\nReduce SDK startup time for AWS Lambda\nOne of the goals of the AWS SDK for Java 2.x is to reduce the startup latency for AWS Lambda\nfunctions. The SDK contains changes that reduce startup time, which are discussed at the end of\nthis topic.\nFirst, this topic focuses on changes that you can make to reduce cold start times. These include\nmaking changes in your code structure and in the configuration of service clients.\nUse an AWS CRT-based HTTP client\nFor working with AWS Lambda, we recommend the AwsCrtHttpClient for synchronous scenarios\nand the AwsCrtAsyncHttpClient for asynchronous scenarios.\nThe the section called \u201cConfigure AWS CRT-based HTTP clients\u201d topic in this guide describes the\nbenefits of using the HTTP clients, how to add the dependency, and how configure their use by\nservice clients.", "mimetype": "text/plain", "start_char_idx": 159356, "end_char_idx": 164071, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bbd5d7b3-370d-43a1-a4c8-d1a989086c54": {"__data__": {"id_": "bbd5d7b3-370d-43a1-a4c8-d1a989086c54", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6af49c03-fe53-4a07-8dc1-0eeca6a3b8a1", "node_type": "1", "metadata": {}, "hash": "e516d274d12718cb263dce63de5163dae8649c8f28e606b85fa2b4564215c6d0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f29a4ce4-8fcc-450a-90a8-2d3f2749f4fe", "node_type": "1", "metadata": {}, "hash": "96ebf95436ff78860ebf5a82231e03444e44fb356910c43efac92190944316c5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Check for service availability 63\nAWS SDK for Java 2.x Developer Guide for version 2.x\nReduce SDK startup time for AWS Lambda\nOne of the goals of the AWS SDK for Java 2.x is to reduce the startup latency for AWS Lambda\nfunctions. The SDK contains changes that reduce startup time, which are discussed at the end of\nthis topic.\nFirst, this topic focuses on changes that you can make to reduce cold start times. These include\nmaking changes in your code structure and in the configuration of service clients.\nUse an AWS CRT-based HTTP client\nFor working with AWS Lambda, we recommend the AwsCrtHttpClient for synchronous scenarios\nand the AwsCrtAsyncHttpClient for asynchronous scenarios.\nThe the section called \u201cConfigure AWS CRT-based HTTP clients\u201d topic in this guide describes the\nbenefits of using the HTTP clients, how to add the dependency, and how configure their use by\nservice clients.\nRemove unused HTTP client dependencies\nAlong with the explicit use of an AWS CRT-based client, you can remove other HTTP clients that\nthe SDK brings in by default. Lambda startup time is reduced when fewer libraries need to be\nloaded, so you should remove any unused artifacts that the JVM needs to load.\nThe following snippet of a Maven pom.xml file shows the exclusion of the Apache-based HTTP\nclient and the Netty-based HTTP client. (These clients aren't needed when you use an AWS CRT-\nbased client.) This example excludes the HTTP client artifacts from the S3 client dependency and\nadds the aws-crt-client artifact to allow access to the AWS CRT-based HTTP clients.\n\n\n2.27.21\n\n\n\n\nsoftware.amazon.awssdk\nbom\n${aws.java.sdk.version}\npom\nReduce SDK startup time for AWS Lambda 64\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\naws-crt-client\n\n\nsoftware.amazon.awssdk\ns3\n\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nsoftware.amazon.awssdk\napache-client\n\n\n\n\n\nNote\nAdd the element to all service client dependencies in your pom.xml file.\nConfigure service clients to shortcut lookups\nSpecify a region\nWhen you create a service client, call the region method on the service client builder. This\nshortcuts the SDK's default Region lookup process that checks several places for the AWS\nRegion information.\nTo keep the Lambda code independent of the region, use the following code inside the\nregion method. This code accesses the AWS_REGION environment variable set by the Lambda\ncontainer.\nConfigure service clients to shortcut lookups 65\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRegion.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))\nUse the EnvironmentVariableCredentialProvider\nMuch like the default lookup behavior for the Region information, the SDK looks in several\nplaces for credentials. By specifying the EnvironmentVariableCredentialProvider when\nyou build a service client, you save time in the SDK's lookup process for credentials.\nNote\nUsing this credentials provider enables the code to be used in Lambda functions, but\nmight not work on Amazon EC2 or other systems.\nIf you intend to use Lambda SnapStart for Java at some point, you should rely\non the default credentials provider chain to lookup credentials. If you specify the\nEnvironmentVariableCredentialsProvider, the initial credentials lookup\nworks, but when SnapStart is activated, the Java runtime sets container credentials\nenvironment variables. On activation, the environment variables used by the\nEnvironmentVariableCredentialsProvider\u2014access key environment variables\u2014\nare not available to the Java SDK.\nThe following code snippet shows an S3 service client appropriately configured for use in a Lambda\nenvironment.\nS3Client s3Client = S3Client.builder()\n.region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable())))\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.httpClient(AwsCrtHttpClient.builder().build())\n.build();\nInitialize the SDK client outside of the Lambda function handler\nWe recommend initializing an SDK client outside of the Lambda handler method. This way, if the\nexecution context is reused, the initialization of the service client can be skipped.", "mimetype": "text/plain", "start_char_idx": 163178, "end_char_idx": 167949, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f29a4ce4-8fcc-450a-90a8-2d3f2749f4fe": {"__data__": {"id_": "f29a4ce4-8fcc-450a-90a8-2d3f2749f4fe", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bbd5d7b3-370d-43a1-a4c8-d1a989086c54", "node_type": "1", "metadata": {}, "hash": "072a329a050ca07e649abe770ca9da91f534b7e232701d559c75285932f59030", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1953ffbc-0101-4858-b2e1-8a814f4db175", "node_type": "1", "metadata": {}, "hash": "6c441ba51d28a6c898bb626efbeacba5116881f7780bfd91f436211969d1ad26", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If you specify the\nEnvironmentVariableCredentialsProvider, the initial credentials lookup\nworks, but when SnapStart is activated, the Java runtime sets container credentials\nenvironment variables. On activation, the environment variables used by the\nEnvironmentVariableCredentialsProvider\u2014access key environment variables\u2014\nare not available to the Java SDK.\nThe following code snippet shows an S3 service client appropriately configured for use in a Lambda\nenvironment.\nS3Client s3Client = S3Client.builder()\n.region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable())))\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.httpClient(AwsCrtHttpClient.builder().build())\n.build();\nInitialize the SDK client outside of the Lambda function handler\nWe recommend initializing an SDK client outside of the Lambda handler method. This way, if the\nexecution context is reused, the initialization of the service client can be skipped. By reusing the\nclient instance and its connections, subsequent invocations of the handler method occur more\nquickly.\nInitialize the SDK client outside of the Lambda function handler 66\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn the following example, the S3Client instance is initialized in the constructor using a static\nfactory method. If the container that is managed by the Lambda environment is reused, the\ninitialized S3Client instance is reused.\npublic class App implements RequestHandler {\nprivate final S3Client s3Client;\npublic App() {\ns3Client = DependencyFactory.s3Client();\n}\n@Override\npublic Object handle Request(final Object input, final Context context) {\nListBucketResponse response = s3Client.listBuckets();\n// Process the response.\n}\n}\nMinimize dependency injection\nDependency injection (DI) frameworks might take additional time to complete the setup process.\nThey might also require additional dependencies, which take time to load.\nIf a DI framework is needed, we recommend using lightweight DI frameworks such as Dagger.\nUse a Maven Archetype targeting AWS Lambda\nThe AWS Java SDK team has developed a Maven Archetype template to bootstrap a Lambda\nproject with minimal startup time. You can build out a Maven project from the archetype and know\nthat the dependencies are configured suitably for the Lambda environment.\nTo learn more about the archetype and work through an example deployment, see this blog post.\nConsider Lambda SnapStart for Java\nIf your runtime requirements are compatible, AWS offers Lambda SnapStart for Java. Lambda\nSnapStart is an infrastructure-based solution that improves startup performance for Java\nfunctions. When you publish a new version of a function, Lambda SnapStart initializes it and takes\nan immutable, encrypted snapshot of the memory and disk state. SnapStart then caches the\nsnapshot for reuse.\nMinimize dependency injection 67\nAWS SDK for Java 2.x Developer Guide for version 2.x\nVersion 2.x changes that affect startup time\nIn addition to changes that you make to your code, version 2.x of the SDK for Java includes three\nprimary changes that reduce startup time:\n\u2022 Use of jackson-jr, which is a serialization library that improves initialization time\n\u2022 Use of the java.time libraries for date and time objects, which is part of the JDK\n\u2022 Use of Slf4j for a logging facade\nAdditional resources\nThe AWS Lambda Developer Guide contains a section on best practices for developing Lambda\nfunctions that is not Java specific.\nFor an example of building a cloud-native application in Java that uses AWS Lambda, see this\nworkshop content. The workshop discussion performance optimization and other best practices.\nYou can consider using static images that are compiled ahead of time to reduce startup latency. For\nexample, you can use the SDK for Java 2.x and Maven to build a GraalVM native image.\nHTTP clients\nYou can change the HTTP client to use for your service client as well as change the default\nconfiguration for HTTP clients with the AWS SDK for Java 2.x. This section discusses HTTP clients\nand settings for the SDK.\nHTTP clients available in the SDK for Java\nSynchronous clients\nSynchronous HTTP clients in the SDK for Java implement the SdkHttpClient interface. A\nsynchronous service client, such as the S3Client or the DynamoDbClient, requires the use of a\nsynchronous HTTP client. The AWS SDK for Java offers three synchronous HTTP clients.\nApacheHttpClient (default)\nApacheHttpClient is the default HTTP client for synchronous service clients. For information\nabout configuring the ApacheHttpClient, see Configure the Apache-based HTTP client.\nVersion 2.x changes that affect startup time 68\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAwsCrtHttpClient\nAwsCrtHttpClient provides high throughput and non-blocking IO. It is built on the\nAWS Common Runtime (CRT) Http Client. For information about configuring the\nAwsCrtHttpClient and using it with service clients, see the section called \u201cConfigure AWS\nCRT-based HTTP clients\u201d.", "mimetype": "text/plain", "start_char_idx": 166982, "end_char_idx": 171989, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1953ffbc-0101-4858-b2e1-8a814f4db175": {"__data__": {"id_": "1953ffbc-0101-4858-b2e1-8a814f4db175", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f29a4ce4-8fcc-450a-90a8-2d3f2749f4fe", "node_type": "1", "metadata": {}, "hash": "96ebf95436ff78860ebf5a82231e03444e44fb356910c43efac92190944316c5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e22cc0da-78fd-4a1f-a0ab-fa248ecd23b8", "node_type": "1", "metadata": {}, "hash": "52335ba03246cf10c2b0848d9f5a3ad175dd4a21ddf229bed3814effa64942e5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "HTTP clients available in the SDK for Java\nSynchronous clients\nSynchronous HTTP clients in the SDK for Java implement the SdkHttpClient interface. A\nsynchronous service client, such as the S3Client or the DynamoDbClient, requires the use of a\nsynchronous HTTP client. The AWS SDK for Java offers three synchronous HTTP clients.\nApacheHttpClient (default)\nApacheHttpClient is the default HTTP client for synchronous service clients. For information\nabout configuring the ApacheHttpClient, see Configure the Apache-based HTTP client.\nVersion 2.x changes that affect startup time 68\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAwsCrtHttpClient\nAwsCrtHttpClient provides high throughput and non-blocking IO. It is built on the\nAWS Common Runtime (CRT) Http Client. For information about configuring the\nAwsCrtHttpClient and using it with service clients, see the section called \u201cConfigure AWS\nCRT-based HTTP clients\u201d.\nUrlConnectionHttpClient\nTo minimize the number of jars and third-party libraries you application uses, you can use the\nUrlConnectionHttpClient. For information about configuring the UrlConnectionHttpClient,\nsee Configure the URLConnection-based HTTP client.\nAsynchronous clients\nAsynchronous HTTP clients in the SDK for Java implement the SdkAsyncHttpClient interface. An\nasynchronous service client, such as the S3AsyncClient or the DynamoDbAsyncClient, requires\nthe use of an asynchronous HTTP client. The AWS SDK for Java offers two asynchronous HTTP\nclients.\nNettyNioAsyncHttpClient (default)\nNettyNioAsyncHttpClient is the default HTTP client used by asynchronous clients. For\ninformation about configuring the NettyNioAsyncHttpClient, see the section called\n\u201cConfigure the Netty-based HTTP client\u201d.\nAwsCrtAsyncHttpClient\nThe AwsCrtAsyncHttpClient is based on the AWS Common Runtime (CRT) HTTP Client.\nFor information about configuring the AwsCrtAsyncHttpClient, see the section called\n\u201cConfigure AWS CRT-based HTTP clients\u201d.\nHTTP client recommendations\nSeveral factors come into play when you choose an HTTP client implementation. Use the following\ninformation to help you decide.\nRecommendation flowchart\nThe following flowchart provides general guidance to help you determine which HTTP client to\nuse.\nClient recommendations 69\nAWS SDK for Java 2.x Developer Guide for version 2.x\nClient recommendations 70\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHTTP client comparison\nThe following table provides detailed information for each HTTP client.\nHTTP client Sync or async When to use Limitation/\ndrawback\nApache-based Sync Use it if you prefer low latency over Slower startup\nHTTP client high throughput time compared\nto other HTTP\n(default sync\nclients\nHTTP client)\nURLConnection- Sync Use it if you have a hard requireme Does not\nbased HTTP nt for limiting third-party support the\nclient dependencies HTTP PATCH\nmethod,\nrequired by\nsome APIS\nlike Amazon\nAPIGatewa\ny Update\noperations\nAWS CRT-based Sync \u2022 Use it if your application is running The following\nsync HTTP in AWS Lambda Java system\n1\nclient properties are\n\u2022 Use it if you prefer high throughpu\nnot supported:\nt over low latency\n\u2022 javax.net\n\u2022 Use it if you prefer sync SDK clients\n.ssl.keyStore\n\u2022 javax.net\n.ssl.keyS\ntorePassword\n\u2022 javax.net\n.ssl.trustStore\n\u2022 javax.net\n.ssl.trus\nClient recommendations 71\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHTTP client Sync or async When to use Limitation/\ndrawback\ntStorePas\nsword\nNetty-based Async \u2022 Use it if your application invokes Slower startup\nHTTP client APIs that require HTTP/2 support time compared\nsuch as Kinesis API Subscribe to other HTTP\n(default async\nToShard clients\nHTTP client)\nClient recommendations 72\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHTTP client Sync or async When to use Limitation/\ndrawback\nAWS CRT-based Async \u2022 Use it if your application is running \u2022 Does not\nasync HTTP in AWS Lambda support service\n1\nclient clients that\n\u2022 Use it if you prefer high throughpu\nrequire HTTP/2\nt over low latency\nsupport such\n\u2022 Use it if you prefer async SDK\nas KinesisAs\nclients\nynClient\nand Transcrib\neStreamin\ngAsyncCli\nent\nThe following\nJava system\nproperties are\nnot supported:\n\u2022 javax.net\n.ssl.keyStore\n\u2022 javax.net\n.ssl.keyS\ntorePassword\n\u2022 javax.net\n.ssl.trustStore\n\u2022 javax.net\n.ssl.trus\ntStorePas\nsword\n1\nBecause of their added benefits, we recommend that you use the AWS CRT-based HTTP clients if\npossible.", "mimetype": "text/plain", "start_char_idx": 171067, "end_char_idx": 175465, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e22cc0da-78fd-4a1f-a0ab-fa248ecd23b8": {"__data__": {"id_": "e22cc0da-78fd-4a1f-a0ab-fa248ecd23b8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1953ffbc-0101-4858-b2e1-8a814f4db175", "node_type": "1", "metadata": {}, "hash": "6c441ba51d28a6c898bb626efbeacba5116881f7780bfd91f436211969d1ad26", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "efe826e9-93f4-4f80-a413-bb872c5518c9", "node_type": "1", "metadata": {}, "hash": "9e7f59a86ab758abaf331d55936a8e28c2a7986600a2d73715b2845144f59597", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Client recommendations 73\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSmart configuration defaults\nThe AWS SDK for Java 2.x (version 2.17.102 or later) offers a smart configuration defaults feature.\nThis feature optimizes two HTTP client properties along with other properties that don't affect the\nHTTP client.\nThe smart configuration defaults set sensible values for the connectTimeoutInMillis and\ntlsNegotiationTimeoutInMillis properties based on a defaults mode value that you provide.\nYou choose the defaults mode value based on your application's characteristics.\nFor more information about smart configuration defaults and how to choose the defaults mode\nvalue that is best suited for your applications, see the AWS SDKs and Tools Reference Guide.\nFollowing are four ways to set the defaults mode for your application.\nService client\nUse the service client builder to configure the defaults mode directly on the service client. The\nfollowing example sets the defaults mode to auto for the DynamoDbClient.\nDynamoDbClient ddbClient = DynamoDbClient.builder()\n.defaultsMode(DefaultsMode.AUTO)\n.build();\nSystem property\nYou can use the aws.defaultsMode system property to specify the defaults mode. If you set\nthe system property in Java, you need to set the property before initializing any service client.\nThe following example shows you how to set the defaults mode to auto using a system\nproperty set in Java.\nSystem.setProperty(\"aws.defaultsMode\", \"auto\");\nThe following example demonstrates how you set the defaults mode to auto using a -D option\nof the java command.\njava -Daws.defaultsMode=auto\nSmart defaults 74\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnvironment variable\nSet a value for environment variable AWS_DEFAULTS_MODE to select the defaults mode for your\napplication.\nThe following information shows the command to run to set the value for the defaults mode to\nauto using an environment variable.\nOperating system Command to set environment variables\nLinux, macOS, or Unix export AWS_DEFAULTS_MODE=auto\nWindows set AWS_DEFAULTS_MODE=auto\nAWS config file\nYou can add a defaults_mode configuration property to the shared AWS config file as the\nfollowing example shows.\n[default]\ndefaults_mode = auto\nIf you set the defaults mode globally with the system property, environment variable, or AWS\nconfig file, you can override the settings when you build an HTTP client.\nWhen you build an HTTP client with the httpClientBuilder() method, settings apply only to\nthe instance that you are building. An example of this is shown here. The Netty-based HTTP client\nin this example overrides any default mode values set globally for connectTimeoutInMillis\nand tlsNegotiationTimeoutInMillis.\nConfigure the Apache-based HTTP client\nSynchronous service clients in the AWS SDK for Java 2.x use an Apache-based HTTP client,\nApacheHttpClient by default. The SDK's ApacheHttpClient is based on the Apache HttpClient.\nThe SDK also offers the UrlConnectionHttpClient, which loads more quickly, but has fewer features.\nFor information about configuring the UrlConnectionHttpClient, see the section called\n\u201cConfigure the URLConnection-based HTTP client\u201d.\nConfigure the Apache-based HTTP client 75\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo see the full set of configuration options available to you for the ApacheHttpClient, see\nApacheHttpClient.Builder and ProxyConfiguration.Builder.\nAccess the ApacheHttpClient\nIn most situations, you use the ApacheHttpClient without any explicit configuration. You declare\nyour service clients and the SDK will configure the ApacheHttpClient with standard values for\nyou.\nIf you want to explicitly configure the ApacheHttpClient or use it with multiple service clients,\nyou need to make it available for configuration.\nNo configuration needed\nWhen you declare a dependency on a service client in Maven, the SDK adds a runtime dependency\non the apache-client artifact. This makes the ApacheHttpClient class available to your code\nat runtime, but not at compile time. If you are not configuring the Apache-based HTTP client, you\ndo not need to specify a dependency for it.\nIn the following XML snippet of a Maven pom.xml file, the dependency declared with\ns3 automatically brings in the Apache-based HTTP client. You\ndon't need to declare a dependency specifically for it.", "mimetype": "text/plain", "start_char_idx": 175466, "end_char_idx": 179832, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "efe826e9-93f4-4f80-a413-bb872c5518c9": {"__data__": {"id_": "efe826e9-93f4-4f80-a413-bb872c5518c9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e22cc0da-78fd-4a1f-a0ab-fa248ecd23b8", "node_type": "1", "metadata": {}, "hash": "52335ba03246cf10c2b0848d9f5a3ad175dd4a21ddf229bed3814effa64942e5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "26b43b04-ad51-4609-aaa9-4a6dfd9b1bd2", "node_type": "1", "metadata": {}, "hash": "56f12f6989fff88148d5586ae951a9134b11013ae27d972ab31c0379ed05c663", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Access the ApacheHttpClient\nIn most situations, you use the ApacheHttpClient without any explicit configuration. You declare\nyour service clients and the SDK will configure the ApacheHttpClient with standard values for\nyou.\nIf you want to explicitly configure the ApacheHttpClient or use it with multiple service clients,\nyou need to make it available for configuration.\nNo configuration needed\nWhen you declare a dependency on a service client in Maven, the SDK adds a runtime dependency\non the apache-client artifact. This makes the ApacheHttpClient class available to your code\nat runtime, but not at compile time. If you are not configuring the Apache-based HTTP client, you\ndo not need to specify a dependency for it.\nIn the following XML snippet of a Maven pom.xml file, the dependency declared with\ns3 automatically brings in the Apache-based HTTP client. You\ndon't need to declare a dependency specifically for it.\n\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\n\nsoftware.amazon.awssdk\ns3\n\n\nConfigure the Apache-based HTTP client 76\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWith these dependencies, you cannot make any explicit HTTP configuration changes, because the\nApacheHttpClient library is only on the runtime classpath.\nConfiguration needed\nTo configure the ApacheHttpClient, you need to add a dependency on the apache-client\nlibrary at compile time.\nRefer to the following example of a Maven pom.xml file to configure the ApacheHttpClient.\n\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ns3\n\n\n\nsoftware.amazon.awssdk\napache-client\n\n\nUse and configure the ApacheHttpClient\nYou can configure an instance of ApacheHttpClient along with building a service client, or you\ncan configure a single instance to share across multiple service clients.\nWith either approach, you use the ApacheHttpClient.Builder to configure the properties for\nthe Apache-based HTTP client.\nConfigure the Apache-based HTTP client 77\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBest practice: dedicate an ApacheHttpClient instance to a service client\nIf you need to configure an instance of the ApacheHttpClient, we recommend that you build\nthe dedicated ApacheHttpClient instance. You can do so by using the httpClientBuilder\nmethod of the service client's builder. This way, the lifecycle of the HTTP client is managed by the\nSDK, which helps avoid potential memory leaks if the ApacheHttpClient instance is not closed\ndown when it's no longer needed.\nThe following example creates an S3Client and configures the embedded instance of\nApacheHttpClient with maxConnections and connectionTimeout values. The HTTP\ninstance is created using the httpClientBuilder method of S3Client.Builder.\nImports\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Duration;\nCode\nS3Client s3Client = S3Client // Singleton: Use the s3Client for all requests.\n.builder()\n.httpClientBuilder(ApacheHttpClient.builder()\n.maxConnections(100)\n.connectionTimeout(Duration.ofSeconds(5))\n).build();\n// Perform work with the s3Client.\ns3Client.close(); // Requests completed: Close all service clients.\nAlternative approach: share an ApacheHttpClient instance\nTo help keep resource and memory usage lower for your application, you can configure an\nApacheHttpClient and share it across multiple service clients. The HTTP connection pool will be\nshared, which lowers resource usage.\nConfigure the Apache-based HTTP client 78\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nWhen an ApacheHttpClient instance is shared, you must close it when it is ready to be\ndisposed. The SDK will not close the instance when the service client is closed.\nThe following example configures an Apache-based HTTP client that is used by two service clients.\nThe configured ApacheHttpClient instance is passed to the httpClient method of each\nbuilder.", "mimetype": "text/plain", "start_char_idx": 178885, "end_char_idx": 183703, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "26b43b04-ad51-4609-aaa9-4a6dfd9b1bd2": {"__data__": {"id_": "26b43b04-ad51-4609-aaa9-4a6dfd9b1bd2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "efe826e9-93f4-4f80-a413-bb872c5518c9", "node_type": "1", "metadata": {}, "hash": "9e7f59a86ab758abaf331d55936a8e28c2a7986600a2d73715b2845144f59597", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "027bfb21-0124-4507-bf52-95e0ffbb9065", "node_type": "1", "metadata": {}, "hash": "f6b93bfc8f2c068ac383e2344b40a436168ee118fb1c594830de3f78056aa3e1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".builder()\n.httpClientBuilder(ApacheHttpClient.builder()\n.maxConnections(100)\n.connectionTimeout(Duration.ofSeconds(5))\n).build();\n// Perform work with the s3Client.\ns3Client.close(); // Requests completed: Close all service clients.\nAlternative approach: share an ApacheHttpClient instance\nTo help keep resource and memory usage lower for your application, you can configure an\nApacheHttpClient and share it across multiple service clients. The HTTP connection pool will be\nshared, which lowers resource usage.\nConfigure the Apache-based HTTP client 78\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nWhen an ApacheHttpClient instance is shared, you must close it when it is ready to be\ndisposed. The SDK will not close the instance when the service client is closed.\nThe following example configures an Apache-based HTTP client that is used by two service clients.\nThe configured ApacheHttpClient instance is passed to the httpClient method of each\nbuilder. When the service clients and the HTTP client are no longer needed, the code explicitly\ncloses them. The code closes the HTTP client last.\nImports\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nCode\nSdkHttpClient apacheHttpClient = ApacheHttpClient.builder()\n.maxConnections(100).build();\n// Singletons: Use the s3Client and dynamoDbClient for all requests.\nS3Client s3Client =\nS3Client.builder()\n.httpClient(apacheHttpClient).build();\nDynamoDbClient dynamoDbClient =\nDynamoDbClient.builder()\n.httpClient(apacheHttpClient).build();\n// Perform work with the s3Client and dynamoDbClient.\n// Requests completed: Close all service clients.\ns3Client.close();\ndynamoDbClient.close();\napacheHttpClient.close(); // Explicitly close apacheHttpClient.\nConfigure the Apache-based HTTP client 79\nAWS SDK for Java 2.x Developer Guide for version 2.x\nProxy configuration example\nThe following code snippet uses the proxy configuration builder for the Apache HTTP client.\nSdkHttpClient apacheHttpClient = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.endpoint(URI.create(\"http://example.com:1234\"))\n.username(\"username\")\n.password(\"password\")\n.addNonProxyHost(\"localhost\")\n.addNonProxyHost(\"host.example.com\")\n.build())\n.build();\nThe equivalent Java system properties for the proxy configuration are shown in the following\ncommand line snippet.\n$ java -Dhttp.proxyHost=example.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=username \\\n-Dhttp.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ...\nApp\nThe equivalent setup that uses environment variables is:\n// Set the following environment variables.\n// $ export HTTP_PROXY=\"http://username:password@example.com:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkHttpClient apacheHttpClient = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\n// Run the application.\n// $ java -cp ... App\nNote\nThe Apache HTTP client does not currently support HTTPS proxy system properties or the\nHTTPS_PROXY environment variable.\nConfigure the Apache-based HTTP client 80\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConfigure the URLConnection-based HTTP client\nThe AWS SDK for Java 2.x offers a lighter-weight UrlConnectionHttpClient HTTP client in\ncomparison to the default ApacheHttpClient. The UrlConnectionHttpClient is based on\nJava's URLConnection.\nThe UrlConnectionHttpClient loads more quickly than the Apache-based HTTP client, but has\nfewer features. Because it loads more quickly, it is a good solution for Java AWS Lambda functions.\nThe UrlConnectionHttpClient has several configurable options that you can access.\nNote\nThe UrlConnectionHttpClient does not support the HTTP PATCH method.\nA handful of AWS API operations require PATCH requests. Those operation names usually\nstart with Update*. The following are several examples.\n\u2022 Several Update* operations in the AWS Security Hub API and also the\nBatchUpdateFindings operation\n\u2022 All Amazon API Gateway API Update* operations\n\u2022 Several Update* operations in the Amazon WorkDocs API\nIf you might use the UrlConnectionHttpClient, first refer to the API Reference for\nthe AWS service that you're using. Check to see if the operations you need use the PATCH\noperation.\nAccess the UrlConnectionHttpClient\nTo configure and use the UrlConnectionHttpClient, you declare a dependency on the url-\nconnection-client Maven artifact in your pom.xml file.\nUnlike the ApacheHttpClient, the UrlConnectionHttpClient is not automatically added to\nyour project, so use must specifically declare it.\nThe following example of a pom.xml file shows the dependencies required to use and configure\nthe HTTP client.", "mimetype": "text/plain", "start_char_idx": 182734, "end_char_idx": 187685, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "027bfb21-0124-4507-bf52-95e0ffbb9065": {"__data__": {"id_": "027bfb21-0124-4507-bf52-95e0ffbb9065", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "26b43b04-ad51-4609-aaa9-4a6dfd9b1bd2", "node_type": "1", "metadata": {}, "hash": "56f12f6989fff88148d5586ae951a9134b11013ae27d972ab31c0379ed05c663", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c52facd1-5cd9-48af-a4dc-d57100d9b40d", "node_type": "1", "metadata": {}, "hash": "9eb0ae60ede95d2d36b8f458a9bc9574517924cc321b791843e142b058c4f976", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "A handful of AWS API operations require PATCH requests. Those operation names usually\nstart with Update*. The following are several examples.\n\u2022 Several Update* operations in the AWS Security Hub API and also the\nBatchUpdateFindings operation\n\u2022 All Amazon API Gateway API Update* operations\n\u2022 Several Update* operations in the Amazon WorkDocs API\nIf you might use the UrlConnectionHttpClient, first refer to the API Reference for\nthe AWS service that you're using. Check to see if the operations you need use the PATCH\noperation.\nAccess the UrlConnectionHttpClient\nTo configure and use the UrlConnectionHttpClient, you declare a dependency on the url-\nconnection-client Maven artifact in your pom.xml file.\nUnlike the ApacheHttpClient, the UrlConnectionHttpClient is not automatically added to\nyour project, so use must specifically declare it.\nThe following example of a pom.xml file shows the dependencies required to use and configure\nthe HTTP client.\n\nConfigure the URLConnection-based HTTP client 81\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\n\nsoftware.amazon.awssdk\nurl-connection-client\n\n\nUse and configure the UrlConnectionHttpClient\nYou can configure an instance of UrlConnectionHttpClient along with building a service client,\nor you can configure a single instance to share across multiple service clients.\nWith either approach, you use the UrlConnectionHttpClient.Builder to configure the properties for\nthe URLConnection-based HTTP client.\nBest practice: dedicate an UrlConnectionHttpClient instance to a service client\nIf you need to configure an instance of the UrlConnectionHttpClient, we recommend\nthat you build the dedicated UrlConnectionHttpClient instance. You can do so by using\nthe httpClientBuilder method of the service client's builder. This way, the lifecycle of\nthe HTTP client is managed by the SDK, which helps avoid potential memory leaks if the\nUrlConnectionHttpClient instance is not closed down when it's no longer needed.\nThe following example creates an S3Client and configures the embedded instance\nof UrlConnectionHttpClient with socketTimeout and proxyConfiguration\nvalues. The proxyConfiguration method takes a Java lambda expression of type\nConsumer.\nImports\nConfigure the URLConnection-based HTTP client 82\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;\nimport java.net.URI;\nimport java.time.Duration;\nCode\n// Singleton: Use the s3Client for all requests.\nS3Client s3Client =\nS3Client.builder()\n.httpClientBuilder(UrlConnectionHttpClient.builder()\n.socketTimeout(Duration.ofMinutes(5))\n.proxyConfiguration(proxy -> proxy.endpoint(URI.create(\"http://\nproxy.mydomain.net:8888\"))))\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\n// Perform work with the s3Client.\ns3Client.close(); // Requests completed: Close the s3client.\nAlternative approach: share an UrlConnectionHttpClient instance\nTo help keep resource and memory usage lower for your application, you can configure an\nUrlConnectionHttpClient and share it across multiple service clients. The HTTP connection\npool will be shared, which lowers resource usage.\nNote\nWhen an UrlConnectionHttpClient instance is shared, you must close it when it is\nready to be disposed. The SDK will not close the instance when the service client is closed.\nThe following example configures an URLConnection-based HTTP client that is used by two service\nclients. The configured UrlConnectionHttpClient instance is passed to the httpClient\nmethod of each builder. When the service clients and the HTTP client are no longer needed, the\ncode explicitly closes them. The code closes the HTTP client last.\nImports\nimport software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nConfigure the URLConnection-based HTTP client 83\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.urlconnection.ProxyConfiguration;\nimport software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.net.URI;\nimport java.time.Duration;\nCode\nSdkHttpClient urlHttpClient = UrlConnectionHttpClient.create();\n// Singletons: Use the s3Client and dynamoDbClient for all requests.", "mimetype": "text/plain", "start_char_idx": 186732, "end_char_idx": 191657, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c52facd1-5cd9-48af-a4dc-d57100d9b40d": {"__data__": {"id_": "c52facd1-5cd9-48af-a4dc-d57100d9b40d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "027bfb21-0124-4507-bf52-95e0ffbb9065", "node_type": "1", "metadata": {}, "hash": "f6b93bfc8f2c068ac383e2344b40a436168ee118fb1c594830de3f78056aa3e1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "65754c3a-cb69-408e-95a3-09e7c6b835d8", "node_type": "1", "metadata": {}, "hash": "086ed06685a626913df4d92ac1feb00c72b9b20c315148014a63ffee68e342e6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "When the service clients and the HTTP client are no longer needed, the\ncode explicitly closes them. The code closes the HTTP client last.\nImports\nimport software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nConfigure the URLConnection-based HTTP client 83\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.urlconnection.ProxyConfiguration;\nimport software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.net.URI;\nimport java.time.Duration;\nCode\nSdkHttpClient urlHttpClient = UrlConnectionHttpClient.create();\n// Singletons: Use the s3Client and dynamoDbClient for all requests.\nS3Client s3Client =\nS3Client.builder()\n.httpClient(urlHttpClient)\n.defaultsMode(DefaultsMode.IN_REGION)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\nDynamoDbClient dynamoDbClient =\nDynamoDbClient.builder()\n.httpClient(urlHttpClient)\n.defaultsMode(DefaultsMode.IN_REGION)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\n// Perform work with the s3Client and dynamoDbClient.\n// Requests completed: Close all service clients.\ns3Client.close();\ndynamoDbClient.close();\nurlHttpClient.close();\nUse URLConnectionHttpClient and ApacheHttpClient together\nWhen you use the UrlConnectionHttpClient in your application, you must supply each service\nclient with either a URLConnectionHttpClient instance or a ApacheHttpClient instance\nusing the service client builder's httpClientBuilder method.\nAn exception occurs if your program uses multiple service clients and both of the following are\ntrue:\nConfigure the URLConnection-based HTTP client 84\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 One service client is configured to use a UrlConnectionHttpClient instance\n\u2022 Another service client uses the default ApacheHttpClient without explicitly building it with\nthe httpClient() or httpClientBuilder() methods\nThe exception will state that multiple HTTP implementations were found on the classpath.\nThe following example code snippet leads to an exception.\n// The dynamoDbClient uses the UrlConnectionHttpClient\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.httpClient(UrlConnectionHttpClient.create())\n.build();\n// The s3Client below uses the ApacheHttpClient at runtime, without specifying it.\n// An SdkClientException is thrown with the message that multiple HTTP implementations\nwere found on the classpath.\nS3Client s3Client = S3Client.create();\n// Perform work with the s3Client and dynamoDbClient.\ndynamoDbClient.close();\ns3Client.close();\nAvoid the exception by explicitly configuring the S3Client with an ApacheHttpClient.\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.httpClient(UrlConnectionHttpClient.create())\n.build();\nS3Client s3Client = S3Client.builder()\n.httpClient(ApacheHttpClient.create()) // Explicitly build the\nApacheHttpClient.\n.build();\n// Perform work with the s3Client and dynamoDbClient.\ndynamoDbClient.close();\ns3Client.close();\nConfigure the URLConnection-based HTTP client 85\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nTo explicitly create the ApacheHttpClient, you must add a dependency on the apache-\nclient artifact in your Maven project file.\nProxy configuration example\nThe following code snippet uses the proxy configuration builder for the URL connection HTTP\nclient.\nSdkHttpClient urlHttpClient = UrlConnectionHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.endpoint(URI.create(\"http://example.com:1234\"))\n.username(\"username\")\n.password(\"password\")\n.addNonProxyHost(\"localhost\")\n.addNonProxyHost(\"host.example.com\")\n.build())\n.build();\nThe equivalent Java system properties for the proxy configuration are shown in the following\ncommand line snippet.\n$ java -Dhttp.proxyHost=example.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=username \\\n-Dhttp.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ...\nApp\nThe equivalent setup that uses environment variables is:\n// Set the following environment variables.\n// $ export HTTP_PROXY=\"http://username:password@example.com:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkHttpClient apacheHttpClient = UrlConnectionHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\nConfigure the URLConnection-based HTTP client 86\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Run the application.\n// $ java -cp ... App\nNote\nThe URLConnection-based HTTP client does not currently support HTTPS proxy system\nproperties or the HTTPS_PROXY environment variable.", "mimetype": "text/plain", "start_char_idx": 190763, "end_char_idx": 195706, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "65754c3a-cb69-408e-95a3-09e7c6b835d8": {"__data__": {"id_": "65754c3a-cb69-408e-95a3-09e7c6b835d8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c52facd1-5cd9-48af-a4dc-d57100d9b40d", "node_type": "1", "metadata": {}, "hash": "9eb0ae60ede95d2d36b8f458a9bc9574517924cc321b791843e142b058c4f976", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "955060b2-7811-4f18-a16e-64eb75b3866b", "node_type": "1", "metadata": {}, "hash": "0a1b452b69c112c7b2d0b0e57716aa90ed32205e236933b5ff37a832a4f406c8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "$ java -Dhttp.proxyHost=example.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=username \\\n-Dhttp.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ...\nApp\nThe equivalent setup that uses environment variables is:\n// Set the following environment variables.\n// $ export HTTP_PROXY=\"http://username:password@example.com:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkHttpClient apacheHttpClient = UrlConnectionHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\nConfigure the URLConnection-based HTTP client 86\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Run the application.\n// $ java -cp ... App\nNote\nThe URLConnection-based HTTP client does not currently support HTTPS proxy system\nproperties or the HTTPS_PROXY environment variable.\nConfigure the Netty-based HTTP client\nThe default HTTP client for asynchronous operations in the AWS SDK for Java 2.x is the Netty-\nbased NettyNioAsyncHttpClient. The Netty-based client is based on the asynchronous event-driven\nnetwork framework of the Netty project.\nAs an alternative HTTP client, you can use the new AWS CRT-based HTTP client. This topic shows\nyou how to configure the NettyNioAsyncHttpClient.\nAccess the NettyNioAsyncHttpClient\nIn most situations, you use the NettyNioAsyncHttpClient without any explicit configuration in\nasynchronous programs. You declare your asynchronous service clients and the SDK will configure\nthe NettyNioAsyncHttpClient with standard values for you.\nIf you want to explicitly configure the NettyNioAsyncHttpClient or use it with multiple service\nclients, you need to make it available for configuration.\nNo configuration needed\nWhen you declare a dependency on a service client in Maven, the SDK adds a runtime dependency\non the netty-nio-client artifact. This makes the NettyNioAsyncHttpClient class available\nto your code at runtime, but not at compile time. If you are not configuring the Netty-based HTTP\nclient, you don't need to specify a dependency for it.\nIn the following XML snippet of a Maven pom.xml file, the dependency declared with\ndynamodb-enhanced transitively brings in the Netty-based\nHTTP client. You don't need to declare a dependency specifically for it.\n\n\nConfigure the Netty-based HTTP client 87\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ndynamodb-enhanced\n\n\nWith these dependencies, you cannot make any HTTP configuration changes, since the\nNettyNioAsyncHttpClient library is only on the runtime classpath.\nConfiguration needed\nTo configure the NettyNioAsyncHttpClient, you need to add a dependency on the netty-\nnio-client artifact at compile time.\nRefer to the following example of a Maven pom.xml file to configure the\nNettyNioAsyncHttpClient.\n\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ndynamodb-enhanced\n\nConfigure the Netty-based HTTP client 88\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nUse and configure the NettyNioAsyncHttpClient\nYou can configure an instance of NettyNioAsyncHttpClient along with building a service client,\nor you can configure a single instance to share across multiple service clients.\nWith either approach, you use the NettyNioAsyncHttpClient.Builder to configure the properties for\nthe Netty-based HTTP client instance.", "mimetype": "text/plain", "start_char_idx": 194776, "end_char_idx": 199110, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "955060b2-7811-4f18-a16e-64eb75b3866b": {"__data__": {"id_": "955060b2-7811-4f18-a16e-64eb75b3866b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "65754c3a-cb69-408e-95a3-09e7c6b835d8", "node_type": "1", "metadata": {}, "hash": "086ed06685a626913df4d92ac1feb00c72b9b20c315148014a63ffee68e342e6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "92d3eb9c-bc51-45a4-8c4d-c280c62d1094", "node_type": "1", "metadata": {}, "hash": "10ef977d4ade314adb74e38168701d9b5c08cc747b4d9dc7ce96d6c6d7aef5bd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "-->\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nUse and configure the NettyNioAsyncHttpClient\nYou can configure an instance of NettyNioAsyncHttpClient along with building a service client,\nor you can configure a single instance to share across multiple service clients.\nWith either approach, you use the NettyNioAsyncHttpClient.Builder to configure the properties for\nthe Netty-based HTTP client instance.\nBest practice: dedicate a NettyNioAsyncHttpClient instance to a service client\nIf you need to configure an instance of the NettyNioAsyncHttpClient, we recommend\nthat you build a dedicated NettyNioAsyncHttpClient instance. You can do so by using\nthe httpClientBuilder method of the service client's builder. This way, the lifecycle of\nthe HTTP client is managed by the SDK, which helps avoid potential memory leaks if the\nNettyNioAsyncHttpClient instance is not closed down when it's no longer needed.\nThe following example creates a DynamoDbAsyncClient instance that is used by a\nDynamoDbEnhancedAsyncClient instance. The DynamoDbAsyncClient instance\ncontains the NettyNioAsyncHttpClient instance with connectionTimeout and\nmaxConcurrency values. The HTTP instance is created using httpClientBuilder method of\nDynamoDbAsyncClient.Builder.\nImports\nimport software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nimport software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;\nimport java.time.Duration;\nConfigure the Netty-based HTTP client 89\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\n// DynamoDbAsyncClient is the lower-level client used by the enhanced client.\nDynamoDbAsyncClient dynamoDbAsyncClient =\nDynamoDbAsyncClient\n.builder()\n.httpClientBuilder(NettyNioAsyncHttpClient.builder()\n.connectionTimeout(Duration.ofMillis(5_000))\n.maxConcurrency(100)\n.tlsNegotiationTimeout(Duration.ofMillis(3_500)))\n.defaultsMode(DefaultsMode.IN_REGION)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\n// Singleton: Use dynamoDbAsyncClient and enhancedClient for all requests.\nDynamoDbEnhancedAsyncClient enhancedClient =\nDynamoDbEnhancedAsyncClient\n.builder()\n.dynamoDbClient(dynamoDbAsyncClient)\n.extensions(AutoGeneratedTimestampRecordExtension.create())\n.build();\n// Perform work with the dynamoDbAsyncClient and enhancedClient.\n// Requests completed: Close dynamoDbAsyncClient.\ndynamoDbAsyncClient.close();\nAlternative approach: share a NettyNioAsyncHttpClient instance\nTo help keep resource and memory usage lower for your application, you can configure a\nNettyNioAsyncHttpClient and share it across multiple service clients. The HTTP connection\npool will be shared, which lowers resource usage.\nNote\nWhen a NettyNioAsyncHttpClient instance is shared, you must close it when it is ready\nto be disposed. The SDK will not close the instance when the service client is closed.\nThe following example configures a Netty-based HTTP client that is used by two service clients.\nThe configured NettyNioAsyncHttpClient instance is passed to the httpClient method of\nConfigure the Netty-based HTTP client 90\nAWS SDK for Java 2.x Developer Guide for version 2.x\neach builder. When the service clients and the HTTP client are no longer needed, the code explicitly\ncloses them. The code closes the HTTP client last.\nImports\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nCode\n// Create a NettyNioAsyncHttpClient shared instance.\nSdkAsyncHttpClient nettyHttpClient =\nNettyNioAsyncHttpClient.builder().maxConcurrency(100).build();\n// Singletons: Use the s3AsyncClient, dbAsyncClient, and enhancedAsyncClient for all\nrequests.", "mimetype": "text/plain", "start_char_idx": 198622, "end_char_idx": 202780, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "92d3eb9c-bc51-45a4-8c4d-c280c62d1094": {"__data__": {"id_": "92d3eb9c-bc51-45a4-8c4d-c280c62d1094", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "955060b2-7811-4f18-a16e-64eb75b3866b", "node_type": "1", "metadata": {}, "hash": "0a1b452b69c112c7b2d0b0e57716aa90ed32205e236933b5ff37a832a4f406c8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "892ba326-42e2-428d-a59e-36c764161d29", "node_type": "1", "metadata": {}, "hash": "1b3b6f1e17cfa041947cbb8197d8d4140dfb41eaa30a8908e1ae4d9df0ad4aa9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The configured NettyNioAsyncHttpClient instance is passed to the httpClient method of\nConfigure the Netty-based HTTP client 90\nAWS SDK for Java 2.x Developer Guide for version 2.x\neach builder. When the service clients and the HTTP client are no longer needed, the code explicitly\ncloses them. The code closes the HTTP client last.\nImports\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nCode\n// Create a NettyNioAsyncHttpClient shared instance.\nSdkAsyncHttpClient nettyHttpClient =\nNettyNioAsyncHttpClient.builder().maxConcurrency(100).build();\n// Singletons: Use the s3AsyncClient, dbAsyncClient, and enhancedAsyncClient for all\nrequests.\nS3AsyncClient s3AsyncClient =\nS3AsyncClient.builder()\n.httpClient(nettyHttpClient)\n.build();\nDynamoDbAsyncClient dbAsyncClient =\nDynamoDbAsyncClient.builder()\n.httpClient(nettyHttpClient)\n.defaultsMode(DefaultsMode.IN_REGION)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\nDynamoDbEnhancedAsyncClient enhancedAsyncClient =\nDynamoDbEnhancedAsyncClient.builder()\n.dynamoDbClient(dbAsyncClient)\n.extensions(AutoGeneratedTimestampRecordExtension.create())\n.build();\n// Perform work with s3AsyncClient, dbAsyncClient, and enhancedAsyncClient.\n// Requests completed: Close all service clients.\ns3AsyncClient.close();\ndbAsyncClient.close()\nConfigure the Netty-based HTTP client 91\nAWS SDK for Java 2.x Developer Guide for version 2.x\nnettyHttpClient.close(); // Explicitly close nettyHttpClient.\nProxy configuration example\nThe following code snippet uses the proxy configuration builder for the Netty HTTP client.\nSdkAsyncHttpClient nettyHttpClient = NettyNioAsyncHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.host(\"myproxy\")\n.port(1234)\n.username(\"username\")\n.password(\"password\")\n.nonProxyHosts(Set.of(\"localhost\", \"host.example.com\"))\n.build())\n.build();\nThe equivalent Java system properties for the proxy configuration are shown in the following\ncommand line snippet.\n$ java -Dhttps.proxyHost=myproxy -Dhttps.proxyPort=1234 -Dhttps.proxyUser=username \\\n-Dhttps.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ...\nApp\nImportant\nTo use any of the HTTPS proxy system properties, the scheme property must be set in code\nto https. If the scheme property is not set in code, the scheme defaults to HTTP and the\nSDK looks only for http.* system properties.\nThe equivalent setup that uses environment variables is:\n// Set the following environment variables.\n// $ export HTTPS_PROXY=\"https://username:password@myproxy:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkAsyncHttpClient nettyHttpClient = NettyNioAsyncHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\nConfigure the Netty-based HTTP client 92\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\n// Run the application.\n// $ java -cp ... App\nConfigure AWS CRT-based HTTP clients\nThe AWS CRT-based HTTP clients include the synchronous AwsCrtHttpClient and asynchronous\nAwsCrtAsyncHttpClient. The AWS CRT-based HTTP clients provide the following HTTP client\nbenefits:\n\u2022 Faster SDK startup time\n\u2022 Smaller memory footprint\n\u2022 Reduced latency time\n\u2022 Connection health management\n\u2022 DNS load balancing\nAWS CRT-based components in the SDK\nThe AWS CRT-based HTTP clients, described in this topic, and the AWS CRT-based S3 client are\ndifferent components in the SDK.\nThe synchronous and asynchronous AWS CRT-based HTTP clients are implementations SDK HTTP\nclient interfaces and are used for general HTTP communication. They are alternatives to the other\nsynchronous or asynchronous HTTP clients in the SDK with additional benefits.\nThe AWS CRT-based S3 client is an implementation of the S3AsyncClient interface and is used for\nworking with the Amazon S3 service. It is an alternative to the Java-based implementation of the\nS3AsyncClient interface and offers several advantages.\nAlthough both components use libraries from the AWS Common Runtime, the AWS CRT-based\nHTTP clients do not use the aws-c-s3 library and do not support the S3 multipart upload API\nfeatures. The AWS CRT-based S3 client, by contrast, was purpose-built to support the S3 multipart\nupload API features.", "mimetype": "text/plain", "start_char_idx": 201962, "end_char_idx": 206465, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "892ba326-42e2-428d-a59e-36c764161d29": {"__data__": {"id_": "892ba326-42e2-428d-a59e-36c764161d29", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "92d3eb9c-bc51-45a4-8c4d-c280c62d1094", "node_type": "1", "metadata": {}, "hash": "10ef977d4ade314adb74e38168701d9b5c08cc747b4d9dc7ce96d6c6d7aef5bd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e370cd1d-18af-49d3-afca-dde8cc7ce724", "node_type": "1", "metadata": {}, "hash": "875e1a7e969afd49f9f9e5eecd39ee7bc5d116303129cfa5c660205a8ef24e28", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The synchronous and asynchronous AWS CRT-based HTTP clients are implementations SDK HTTP\nclient interfaces and are used for general HTTP communication. They are alternatives to the other\nsynchronous or asynchronous HTTP clients in the SDK with additional benefits.\nThe AWS CRT-based S3 client is an implementation of the S3AsyncClient interface and is used for\nworking with the Amazon S3 service. It is an alternative to the Java-based implementation of the\nS3AsyncClient interface and offers several advantages.\nAlthough both components use libraries from the AWS Common Runtime, the AWS CRT-based\nHTTP clients do not use the aws-c-s3 library and do not support the S3 multipart upload API\nfeatures. The AWS CRT-based S3 client, by contrast, was purpose-built to support the S3 multipart\nupload API features.\nConfigure AWS CRT-based HTTP clients 93\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAccess the AWS CRT-based HTTP clients\nBefore you can use the AWS CRT-based HTTP clients, add the aws-crt-client artifact with a\nminimum version of 2.22.0 to your project's dependencies.\nUse one of the following options to set up your Maven pom.xml file.\nNote\nYou might choose to use the Platform-specific jar option if you need to keep the size of\nthe runtime dependencies smaller, for example if your application runs in an AWS Lambda\nfunction.\nUber-jar option\nBy default, the aws-crt-client uses an uber-jar of AWS CRT artifacts that contains binaries\nfor several platforms, including Linux, Windows, and macOS.\n\n\n2.29.10*\n\n\n\n\nsoftware.amazon.awssdk\nbom\n${aws.sdk.version}\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\naws-crt-client\n\n\n\nConfigure AWS CRT-based HTTP clients 94\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*Replace the version shown in red with the version of the Java SDK that you want to use. Find\nthe latest on Maven Central.\nPlatform-specific jar option\nTo restrict the Java runtime to platform-specific version of the AWS CRT library, make the\nfollowing changes to the Uber-jar option.\n\u2022 Add an exclusions element to the SDK's aws-crt-client artifact. This exclusion prevents\nthe SDK from transitively using the AWS CRT uber-jar.\n\u2022 Add a dependency element for the specific AWS CRT platform version you need. See the\nSteps to determine the AWS CRT artifact version below for how you can determine the\ncorrect version.\n\n\n1\n2.29.10 \n\n\n\n\nsoftware.amazon.awssdk\nbom\n${aws.sdk.java.version}\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\naws-crt-client\n\n\nsoftware.amazon.awssdk.crt\naws-crt\n\n\n\n\nsoftware.amazon.awssdk.crt\nConfigure AWS CRT-based HTTP clients 95\nAWS SDK for Java 2.x Developer Guide for version 2.x\naws-crt\n2\n0.31.3 \n3\nlinux-x86_64 \n\n\n1\nReplace the version shown in red with the version of the Java SDK that you want to use. Find\nthe latest on Maven Central.\n2\nReplace the version of software.amazon.awssdk.crt:aws-crt that would be provided by\nthe Uber-jar option. See the following Steps to determine the AWS CRT artifact version.\n3\nReplace the classifier value with one for your platform. Refer to the AWS CRT for Java\nGitHub page for a listing of available values.\nSteps to determine the AWS CRT artifact version\nUse the following steps to determine the AWS CRT artifact version that is compatible with the\nversion of the SDK for Java that you are using.\n1. Set up your pom.xml file as shown in the Uber-jar option.", "mimetype": "text/plain", "start_char_idx": 205656, "end_char_idx": 209953, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e370cd1d-18af-49d3-afca-dde8cc7ce724": {"__data__": {"id_": "e370cd1d-18af-49d3-afca-dde8cc7ce724", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "892ba326-42e2-428d-a59e-36c764161d29", "node_type": "1", "metadata": {}, "hash": "1b3b6f1e17cfa041947cbb8197d8d4140dfb41eaa30a8908e1ae4d9df0ad4aa9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6dc21dc4-2085-468e-925d-753b0bb9ac54", "node_type": "1", "metadata": {}, "hash": "b82174b831a90af1a1ef33ef65f74743ac257307944cc2485d2c7100da6798d6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find\nthe latest on Maven Central.\n2\nReplace the version of software.amazon.awssdk.crt:aws-crt that would be provided by\nthe Uber-jar option. See the following Steps to determine the AWS CRT artifact version.\n3\nReplace the classifier value with one for your platform. Refer to the AWS CRT for Java\nGitHub page for a listing of available values.\nSteps to determine the AWS CRT artifact version\nUse the following steps to determine the AWS CRT artifact version that is compatible with the\nversion of the SDK for Java that you are using.\n1. Set up your pom.xml file as shown in the Uber-jar option. This setup allows you to see what\nversion of software.amazon.awssdk.crt:aws-crt the SDK brings in by default.\n2. At the root of the project (in the same directory as the pom.xml file), run the following\nMaven command:\nmvn dependency:tree -Dincludes=software.amazon.awssdk.crt:aws-crt\nMaven might perform other actions, but at the end you should see console output of the\nsoftware.amazon.awssdk.crt:aws-crt dependency that the SDK transitively uses.\nThe following snippet shows sample output based on an SDK version of 2.29.10:\n[INFO] org.example:yourProject:jar:1.0-SNAPSHOT\n[INFO] \\- software.amazon.awssdk:aws-crt-client:jar:2.29.10:compile\n[INFO] \\- software.amazon.awssdk.crt:aws-crt:jar:0.31.3:compile\n3. Use the version that the console shows for the software.amazon.awssdk.crt:aws-\ncrt artifact. In this case, add 0.31.3 to your pom.xml file.\nConfigure AWS CRT-based HTTP clients 96\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse and configure an AWS CRT-based HTTP client\nYou can configure an AWS CRT-based HTTP client along with building a service client, or you can\nconfigure a single instance to share across multiple service clients.\nWith either approach, you use a builder to configure the properties for the AWS CRT-based HTTP\nclient instance.\nBest practice: dedicate an instance to a service client\nIf you need to configure an instance of an AWS CRT-based HTTP client, we recommend that you\ndedicate the instance by building it along with the service client . You can do so by using the\nhttpClientBuilder method of the service client's builder. This way, the lifecycle of the HTTP\nclient is managed by the SDK, which helps avoid potential memory leaks if the AWS CRT-based\nHTTP client instance is not closed down when it's no longer needed.\nThe following example creates an S3 service client and configures an AWS CRT-based HTTP client\nwith connectionTimeout and maxConcurrency values.\nSynchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Duration;\nCode\n// Singleton: Use s3Client for all requests.\nS3Client s3Client = S3Client.builder()\n.httpClientBuilder(AwsCrtHttpClient\n.builder()\n.connectionTimeout(Duration.ofSeconds(3))\n.maxConcurrency(100))\n.build();\n// Perform work with the s3Client.\n// Requests completed: Close the s3Client.\ns3Client.close();\nConfigure AWS CRT-based HTTP clients 97\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAsynchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport java.time.Duration;\nCode\n// Singleton: Use s3AsyncClient for all requests.\nS3AsyncClient s3AsyncClient = S3AsyncClient.builder()\n.httpClientBuilder(AwsCrtAsyncHttpClient\n.builder()\n.connectionTimeout(Duration.ofSeconds(3))\n.maxConcurrency(100))\n.build();\n// Perform work with the s3AsyncClient.\n// Requests completed: Close the s3AsyncClient.\ns3AsyncClient.close();\nAlternative approach: share an instance\nTo help keep resource and memory usage lower for your application, you can configure an AWS\nCRT-based HTTP client and share it across multiple service clients. The HTTP connection pool will\nbe shared, which lowers resource usage.\nNote\nWhen an AWS CRT-based HTTP client instance is shared, you must close it when it is ready\nto be disposed. The SDK will not close the instance when the service client is closed.\nThe following example configures an AWS CRT-based HTTP client instance with\nconnectionTimeout and maxConcurrency values. The configured instance is passed to the\nhttpClient method of each service client's builder. When the service clients and the HTTP client\nare no longer needed, they are explicitly closed. The HTTP client is closed last.", "mimetype": "text/plain", "start_char_idx": 209359, "end_char_idx": 213738, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6dc21dc4-2085-468e-925d-753b0bb9ac54": {"__data__": {"id_": "6dc21dc4-2085-468e-925d-753b0bb9ac54", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e370cd1d-18af-49d3-afca-dde8cc7ce724", "node_type": "1", "metadata": {}, "hash": "875e1a7e969afd49f9f9e5eecd39ee7bc5d116303129cfa5c660205a8ef24e28", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "496dabbe-134f-48b6-9dd8-34d78307e950", "node_type": "1", "metadata": {}, "hash": "a9550893caacc5aad4459585bccbb598ac0b6ad7f94cf525b299786352b3cf8b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Requests completed: Close the s3AsyncClient.\ns3AsyncClient.close();\nAlternative approach: share an instance\nTo help keep resource and memory usage lower for your application, you can configure an AWS\nCRT-based HTTP client and share it across multiple service clients. The HTTP connection pool will\nbe shared, which lowers resource usage.\nNote\nWhen an AWS CRT-based HTTP client instance is shared, you must close it when it is ready\nto be disposed. The SDK will not close the instance when the service client is closed.\nThe following example configures an AWS CRT-based HTTP client instance with\nconnectionTimeout and maxConcurrency values. The configured instance is passed to the\nhttpClient method of each service client's builder. When the service clients and the HTTP client\nare no longer needed, they are explicitly closed. The HTTP client is closed last.\nConfigure AWS CRT-based HTTP clients 98\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSynchronous client\nImports\nimport\nsoftware.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nimport software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.crt.AwsCrtHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Duration;\nCode\n// Create an AwsCrtHttpClient shared instance.\nSdkHttpClient crtHttpClient = AwsCrtHttpClient.builder()\n.connectionTimeout(Duration.ofSeconds(3))\n.maxConcurrency(100)\n.build();\n// Singletons: Use the s3Client and dynamoDbClient for all requests.\nS3Client s3Client = S3Client.builder()\n.httpClient(crtHttpClient)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.crea\n.defaultsMode(DefaultsMode.IN_REGION)\n.region(Region.US_EAST_1)\n.build();\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.httpClient(crtHttpClient)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.crea\n.defaultsMode(DefaultsMode.IN_REGION)\n.region(Region.US_EAST_1)\n.build();\n// Requests completed: Close all service clients.\ns3Client.close();\ndynamoDbClient.close();\ncrtHttpClient.close(); // Explicitly close crtHttpClient.\nConfigure AWS CRT-based HTTP clients 99\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAsynchronous client\nImports\nimport\nsoftware.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nimport software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport java.time.Duration;\nCode\n// Create an AwsCrtAsyncHttpClient shared instance.\nSdkAsyncHttpClient crtAsyncHttpClient = AwsCrtAsyncHttpClient.builder()\n.connectionTimeout(Duration.ofSeconds(3))\n.maxConcurrency(100)\n.build();\n// Singletons: Use the s3AsyncClient and dynamoDbAsyncClient for all requests.\nS3AsyncClient s3AsyncClient = S3AsyncClient.builder()\n.httpClient(crtAsyncHttpClient)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.defaultsMode(DefaultsMode.IN_REGION)\n.region(Region.US_EAST_1)\n.build();\nDynamoDbAsyncClient dynamoDbAsyncClient = DynamoDbAsyncClient.builder()\n.httpClient(crtAsyncHttpClient)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.defaultsMode(DefaultsMode.IN_REGION)\n.region(Region.US_EAST_1)\n.build();\n// Requests completed: Close all service clients.\ns3AsyncClient.close();\ndynamoDbAsyncClient.close();\ncrtAsyncHttpClient.close(); // Explicitly close crtAsyncHttpClient.\nConfigure AWS CRT-based HTTP clients 100\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSet an AWS CRT-based HTTP client as the default\nYou can setup your Maven build file to have the SDK use an AWS CRT-based HTTP client as the\ndefault HTTP client for service clients.\nYou do this by adding an exclusions element with the default HTTP client dependencies to each\nservice client artifact.\nIn the following pom.xml example, the SDK uses an AWS CRT-based HTTP client for S3 services.\nIf the service client in your code is an S3AsyncClient, the SDK uses AwsCrtAsyncHttpClient.\nIf the service client is an S3Client, the SDK uses AwsCrtHttpClient. With this setup the default\nNetty-based asynchronous HTTP client and the default Apache-based synchronous HTTP are not\navailable.", "mimetype": "text/plain", "start_char_idx": 212876, "end_char_idx": 217437, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "496dabbe-134f-48b6-9dd8-34d78307e950": {"__data__": {"id_": "496dabbe-134f-48b6-9dd8-34d78307e950", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6dc21dc4-2085-468e-925d-753b0bb9ac54", "node_type": "1", "metadata": {}, "hash": "b82174b831a90af1a1ef33ef65f74743ac257307944cc2485d2c7100da6798d6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8c24a722-b617-4bf6-8a44-558c94c99861", "node_type": "1", "metadata": {}, "hash": "a8745b0813bbcc4510f53946fcab119b8f99543b972849494f7b078fa29c7e87", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "s3AsyncClient.close();\ndynamoDbAsyncClient.close();\ncrtAsyncHttpClient.close(); // Explicitly close crtAsyncHttpClient.\nConfigure AWS CRT-based HTTP clients 100\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSet an AWS CRT-based HTTP client as the default\nYou can setup your Maven build file to have the SDK use an AWS CRT-based HTTP client as the\ndefault HTTP client for service clients.\nYou do this by adding an exclusions element with the default HTTP client dependencies to each\nservice client artifact.\nIn the following pom.xml example, the SDK uses an AWS CRT-based HTTP client for S3 services.\nIf the service client in your code is an S3AsyncClient, the SDK uses AwsCrtAsyncHttpClient.\nIf the service client is an S3Client, the SDK uses AwsCrtHttpClient. With this setup the default\nNetty-based asynchronous HTTP client and the default Apache-based synchronous HTTP are not\navailable.\n\n\nVERSION\n\n\n\nsoftware.amazon.awssdk\ns3\n${aws.sdk.version}\n\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\n\nsoftware.amazon.awssdk\napache-client\n\n\n\n\nsoftware.amazon.awssdk\naws-crt-client\n\n\n\nVisit the Maven central repository for the latest VERSION value.\nConfigure AWS CRT-based HTTP clients 101\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf multiple service clients are declared in a pom.xml file, all require the exclusions XML\nelement.\nUse a Java system property\nTo use the AWS CRT-based HTTP clients as the default HTTP for your application, you can set the\nJava system property software.amazon.awssdk.http.async.service.impl to a value of\nsoftware.amazon.awssdk.http.crt.AwsCrtSdkHttpService.\nTo set during application startup, run a command similar to the following.\njava app.jar -Dsoftware.amazon.awssdk.http.async.service.impl=\\\nsoftware.amazon.awssdk.http.crt.AwsCrtSdkHttpService\nUse the following code snippet to set the system property in your application code.\nSystem.setProperty(\"software.amazon.awssdk.http.async.service.impl\",\n\"software.amazon.awssdk.http.crt.AwsCrtSdkHttpService\");\nNote\nYou need to add a dependency on the aws-crt-client artifact in your poml.xml file\nwhen you use a system property to configure the use of the AWS CRT-based HTTP clients.\nAdvanced configuration of AWS CRT-based HTTP clients\nYou can use various configuration settings of the AWS CRT-based HTTP clients, including\nconnection health configuration and maximum idle time. You can review the configuration\noptions available for the AwsCrtAsyncHttpClient. You can configure the same options for the\nAwsCrtHttpClient.\nConnection health configuration\nYou can configure connection health configuration for the AWS CRT-based HTTP clients by using\nthe connectionHealthConfiguration method on the HTTP client builder.\nConfigure AWS CRT-based HTTP clients 102\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following example creates an S3 service client that uses a AWS CRT-based HTTP client instance\nconfigured with connection health configuration and a maximum idle time for connections.\nSynchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Duration;\nCode\n// Singleton: Use the s3Client for all requests.\nS3Client s3Client = S3Client.builder()\n.httpClientBuilder(AwsCrtHttpClient\n.builder()\n.connectionHealthConfiguration(builder -> builder\n.minimumThroughputInBps(32000L)\n.minimumThroughputTimeout(Duration.ofSeconds(3)))\n.connectionMaxIdleTime(Duration.ofSeconds(5)))\n.build();\n// Perform work with s3Client.\n// Requests complete: Close the service client.\ns3Client.close();\nAsynchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport java.time.Duration;\nCode\n// Singleton: Use the s3AsyncClient for all requests.", "mimetype": "text/plain", "start_char_idx": 216540, "end_char_idx": 220781, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8c24a722-b617-4bf6-8a44-558c94c99861": {"__data__": {"id_": "8c24a722-b617-4bf6-8a44-558c94c99861", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "496dabbe-134f-48b6-9dd8-34d78307e950", "node_type": "1", "metadata": {}, "hash": "a9550893caacc5aad4459585bccbb598ac0b6ad7f94cf525b299786352b3cf8b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "41f8dc68-dabc-4c0e-b79b-5b2f849aa7f8", "node_type": "1", "metadata": {}, "hash": "90b3bf815e19b8b0d61eae7e2fb780585f1af2b165fee7414b10f9932f50d5be", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Synchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Duration;\nCode\n// Singleton: Use the s3Client for all requests.\nS3Client s3Client = S3Client.builder()\n.httpClientBuilder(AwsCrtHttpClient\n.builder()\n.connectionHealthConfiguration(builder -> builder\n.minimumThroughputInBps(32000L)\n.minimumThroughputTimeout(Duration.ofSeconds(3)))\n.connectionMaxIdleTime(Duration.ofSeconds(5)))\n.build();\n// Perform work with s3Client.\n// Requests complete: Close the service client.\ns3Client.close();\nAsynchronous client\nImports\nimport software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport java.time.Duration;\nCode\n// Singleton: Use the s3AsyncClient for all requests.\nS3AsyncClient s3AsyncClient = S3AsyncClient.builder()\n.httpClientBuilder(AwsCrtAsyncHttpClient\nConfigure AWS CRT-based HTTP clients 103\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.builder()\n.connectionHealthConfiguration(builder -> builder\n.minimumThroughputInBps(32000L)\n.minimumThroughputTimeout(Duration.ofSeconds(3)))\n.connectionMaxIdleTime(Duration.ofSeconds(5)))\n.build();\n// Perform work with s3AsyncClient.\n// Requests complete: Close the service client.\ns3AsyncClient.close();\nHTTP/2 support\nThe HTTP/2 protocol is not yet supported in the AWS CRT-based HTTP clients, but is planned for a\nfuture release.\nIn the meantime, if you are using service clients that require HTTP/2 support such\nas the KinesisAsyncClient or the TranscribeStreamingAsyncClient, consider using the\nNettyNioAsyncHttpClient instead.\nProxy configuration example\nThe following code snippet shows the use of the ProxyConfiguration.Builder that you use to\nconfigure proxy setting in code.\nSynchronous client\nImports\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.crt.AwsCrtHttpClient;\nimport software.amazon.awssdk.http.crt.ProxyConfiguration;\nCode\nSdkHttpClient crtHttpClient = AwsCrtHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.host(\"myproxy\")\n.port(1234)\nConfigure AWS CRT-based HTTP clients 104\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.username(\"username\")\n.password(\"password\")\n.nonProxyHosts(Set.of(\"localhost\", \"host.example.com\"))\n.build())\n.build();\nAsynchronous client\nImports\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;\nimport software.amazon.awssdk.http.crt.ProxyConfiguration;\nCode\nSdkAsyncHttpClient crtAsyncHttpClient = AwsCrtAsyncHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.host(\"myproxy\")\n.port(1234)\n.username(\"username\")\n.password(\"password\")\n.nonProxyHosts(Set.of(\"localhost\", \"host.example.com\"))\n.build())\n.build();\nThe equivalent Java system properties for the proxy configuration are shown in the following\ncommand line snippet.\n$ java -Dhttps.proxyHost=myproxy -Dhttps.proxyPort=1234 -Dhttps.proxyUser=username \\\n-Dhttps.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ...\nApp\nImportant\nTo use any of the HTTPS proxy system properties, the scheme property must be set in code\nto https. If the scheme property is not set in code, the scheme defaults to HTTP and the\nSDK looks only for http.* system properties.\nConfigure AWS CRT-based HTTP clients 105\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe equivalent setup that uses environment variables is:\n// Set the following environment variables.\n// $ export HTTPS_PROXY=\"https://username:password@myproxy:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkAsyncHttpClient crtAsyncHttpClient = AwsCrtAsyncHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\n// Run the application.\n// $ java -cp ... App\nConfigure HTTP proxies\nYou can configure HTTP proxies by using code, by setting Java system properties, or by setting\nenvironment variables.\nConfigure in code\nYou configure proxies in code with a client-specific ProxyConfiguration builder when you build\nthe service client. The following code shows an example proxy configuration for an Apache-based\nHTTP client that is used by an Amazon S3 service client.", "mimetype": "text/plain", "start_char_idx": 219960, "end_char_idx": 224382, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "41f8dc68-dabc-4c0e-b79b-5b2f849aa7f8": {"__data__": {"id_": "41f8dc68-dabc-4c0e-b79b-5b2f849aa7f8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8c24a722-b617-4bf6-8a44-558c94c99861", "node_type": "1", "metadata": {}, "hash": "a8745b0813bbcc4510f53946fcab119b8f99543b972849494f7b078fa29c7e87", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "82999996-b9ff-470b-b563-bd397252c078", "node_type": "1", "metadata": {}, "hash": "d036043437cdba74b47af5c9c66726e7c31bd95d8e5f513ba4ee4adc19283d60", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// $ export HTTPS_PROXY=\"https://username:password@myproxy:1234\"\n// $ export NO_PROXY=\"localhost|host.example.com\"\n// Set the 'useSystemPropertyValues' to false on the proxy configuration.\nSdkAsyncHttpClient crtAsyncHttpClient = AwsCrtAsyncHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build();\n// Run the application.\n// $ java -cp ... App\nConfigure HTTP proxies\nYou can configure HTTP proxies by using code, by setting Java system properties, or by setting\nenvironment variables.\nConfigure in code\nYou configure proxies in code with a client-specific ProxyConfiguration builder when you build\nthe service client. The following code shows an example proxy configuration for an Apache-based\nHTTP client that is used by an Amazon S3 service client.\nSdkHttpClient httpClient1 = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.endpoint(URI.create(\"http://proxy.example.com\"))\n.username(\"username\")\n.password(\"password\")\n.addNonProxyHost(\"localhost\")\n.build())\n.build();\nS3Client s3Client = S3Client.builder()\n.httpClient(httpClient)\n.build();\nThe section for each HTTP client in this topic shows a proxy configuration example.\nConfigure HTTP proxies 106\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Apache HTTP client\n\u2022 URLConnection-based HTTP client\n\u2022 Netty-based HTTP client\n\u2022 AWS CRT-based HTTP client\nConfigure HTTP proxies with external settings\nEven if you don't explicitly use a ProxyConfiguration builder in code, the SDK looks for external\nsettings to configure a default proxy configuration.\nBy default, the SDK first searches for JVM system properties. If even one property is found, the SDK\nuses the value and any other system property values. If no system properties are available, the SDK\nlooks for proxy environment variables.\nThe SDK can use the following Java system properties and environment variables.\nJava system properties\nSystem property Description HTTP client support\nhttp.proxyHost Host name of the HTTP proxy All\nserver\nhttp.proxyPort Port number of the HTTP All\nproxy server\nhttp.proxyUser Username for HTTP proxy All\nauthentication\nhttp.proxyPassword Password for HTTP proxy All\nauthentication\nhttp.nonProxyHosts List of hosts that should be All\nreached directly, bypassing\nthe proxy. This list is also valid\nwhen HTTPS is used.\nhttps.proxyHost Host name of the HTTPS Netty, CRT\nproxy server\nConfigure HTTP proxies 107\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem property Description HTTP client support\nhttps.proxyPort Port number of the HTTPS Netty, CRT\nproxy server\nhttps.proxyUser Username for HTTPS proxy Netty, CRT\nauthentication\nhttps.proxyPassword Password for HTTPS proxy Netty, CRT\nauthentication\nEnvironment variables\nEnvironment variable Description HTTP client support\n1\nHTTP_PROXY A valid URL with a scheme of All\nHTTP\n1\nHTTPS_PROXY A valid URL with a scheme of Netty, CRT\nHTTPS\n2\nNO_PROXY List of hosts that should be All\nreached directly, bypassing\nthe proxy. The list is valid for\nboth HTTP and HTTPS.\nView key and footnotes\nAll - All HTTP clients offered by the SDK\u2013UrlConnectionHttpClient, ApacheHttpClient,\nNettyNioAsyncHttpClient, AwsCrtAsyncHttpClient.\nNetty - The Netty-based HTTP client (NettyNioAsyncHttpClient).\nCRT - The AWS CRT-based HTTP clients, (AwsCrtHttpClient and AwsCrtAsyncHttpClient).\n1\nThe environment variable queried, whether HTTP_PROXY or HTTPS_PROXY, depends on the\nscheme setting in the client's ProxyConfiguration. The default scheme is HTTP. The following\nsnippet shows how to change the scheme to HTTPS used for environment variable resolution.\nConfigure HTTP proxies 108\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSdkHttpClient httpClient = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.scheme(\"https\")\n.build())\n.build();\n2\nThe NO_PROXY environment variable supports a mix of \"|\" and \",\" separators between host names.\nHost names may include the \"*\" wildcard.\nUse a combination of settings\nYou can use a combination of HTTP proxy settings in code, system properties, and environment\nvariables.\nExample \u2013 configuration provided by a system property and by code\n// Command line with the proxy password set as a system property.\n$ java -Dhttp.proxyPassword=SYS_PROP_password -cp ... App\n// Since the 'useSystemPropertyValues' setting is 'true' (the default), the SDK will\nsupplement\n// the proxy configuration in code with the 'http.proxyPassword' value from the system\nproperty.\nSdkHttpClient apacheHttpClient = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.endpoint(URI.create(\"http://localhost:1234\"))\n.username(\"username\")\n.build())\n.build();\n// Use the apache HTTP client with proxy configuration.", "mimetype": "text/plain", "start_char_idx": 223543, "end_char_idx": 228336, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "82999996-b9ff-470b-b563-bd397252c078": {"__data__": {"id_": "82999996-b9ff-470b-b563-bd397252c078", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "41f8dc68-dabc-4c0e-b79b-5b2f849aa7f8", "node_type": "1", "metadata": {}, "hash": "90b3bf815e19b8b0d61eae7e2fb780585f1af2b165fee7414b10f9932f50d5be", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fc8c2054-8783-47d2-8fc5-eb7cf34276db", "node_type": "1", "metadata": {}, "hash": "024b3b64c4459248f8509bcffc6c8ac4a99019256a559c0a07196808254632b9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Host names may include the \"*\" wildcard.\nUse a combination of settings\nYou can use a combination of HTTP proxy settings in code, system properties, and environment\nvariables.\nExample \u2013 configuration provided by a system property and by code\n// Command line with the proxy password set as a system property.\n$ java -Dhttp.proxyPassword=SYS_PROP_password -cp ... App\n// Since the 'useSystemPropertyValues' setting is 'true' (the default), the SDK will\nsupplement\n// the proxy configuration in code with the 'http.proxyPassword' value from the system\nproperty.\nSdkHttpClient apacheHttpClient = ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.endpoint(URI.create(\"http://localhost:1234\"))\n.username(\"username\")\n.build())\n.build();\n// Use the apache HTTP client with proxy configuration.\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.httpClient(apacheHttpClient)\n.build();\nThe SDK resolves the following proxy settings.\nHost = localhost\nPort = 1234\nPassword = SYS_PROP_password\nUserName = username\nNon ProxyHost = null\nConfigure HTTP proxies 109\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExample \u2013 both system properties and environment variables are available\nEach HTTP client's ProxyConfiguration builder offers settings named\nuseSystemPropertyValues and useEnvironmentVariablesValues. By default, both setting\nare true. When true, the SDK automatically uses values from system properties or environment\nvariables for options that are not provided by the ProxyConfiguration builder.\nImportant\nSystem properties take precedence over environment variables. If an HTTP proxy system\nproperty is found, the SDK retrieves all values from system properties and none from\nenvironment variables. If you want to prioritize environment variables over system\nproperties, set useSystemPropertyValues to false.\nFor this example, the following settings are available a runtime:\n// System properties\nhttp.proxyHost=SYS_PROP_HOST.com\nhttp.proxyPort=2222\nhttp.password=SYS_PROP_PASSWORD\nhttp.user=SYS_PROP_USER\n// Environment variables\nHTTP_PROXY=\"http://EnvironmentUser:EnvironmentPassword@ENV_VAR_HOST:3333\"\nNO_PROXY=\"environmentnonproxy.host,environmentnonproxy2.host:1234\"\nThe service client is created with one of the following statements. None of the statements\nexplicitly set a proxy setting.\nDynamoDbClient client = DynamoDbClient.create();\nDynamoDbClient client = DynamoDbClient.builder().build();\nDynamoDbClient client = DynamoDbClient.builder()\n.httpClient(ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.build())\n.build())\n.build();\nThe following proxy settings are resolved by the SDK:\nConfigure HTTP proxies 110\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHost = SYS_PROP_HOST.com\nPort = 2222\nPassword = SYS_PROP_PASSWORD\nUserName = SYS_PROP_USER\nNon ProxyHost = null\nBecause the service client has default proxy settings, the SDK searches for system properties and\nthen environment variables. Since system properties settings take precedence over environment\nvariables, the SDK uses only system properties.\nIf the use of system properties is changed to false as shown in the following code, the SDK\nresolves only the environment variables.\nDynamoDbClient client = DynamoDbClient.builder()\n.httpClient(ApacheHttpClient.builder()\n.proxyConfiguration(ProxyConfiguration.builder()\n.useSystemPropertyValues(Boolean.FALSE)\n.build())\n.build())\n.build();\nThe resolved proxy settings using HTTP are:\nHost = ENV_VAR_HOST\nPort = 3333\nPassword = EnvironmentPassword\nUserName = EnvironmentUser\nNon ProxyHost = environmentnonproxy.host, environmentnonproxy2.host:1234\nException handling for the AWS SDK for Java 2.x\nUnderstanding how and when the AWS SDK for Java 2.x throws exceptions is important to building\nhigh-quality applications using the SDK. The following sections describe the different cases of\nexceptions that are thrown by the SDK and how to handle them appropriately.\nWhy unchecked exceptions?\nThe AWS SDK for Java uses runtime (or unchecked) exceptions instead of checked exceptions for\nthese reasons:\nException handling 111\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 To allow developers fine-grained control over the errors they want to handle without forcing\nthem to handle exceptional cases they aren\u2019t concerned about (and making their code overly\nverbose)\n\u2022 To prevent scalability issues inherent with checked exceptions in large applications\nIn general, checked exceptions work well on small scales, but can become troublesome as\napplications grow and become more complex.\nAwsServiceException (and subclasses)\nAwsServiceException is the most common exception that you\u2019ll experience when using the AWS\nSDK for Java. AwsServiceException is a subclass of the more general SdkServiceException.\nAwsServiceExceptions represent an error response from an AWS service.", "mimetype": "text/plain", "start_char_idx": 227525, "end_char_idx": 232388, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fc8c2054-8783-47d2-8fc5-eb7cf34276db": {"__data__": {"id_": "fc8c2054-8783-47d2-8fc5-eb7cf34276db", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "82999996-b9ff-470b-b563-bd397252c078", "node_type": "1", "metadata": {}, "hash": "d036043437cdba74b47af5c9c66726e7c31bd95d8e5f513ba4ee4adc19283d60", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c94b42a5-99f6-49c7-91cd-d3c4d818ee95", "node_type": "1", "metadata": {}, "hash": "ee3216d5e6677f8f88cf9d95192d1b8833942e7108e8a1a5cadf9a6d50832488", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following sections describe the different cases of\nexceptions that are thrown by the SDK and how to handle them appropriately.\nWhy unchecked exceptions?\nThe AWS SDK for Java uses runtime (or unchecked) exceptions instead of checked exceptions for\nthese reasons:\nException handling 111\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 To allow developers fine-grained control over the errors they want to handle without forcing\nthem to handle exceptional cases they aren\u2019t concerned about (and making their code overly\nverbose)\n\u2022 To prevent scalability issues inherent with checked exceptions in large applications\nIn general, checked exceptions work well on small scales, but can become troublesome as\napplications grow and become more complex.\nAwsServiceException (and subclasses)\nAwsServiceException is the most common exception that you\u2019ll experience when using the AWS\nSDK for Java. AwsServiceException is a subclass of the more general SdkServiceException.\nAwsServiceExceptions represent an error response from an AWS service. For example, if you try\nto terminate an Amazon EC2 instance that doesn\u2019t exist, Amazon EC2 will return an error response\nand all the details of that error response will be included in the AwsServiceException that\u2019s\nthrown.\nWhen you encounter an AwsServiceException, you know that your request was successfully\nsent to the AWS service but couldn\u2019t be successfully processed. This can be because of errors in the\nrequest\u2019s parameters or because of issues on the service side.\nAwsServiceException provides you with information such as:\n\u2022 Returned HTTP status code\n\u2022 Returned AWS error code\n\u2022 Detailed error message from the service in the AwsErrorDetails class\n\u2022 AWS request ID for the failed request\nIn most cases, a service-specific subclass of AwsServiceException is thrown to allow developers\nfine-grained control over handling error cases through catch blocks. The Java SDK API reference\nfor AwsServiceException displays the large number of AwsServiceException subclasses. Use the\nsubclass links to drill down to see the granular exceptions thrown by a service.\nFor example, the following links to the SDK API reference show the exception hierarchies for a few\ncommon AWS services. The list of subclasses shown on each pages shows the specific exceptions\nthat your code can catch.\n\u2022 Amazon S3\nAwsServiceException (and subclasses) 112\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 DynamoDB\n\u2022 Amazon SQS\nTo learn more about an exception, inspect the errorCode on the AwsErrorDetails object. You\ncan use the errorCode value to look up information in the service guide API. For example if an\nS3Exception is caught and the AwsErrorDetails#errorCode() value is InvalidRequest,\nuse the list of error codes in the Amazon S3 API Reference to see more details.\nSdkClientException\nSdkClientException indicates that a problem occurred inside the Java client code, either\nwhile trying to send a request to AWS or while trying to parse a response from AWS. An\nSdkClientException is generally more severe than an SdkServiceException, and indicates a\nmajor problem that is preventing the client from making service calls to AWS services. For example,\nthe AWS SDK for Java throws an SdkClientException if no network connection is available\nwhen you try to call an operation on one of the clients.\nExceptions and retry behavior\nThe SDK for Java retries requests for several client-side exceptions and for HTTP status codes that\nit receives from AWS service responses. These errors are handled as part of the legacy RetryMode\nthat service clients use by default. The Java API reference for RetryMode describes the various\nways that you can configure the mode.\nTo customize the exceptions and HTTP status codes that trigger automatic retries, configure\nyour service client with a RetryPolicy that adds RetryOnExceptionsCondition and\nRetryOnStatusCodeCondition instances.\nRetries\nCalls to AWS services can fail occasionally for unexpected reasons. Certain errors, such as throttling\n(rate exceeded) or transient errors, might succeed if the call is retried. The AWS SDK for Java 2.x\nhas a built-in mechanism to detect such errors and automatically retry the call that is enabled by\ndefault for all clients.\nThis page describes how this works, how to configure the distinct modes, and tailor the retry\nbehavior.\nSdkClientException 113\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRetry strategies\nA retry strategy is a mechanism used in the SDK to implement retries. Each SDK client has a retry\nstrategy created at build time that cannot be modified after the client is built.\nThe retry strategy has the following responsibilities.\n\u2022 Classify exceptions as retryable or not.\n\u2022 Compute the suggested delay to wait before the next attempt.\n\u2022 Maintain a token bucket that provides a mechanism to stop retries when a large percentage of\nrequests are failing and retries are unsuccessful.", "mimetype": "text/plain", "start_char_idx": 231347, "end_char_idx": 236269, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c94b42a5-99f6-49c7-91cd-d3c4d818ee95": {"__data__": {"id_": "c94b42a5-99f6-49c7-91cd-d3c4d818ee95", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fc8c2054-8783-47d2-8fc5-eb7cf34276db", "node_type": "1", "metadata": {}, "hash": "024b3b64c4459248f8509bcffc6c8ac4a99019256a559c0a07196808254632b9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fe5542d6-7059-4a5c-8d5f-dd46425348d0", "node_type": "1", "metadata": {}, "hash": "ce8abf4225c0868b0c8fcc7422c82ae67b796c20e6b28794fdfd0aa1f2bf0eaf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Certain errors, such as throttling\n(rate exceeded) or transient errors, might succeed if the call is retried. The AWS SDK for Java 2.x\nhas a built-in mechanism to detect such errors and automatically retry the call that is enabled by\ndefault for all clients.\nThis page describes how this works, how to configure the distinct modes, and tailor the retry\nbehavior.\nSdkClientException 113\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRetry strategies\nA retry strategy is a mechanism used in the SDK to implement retries. Each SDK client has a retry\nstrategy created at build time that cannot be modified after the client is built.\nThe retry strategy has the following responsibilities.\n\u2022 Classify exceptions as retryable or not.\n\u2022 Compute the suggested delay to wait before the next attempt.\n\u2022 Maintain a token bucket that provides a mechanism to stop retries when a large percentage of\nrequests are failing and retries are unsuccessful.\nNote\nBefore the release of retry strategies with version 2.26.0 of the SDK, retry policies\nprovided the retry mechanism in the SDK. The retry policy API is made up of the core\nRetryPolicy class in the software.amazon.awssdk.core.retry package, whereas\nthe software.amazon.awssdk.retries package contains the retry strategy API\nelements.\nThe retry strategy API was introduced as part of the AWS-wide effort to unify the interfaces\nand behavior of the core components of the SDKs.\nThe SDK for Java 2.x has three built-in retry strategies: standard, legacy, and adaptive. All three\nretry strategies are preconfigured to retry on a set of retryable exceptions. Examples of retryable\nerrors are socket timeouts, service-side throttling, concurrency or optimistic lock failures, and\ntransient service errors.\nStandard retry strategy\nThe standard retry strategy is the recommended RetryStrategy implementation for normal use\ncases. Unlike the AdaptiveRetryStrategy, the standard strategy is generally useful across all\nretry use cases.\nBy default, the standard retry strategy does the following.\n\u2022 Retries on the conditions that are configured at build time. You can adjust this with\nStandardRetryStrategy.Builder#retryOnException.\nRetry strategies 114\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Retries 2 times for a total of 3 attempts. You can adjust this with\nStandardRetryStrategy.Builder#maxAttempts(int).\n\u2022 For non-throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff\nstrategy, with a base delay of 100 milliseconds and a max delay of 20 seconds. You can adjust\nthis with StandardRetryStrategy.Builder#backoffStrategy.\n\u2022 For throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff\nstrategy, with a base delay of 1 second and a max delay of 20 seconds. You can adjust this with\nStandardRetryStrategy.Builder#throttlingBackoffStrategy.\n\u2022 Performs circuit breaking (disabling retries) in the event of high downstream\nfailures. The first attempt is always executed, only retries are disabled. Adjust with\nStandardRetryStrategy.Builder#circuitBreakerEnabled.\nLegacy retry strategy\nThe legacy retry strategy is a RetryStrategy for normal use cases, however, it is deprecated in\nfavor of the StandardRetryStrategy. This is the default retry strategy used by clients when you\ndon't specify another strategy.\nIt is characterized by treating throttling and non-throttling exceptions differently, for throttling\nexceptions the base delay for the backoff is larger (500ms) than the base delay for non-throttling\nexceptions (100ms), and throttling exceptions do not affect the token bucket state.\nExperience using this strategy at scale inside AWS has shown that is not particularly better than the\nstandard retry strategy. Moreover, it fails to protect downstream services from retry storms and can\nlead to resource starvation on the client side.\nBy default, the legacy retry strategy does the following.\n\u2022 Retries on the conditions that are configured at build time. You can adjust this with\nLegacyRetryStrategy.Builder#retryOnException .\n\u2022 Retries 3 times for a total of 4 attempts. You can adjust this with\nLegacyRetryStrategy.Builder#maxAttempts(int).\n\u2022 For non-throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff\nstrategy, with a base delay of 100 milliseconds and a max delay of 20 seconds. You can adjust\nthis with LegacyRetryStrategy.Builder#backoffStrategy.\nRetry strategies 115\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff strategy,\nwith a base delay of 500 milliseconds and a max delay of 20 seconds. You can adjust this with\nLegacyRetryStrategy.Builder#throttlingBackoffStrategy.", "mimetype": "text/plain", "start_char_idx": 235327, "end_char_idx": 240018, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fe5542d6-7059-4a5c-8d5f-dd46425348d0": {"__data__": {"id_": "fe5542d6-7059-4a5c-8d5f-dd46425348d0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c94b42a5-99f6-49c7-91cd-d3c4d818ee95", "node_type": "1", "metadata": {}, "hash": "ee3216d5e6677f8f88cf9d95192d1b8833942e7108e8a1a5cadf9a6d50832488", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "792c4dce-31fd-4131-9c27-a19e6dded82e", "node_type": "1", "metadata": {}, "hash": "324d93ec21a82cc078b05fabafd44ae47c6d47723efbf7e571488411599065ac", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 Retries on the conditions that are configured at build time. You can adjust this with\nLegacyRetryStrategy.Builder#retryOnException .\n\u2022 Retries 3 times for a total of 4 attempts. You can adjust this with\nLegacyRetryStrategy.Builder#maxAttempts(int).\n\u2022 For non-throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff\nstrategy, with a base delay of 100 milliseconds and a max delay of 20 seconds. You can adjust\nthis with LegacyRetryStrategy.Builder#backoffStrategy.\nRetry strategies 115\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For throttling exceptions, it uses the BackoffStrategy#exponentialDelay backoff strategy,\nwith a base delay of 500 milliseconds and a max delay of 20 seconds. You can adjust this with\nLegacyRetryStrategy.Builder#throttlingBackoffStrategy.\n\u2022 Performs circuit breaking (disabling retries) in the event of high downstream failures.\nCircuit breaking never prevents a successful first attempt. You can adjust this behavior with\nLegacyRetryStrategy.Builder#circuitBreakerEnabled.\n\u2022 The state of the circuit breaker is not affected by throttling exceptions.\nAdaptive retry strategy\nThe adaptive retry strategy is a RetryStrategy for use cases with a high level of resource\nconstraints.\nThe adaptive retry strategy includes all the features of the standard strategy and adds a client-\nside rate limiter that measures the rate of throttled requests compared to non-throttled requests.\nThe strategy uses this measurement to slow down the requests in an attempt to stay within a safe\nbandwidth, ideally causing zero throttling errors.\nBy default, the adaptive retry strategy does the following.\n\u2022 Retries on the conditions that are configured at build time. You can adjust this with\nAdaptiveRetryStrategy.Builder#retryOnException .\n\u2022 Retries 2 times for a total of 3 attempts. You can adjust this with\nAdaptiveRetryStrategy.Builder#maxAttempts(int).\n\u2022 Uses a dynamic backoff delay that is based on the current load against the downstream resource.\n\u2022 Performs circuit breaking (disabling retries) when there are high number of downstream failures.\nCircuit breaking may prevent a second attempt in outage scenarios to protect the downstream\nservice.\nWarning\nThe adaptive retry strategy assumes that the client works against a single resource (for\nexample, one DynamoDB table or one Amazon S3 bucket).\nIf you use a single client for multiple resources, throttling or outages associated with\none resource result in increased latency and failures when the client accesses all other\nRetry strategies 116\nAWS SDK for Java 2.x Developer Guide for version 2.x\nresources. When you use the adaptive retry strategy, we recommend that you use a single\nclient for each resource.\nWe also recommend that you use this strategy in situations where all clients use the\nadaptive retry strategy against the resource.\nImportant\nThe release of retry strategies with 2.26.0 of the Java SDK includes the new\nRetryMode.ADAPTIVE_V2 enumeration value. The ADAPTIVE_V2 mode corrects an error\nthat failed to delay the first attempt when throttling errors were detected previously.\nWith the 2.26.0 release, users automatically get the ADAPTIVE_V2 mode behavior by\nsetting the mode as adaptive with an environment variable, system property, or profile\nsetting. There is no adaptive_v2 value for these settings. See the following the section\ncalled \u201cSpecify a strategy\u201d section for how to set the mode.\nUsers can get the previous behavior by setting the mode in code using\nRetryMode.ADAPTIVE.\nSummary: Comparison of retry strategy default values\nThe following table shows the default values for the properties of each retry strategy.\nStrategy Maximum Base delay Base Token Token cost Token\nattempts for non- delay for bucket per non- cost per\nthrottling throttling size throttling throttling\nerrors errors retry retry\nStandard 3 100 ms 1000 ms 500 5 5\nLegacy 4 100 ms 500 ms 500 5 0\nAdaptive 3 100 ms 100 ms 500 5 5\nSpecify a strategy\nYou have four ways to specify a strategy for your service client.\nSpecify a strategy 117\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn code\nWhen you build a client, you can configure a lambda expression with a retry strategy. The following\nsnippet configures a standard retry strategy that uses default values on a DynamoDB service client.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(RetryMode.STANDARD))\n.build();\nYou can specify RetryMode.LEGACY or RetryMode.ADAPTIVE in place of\nRetryMode.STANDARD.\nAs a profile setting\nInclude retry_mode as profile setting in the shared AWS config file.", "mimetype": "text/plain", "start_char_idx": 239218, "end_char_idx": 243821, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "792c4dce-31fd-4131-9c27-a19e6dded82e": {"__data__": {"id_": "792c4dce-31fd-4131-9c27-a19e6dded82e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fe5542d6-7059-4a5c-8d5f-dd46425348d0", "node_type": "1", "metadata": {}, "hash": "ce8abf4225c0868b0c8fcc7422c82ae67b796c20e6b28794fdfd0aa1f2bf0eaf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0934db89-8d06-4383-9892-2f10e1613d52", "node_type": "1", "metadata": {}, "hash": "56913eb1da544e12c510057a02d6471eb4b48750a941cff32f259254e42cc417", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Specify a strategy 117\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn code\nWhen you build a client, you can configure a lambda expression with a retry strategy. The following\nsnippet configures a standard retry strategy that uses default values on a DynamoDB service client.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(RetryMode.STANDARD))\n.build();\nYou can specify RetryMode.LEGACY or RetryMode.ADAPTIVE in place of\nRetryMode.STANDARD.\nAs a profile setting\nInclude retry_mode as profile setting in the shared AWS config file. Specify standard, legacy,\nor adaptive as a value. When set as a profile setting, all service clients that are created while the\nprofile is active use the specified retry strategy with default values. You can override this setting by\nconfiguring a retry strategy in code as shown previously.\nWith the following profile, all service clients use the standard retry strategy.\n[profile dev]\nregion = us-east-2\nretry_mode = standard\nAs a JVM system property\nYou can configure a retry stategy for all service clients, unless overridden in code, by using the\nsystem property aws.retryMode. Specify standard, legacy, or adaptive as a value.\nUse the -D switch when you invoke Java as shown in the following command.\njava -Daws.retryMode=standard ...\nAlternatively, set the system property in the code before creating any client as shown in the\nfollowing snippet.\npublic void main(String[] args) {\n// Set the property BEFORE any AWS service clients are created.\nSystem.setProperty(\"aws.retryMode\", \"standard\");\nSpecify a strategy 118\nAWS SDK for Java 2.x Developer Guide for version 2.x\n...\n}\nWith an environment variable\nYou can also use the AWS_RETRY_MODE environment variable with a value of standard, legacy,\nor adaptive. As with a profile setting or JVM system property, the environment variable\nconfigures all service clients with the specified retry mode unless you configure a client in code.\nThe following command sets the retry mode to standard for the current shell session.\nexport AWS_RETRY_MODE=standard\nCustomize a strategy\nYou can customize any retry strategy by setting the maximum attempts, backoff strategy, and\nexceptions that are retryable. You can customize when you build a retry strategy or when you build\na client by using a override builder that allows further refinements of the configured strategy.\nCustomize maximum attempts\nYou can configure the maximum number of attempts during client construction as shown in the\nfollowing statement. The following statement customizes the default retry strategy for the client\nto a maximum of 5 attempt--a first attempt plus 4 retries.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(b -> b.maxAttempts(5)))\n.build();\nAlternatively, you can build the strategy and provide it to the client as in the following code\nexample. The following code replaces the standard 3 maximum attempts with 10 and configures a\nDynamoDB client with the customized strategy.\nStandardRetryStrategy strategy = AwsRetryStrategy.standardRetryStrategy()\n.toBuilder()\n.maxAttempts(10)\n.build();\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(strategy))\n.build();\nCustomize a strategy 119\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWarning\nWe recommended that you configure each client with a unique RetryStrategy instance.\nIf a RetryStrategy instance is shared, failures in one client might affect the retry\nbehavior in the other.\nYou can also set the maximum number of attempts for all clients by using external settings instead\nof code. You configure this setting as describe in the the section called \u201cSpecify a strategy\u201d section.\nCustomize retryable exceptions\nYou can configure additional exceptions that trigger retires during client construction. This\ncustomization is provided for edge cases where exceptions are thrown that are not included in the\ndefault set of retryable exceptions.\nThe following code snippet shows the methods you use to customize the retry\nexceptions--retryOnException and retryOnExceptionOrCause. The\nretryOnExceptionOrCause methods adds a retryable exception if the SDK throws the direct\nexception or if the exception is wrapped.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(\nb -> b.retryOnException(EdgeCaseException.class)\n.retryOnExceptionOrCause(WrappedEdgeCaseException.class)))\n.build();\nCustomize the backoff strategy\nYou can build the backoff strategy and supply it to the client.\nThe following code builds a BackoffStrategy that replaces the default, standard strategy's\nexponential delay backoff strategy.\nBackoffStrategy backoffStrategy =\nBackoffStrategy.exponentialDelay(Duration.ofMillis(150), // The base delay.\nDuration.ofSeconds(15)); // The maximum delay.", "mimetype": "text/plain", "start_char_idx": 243237, "end_char_idx": 248103, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0934db89-8d06-4383-9892-2f10e1613d52": {"__data__": {"id_": "0934db89-8d06-4383-9892-2f10e1613d52", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "792c4dce-31fd-4131-9c27-a19e6dded82e", "node_type": "1", "metadata": {}, "hash": "324d93ec21a82cc078b05fabafd44ae47c6d47723efbf7e571488411599065ac", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a886fe5a-d752-4078-8f5a-8991d9fd9f34", "node_type": "1", "metadata": {}, "hash": "af14bdda88bbb943979e5c9502d3dacb808ae028e87e06620f63f8e78349ffc8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following code snippet shows the methods you use to customize the retry\nexceptions--retryOnException and retryOnExceptionOrCause. The\nretryOnExceptionOrCause methods adds a retryable exception if the SDK throws the direct\nexception or if the exception is wrapped.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(\nb -> b.retryOnException(EdgeCaseException.class)\n.retryOnExceptionOrCause(WrappedEdgeCaseException.class)))\n.build();\nCustomize the backoff strategy\nYou can build the backoff strategy and supply it to the client.\nThe following code builds a BackoffStrategy that replaces the default, standard strategy's\nexponential delay backoff strategy.\nBackoffStrategy backoffStrategy =\nBackoffStrategy.exponentialDelay(Duration.ofMillis(150), // The base delay.\nDuration.ofSeconds(15)); // The maximum delay.\nDynamoDbClient client = DynamoDbClient.builder()\n.overrideConfiguration(o -> o.retryStrategy(\nb -> b.backoffStrategy(backoffStrategy)))\nCustomize a strategy 120\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nMigrating from RetryPolicy to RetryStrategy\nRetryPolicy (the retry policy API) will be supported for the foreseeable future. If you currently\nuse an instance of RetryPolicy to configure your client, everything is going to work as before.\nBehind the scenes the Java SDK adapts it to a RetryStrategy. The new retry strategy interfaces\nprovide the same functionality as a RetryPolicy but are created and configured differently.\nLogging with the SDK for Java 2.x\nThe AWS SDK for Java 2.x uses SLF4J, which is an abstraction layer that enables the use of any one\nof several logging systems at runtime.\nSupported logging systems include the Java Logging Framework and Apache Log4j 2, among\nothers. This topic shows you how to use Log4j 2 as the logging system for working with the SDK.\nLog4j 2 configuration file\nYou typically use a configuration file, namedlog4j2.xml with Log4j 2. Example configuration files\nare shown below. To learn more about the values used in the configuration file, see the manual for\nLog4j configuration.\nThe log4j2.xml file needs to be on the classpath when your application starts up. For a Maven\nproject, put the file in the /src/main/resources directory.\nThe log4j2.xml configuration file specifies properties such as logging level, where logging\noutput is sent (for example, to a file or to the console), and the format of the output. The logging\nlevel specifies the level of detail that Log4j 2 outputs. Log4j 2 supports the concept of multiple\nlogging hierarchies. The logging level is set independently for each hierarchy. The main logging\nhierarchy that you use with the AWS SDK for Java 2.x is software.amazon.awssdk.\nAdd logging dependency\nTo configure the Log4j 2 binding for SLF4J in your build file, use the following.\nMaven\nAdd the following elements to your pom.xml file.\nMigrating from RetryPolicy to RetryStrategy 121\nAWS SDK for Java 2.x Developer Guide for version 2.x\n...\n\norg.apache.logging.log4j\nlog4j-slf4j2-impl\nVERSION\n\n...\nGradle\u2013Kotlin DSL\nAdd the following to your build.gradle.kts file.\n...\ndependencies {\n...\nimplementation(\"org.apache.logging.log4j:log4j-slf4j2-impl:VERSION\")\n...\n}\n...\nUse 2.20.0 for the minimum version of the log4j-slf4j2-impl artifact. For the latest version,\nuse the version published to Maven central. Replace VERSION with version you'll use.\nSDK-specific errors and warnings\nWe recommend that you always leave the \"software.amazon.awssdk\" logger hierarchy set to\n\"WARN\" to catch any important messages from the SDK's client libraries. For example, if the\nAmazon S3 client detects that your application hasn\u2019t properly closed an InputStream and could\nbe leaking resources, the S3 client reports it through a warning message to the logs. This also\nensures that messages are logged if the client has any problems handling requests or responses.\nThe following log4j2.xml file sets the rootLogger to \"WARN\", which causes warning\nand error-level messages from all loggers in the application to be output, including\nthose in the \"software.amazon.awssdk\" hierarchy. Alternatively, you can explicitly set the\n\"software.amazon.awssdk\" logger hierarchy to \"WARN\" if is used.", "mimetype": "text/plain", "start_char_idx": 247245, "end_char_idx": 251589, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a886fe5a-d752-4078-8f5a-8991d9fd9f34": {"__data__": {"id_": "a886fe5a-d752-4078-8f5a-8991d9fd9f34", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0934db89-8d06-4383-9892-2f10e1613d52", "node_type": "1", "metadata": {}, "hash": "56913eb1da544e12c510057a02d6471eb4b48750a941cff32f259254e42cc417", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4b45aeb3-6ab9-4abf-aece-bcd4bf713aac", "node_type": "1", "metadata": {}, "hash": "a15d8308d23ec182645247f5956d83ab44e30e026579e3c599853a54d9aa6d11", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Replace VERSION with version you'll use.\nSDK-specific errors and warnings\nWe recommend that you always leave the \"software.amazon.awssdk\" logger hierarchy set to\n\"WARN\" to catch any important messages from the SDK's client libraries. For example, if the\nAmazon S3 client detects that your application hasn\u2019t properly closed an InputStream and could\nbe leaking resources, the S3 client reports it through a warning message to the logs. This also\nensures that messages are logged if the client has any problems handling requests or responses.\nThe following log4j2.xml file sets the rootLogger to \"WARN\", which causes warning\nand error-level messages from all loggers in the application to be output, including\nthose in the \"software.amazon.awssdk\" hierarchy. Alternatively, you can explicitly set the\n\"software.amazon.awssdk\" logger hierarchy to \"WARN\" if is used.\nExample Log4j2.xml configuration file\nThis configuration will log messages at the \"ERROR\" and \"WARN\" levels to the console for all logger\nhierarchies.\nSDK-specific errors and warnings 122\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\n\n\n\n\n\n\n\n\n\n\nRequest/response summary logging\nEvery request to an AWS service generates a unique AWS request ID that is useful if you run\ninto an issue with how an AWS service is handling a request. AWS request IDs are accessible\nprogrammatically through SdkServiceException objects in the SDK for any failed service call,\nand can also be reported through the \"DEBUG\" log level of the \"software.amazon.awssdk.request\"\nlogger.\nThe following log4j2.xml file enables a summary of requests and responses.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nHere is an example of the log output:\nRequest/response summary logging 123\nAWS SDK for Java 2.x Developer Guide for version 2.x\n2022-09-23 16:02:08 [main] DEBUG software.amazon.awssdk.request:85 - Sending Request:\nDefaultSdkHttpFullRequest(httpMethod=POST, protocol=https, host=dynamodb.us-\neast-1.amazonaws.com, encodedPath=/, headers=[amz-sdk-invocation-id, Content-Length,\nContent-Type, User-Agent, X-Amz-Target], queryParameters=[])\n2022-09-23 16:02:08 [main] DEBUG software.amazon.awssdk.request:85 - Received\nsuccessful response: 200, Request ID:\nQS9DUMME2NHEDH8TGT9N5V53OJVV4KQNSO5AEMVJF66Q9ASUAAJG, Extended Request ID: not\navailable\nIf you are interested in only the request ID use .\nDebug-level SDK logging\nIf you need more detail about what the SDK is doing, you can set the logging level of the\nsoftware.amazon.awssdk logger to DEBUG. At this level, the SDK outputs a large amount of\ndetail, so we recommend that you set this level to resolve errors using integration tests.\nAt this logging level, the SDK logs information about configuration, credentials resolution,\nexecution interceptors, high-level TLS activity, request signing, and much more.\nThe following is a sampling of statements that are output by the SDK at DEBUG level for a\nS3Client#listBuckets() call.\nDEBUG s.a.a.r.p.AwsRegionProviderChain:57 - Unable to load region from\nsoftware.amazon.awssdk.regions.providers.SystemSettingsRegionProvider@324dcd31:Unable\nto load region from system settings. Region must be specified either via environment\nvariable (AWS_REGION) or system property (aws.region).", "mimetype": "text/plain", "start_char_idx": 250706, "end_char_idx": 254671, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4b45aeb3-6ab9-4abf-aece-bcd4bf713aac": {"__data__": {"id_": "4b45aeb3-6ab9-4abf-aece-bcd4bf713aac", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a886fe5a-d752-4078-8f5a-8991d9fd9f34", "node_type": "1", "metadata": {}, "hash": "af14bdda88bbb943979e5c9502d3dacb808ae028e87e06620f63f8e78349ffc8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c1455980-7e31-4bab-af1c-b99b3e2a4625", "node_type": "1", "metadata": {}, "hash": "a6c7ff7c184fd1e3b464f6d9b54069e8fc6c630a98f1b638c3735d4522f8a891", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Debug-level SDK logging\nIf you need more detail about what the SDK is doing, you can set the logging level of the\nsoftware.amazon.awssdk logger to DEBUG. At this level, the SDK outputs a large amount of\ndetail, so we recommend that you set this level to resolve errors using integration tests.\nAt this logging level, the SDK logs information about configuration, credentials resolution,\nexecution interceptors, high-level TLS activity, request signing, and much more.\nThe following is a sampling of statements that are output by the SDK at DEBUG level for a\nS3Client#listBuckets() call.\nDEBUG s.a.a.r.p.AwsRegionProviderChain:57 - Unable to load region from\nsoftware.amazon.awssdk.regions.providers.SystemSettingsRegionProvider@324dcd31:Unable\nto load region from system settings. Region must be specified either via environment\nvariable (AWS_REGION) or system property (aws.region).\nDEBUG s.a.a.c.i.h.l.ClasspathSdkHttpServiceProvider:85 - The HTTP implementation loaded\nis software.amazon.awssdk.http.apache.ApacheSdkHttpService@a23a01d\nDEBUG s.a.a.c.i.ExecutionInterceptorChain:85 - Creating an interceptor\nchain that will apply interceptors in the following order:\n[software.amazon.awssdk.core.internal.interceptor.HttpChecksumValidationInterceptor@69b2f8e5,\nsoftware.amazon.awssdk.awscore.interceptor.HelpfulUnknownHostExceptionInterceptor@6331250e,\nsoftware.amazon.awssdk.awscore.eventstream.EventStreamInitialRequestInterceptor@a10c1b5,\nsoftware.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor@644abb8f,\nsoftware.amazon.awssdk.services.s3.auth.scheme.internal.S3AuthSchemeInterceptor@1a411233,\nsoftware.amazon.awssdk.services.s3.endpoints.internal.S3ResolveEndpointInterceptor@70325d20,\nsoftware.amazon.awssdk.services.s3.endpoints.internal.S3RequestSetEndpointInterceptor@7c2327fa,\nsoftware.amazon.awssdk.services.s3.internal.handlers.StreamingRequestInterceptor@4d847d32,\nsoftware.amazon.awssdk.services.s3.internal.handlers.CreateBucketInterceptor@5f462e3b,\nsoftware.amazon.awssdk.services.s3.internal.handlers.CreateMultipartUploadRequestInterceptor@3d7fa3ae,\nDebug-level SDK logging 124\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsoftware.amazon.awssdk.services.s3.internal.handlers.DecodeUrlEncodedResponseInterceptor@58065f0c,\nsoftware.amazon.awssdk.services.s3.internal.handlers.GetBucketPolicyInterceptor@3605c4d3,\nsoftware.amazon.awssdk.services.s3.internal.handlers.S3ExpressChecksumInterceptor@585c13de,\nsoftware.amazon.awssdk.services.s3.internal.handlers.AsyncChecksumValidationInterceptor@187eb9a8,\nsoftware.amazon.awssdk.services.s3.internal.handlers.SyncChecksumValidationInterceptor@726a6b94,\nsoftware.amazon.awssdk.services.s3.internal.handlers.EnableTrailingChecksumInterceptor@6ad11a56,\nsoftware.amazon.awssdk.services.s3.internal.handlers.ExceptionTranslationInterceptor@522b2631,\nsoftware.amazon.awssdk.services.s3.internal.handlers.GetObjectInterceptor@3ff57625,\nsoftware.amazon.awssdk.services.s3.internal.handlers.CopySourceInterceptor@1ee29c84,\nsoftware.amazon.awssdk.services.s3.internal.handlers.ObjectMetadataInterceptor@7c8326a4]\nDEBUG s.a.a.u.c.CachedSupplier:85 - (SsoOidcTokenProvider()) Cached value is stale and\nwill be refreshed.", "mimetype": "text/plain", "start_char_idx": 253788, "end_char_idx": 256985, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c1455980-7e31-4bab-af1c-b99b3e2a4625": {"__data__": {"id_": "c1455980-7e31-4bab-af1c-b99b3e2a4625", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4b45aeb3-6ab9-4abf-aece-bcd4bf713aac", "node_type": "1", "metadata": {}, "hash": "a15d8308d23ec182645247f5956d83ab44e30e026579e3c599853a54d9aa6d11", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "80e01c24-441c-4d0c-9825-cb0cbdb97b69", "node_type": "1", "metadata": {}, "hash": "a95d3c1e7187ffff4b61944ae5069823255fdf463e9963d3104914ea1cdd4fc1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "...\nDEBUG s.a.a.c.i.ExecutionInterceptorChain:85 - Creating an interceptor\nchain that will apply interceptors in the following order:\n[software.amazon.awssdk.core.internal.interceptor.HttpChecksumValidationInterceptor@51351f28,\nsoftware.amazon.awssdk.awscore.interceptor.HelpfulUnknownHostExceptionInterceptor@21618fa7,\nsoftware.amazon.awssdk.awscore.eventstream.EventStreamInitialRequestInterceptor@15f2eda3,\nsoftware.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor@34cf294c,\nsoftware.amazon.awssdk.services.sso.auth.scheme.internal.SsoAuthSchemeInterceptor@4d7aaca2,\nsoftware.amazon.awssdk.services.sso.endpoints.internal.SsoResolveEndpointInterceptor@604b1e1d,\nsoftware.amazon.awssdk.services.sso.endpoints.internal.SsoRequestSetEndpointInterceptor@62566842]\n...\nDEBUG s.a.a.request:85 - Sending Request: DefaultSdkHttpFullRequest(httpMethod=GET,\nprotocol=https, host=portal.sso.us-east-1.amazonaws.com, encodedPath=/federation/\ncredentials, headers=[amz-sdk-invocation-id, User-Agent, x-amz-sso_bearer_token],\nqueryParameters=[role_name, account_id])\nDEBUG s.a.a.c.i.h.p.s.SigningStage:85 - Using SelectedAuthScheme: smithy.api#noAuth\nDEBUG s.a.a.h.a.i.c.SdkTlsSocketFactory:366 - Connecting socket to portal.sso.us-\neast-1.amazonaws.com/18.235.195.183:443 with timeout 2000\n...\nDEBUG s.a.a.requestId:85 - Received successful response: 200, Request ID: bb4f40f4-\ne920-4b5c-8648-58f26e7e08cd, Extended Request ID: not available\nDEBUG s.a.a.request:85 - Received successful response: 200, Request ID: bb4f40f4-\ne920-4b5c-8648-58f26e7e08cd, Extended Request ID: not available\nDEBUG s.a.a.u.c.CachedSupplier:85 -\n(software.amazon.awssdk.services.sso.auth.SsoCredentialsProvider@b965857) Successfully\nrefreshed cached value. Next Prefetch Time: 2024-04-25T22:03:10.097Z. Next Stale Time:\n2024-04-25T22:05:30Z\nDEBUG s.a.a.c.i.ExecutionInterceptorChain:85 - Interceptor\n'software.amazon.awssdk.services.s3.endpoints.internal.S3RequestSetEndpointInterceptor@7c2327fa'\nmodified the message with its modifyHttpRequest method.\n...\nDEBUG s.a.a.c.i.h.p.s.SigningStage:85 - Using SelectedAuthScheme: aws.auth#sigv4\nDebug-level SDK logging 125\nAWS SDK for Java 2.x Developer Guide for version 2.x\n...\nDEBUG s.a.a.a.s.Aws4Signer:85 - AWS4 Canonical Request: GET\n...\nDEBUG s.a.a.h.a.a.i.s.DefaultV4RequestSigner:85 - AWS4 String to sign: AWS4-HMAC-SHA256\n20240425T210631Z\n20240425/us-east-1/s3/aws4_request\naafb7784627fa7a49584256cb746279751c48c2076f813259ef767ecce304d64\nDEBUG s.a.a.h.a.i.c.SdkTlsSocketFactory:366 - Connecting socket to s3.us-\neast-1.amazonaws.com/52.217.41.86:443 with timeout 2000\n...\nThe following log4j2.xml file configures the previous output.\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnable wire logging\nIt can be useful to see the exact requests and responses that the SDK for Java 2.x sends and\nreceives. If you need access to this information, you can temporarily enable it by adding the\nnecessary configuration depending on the HTTP client the service client uses.\nBy default, synchronous service clients, such as the S3Client, use an underlying Apache HttpClient,\nand asynchronous service clients, such as the S3AsyncClient, use a Netty non-blocking HTTP client.", "mimetype": "text/plain", "start_char_idx": 256986, "end_char_idx": 260465, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "80e01c24-441c-4d0c-9825-cb0cbdb97b69": {"__data__": {"id_": "80e01c24-441c-4d0c-9825-cb0cbdb97b69", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c1455980-7e31-4bab-af1c-b99b3e2a4625", "node_type": "1", "metadata": {}, "hash": "a6c7ff7c184fd1e3b464f6d9b54069e8fc6c630a98f1b638c3735d4522f8a891", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "10c780ae-9a03-45b8-8e70-41cdf7ba1af7", "node_type": "1", "metadata": {}, "hash": "589db3adab3f8bba91d57bac43e1248b54023489329d93646dc7cf6f411b7e0b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\n\n\n\n\n\n\n\n\n\n\n\n\nEnable wire logging\nIt can be useful to see the exact requests and responses that the SDK for Java 2.x sends and\nreceives. If you need access to this information, you can temporarily enable it by adding the\nnecessary configuration depending on the HTTP client the service client uses.\nBy default, synchronous service clients, such as the S3Client, use an underlying Apache HttpClient,\nand asynchronous service clients, such as the S3AsyncClient, use a Netty non-blocking HTTP client.\nHere is a breakdown of HTTP clients you can use for the two categories of service clients:\nEnable wire logging 126\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSynchronous HTTP Clients Asynchronous HTTP Clients\nApacheHttpClient (default) NettyNioAsyncHttpClient (default)\nUrlConnectionHttpClient AwsCrtAsyncHttpClient\nAwsCrtHttpClient\nConsult the appropriate tab below for configuration settings you need to add depending on the\nunderlying HTTP client.\nWarning\nWe recommend you only use wire logging for debugging purposes. Disable it in your\nproduction environments because it can log sensitive data. It logs the full request or\nresponse without encryption, even for an HTTPS call. For large requests (e.g., to upload a\nfile to Amazon S3) or responses, verbose wire logging can also significantly impact your\napplication\u2019s performance.\nApacheHttpClient\nAdd the \"org.apache.http.wire\" logger to the log4j2.xml configuration file and set the level to\n\"DEBUG\".\nThe following log4j2.xml file turns on full wire logging for the Apache HttpClient.\n\n\n\n\n\n\n\n\n\n\n\n\nEnable wire logging 127\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\n\nAn additional Maven dependency on the log4j-1.2-api artifact is required for wire logging\nwith Apache since it uses 1.2 under the hood.\nThe full set of Maven dependencies for log4j 2, including wire logging for the Apache HTTP\nclient are shown in the following build file snippets.\nMaven\n...\n\n...\n\n\norg.apache.logging.log4j\nlog4j-bom\nVERSION\npom\nimport\n\n\n\n...\n\n\norg.apache.logging.log4j\nlog4j-slf4j2-impl\n\n\n\norg.apache.logging.log4j\nlog4j-1.2-api\n\n...\nGradle\u2013Kotlin DSL\n...\nEnable wire logging 128\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndependencies {\n...\nimplementation(platform(\"org.apache.logging.log4j:log4j-bom:VERSION\"))\nimplementation(\"org.apache.logging.log4j:log4j-slf4j2-impl\")\nimplementation(\"org.apache.logging.log4j:log4j-1.2-api\")\n}\n...\nUse 2.20.0 for the minimum version of the log4j-bom artifact. For the latest version, use the\nversion published to Maven central. Replace VERSION with version you'll use.", "mimetype": "text/plain", "start_char_idx": 259655, "end_char_idx": 263445, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "10c780ae-9a03-45b8-8e70-41cdf7ba1af7": {"__data__": {"id_": "10c780ae-9a03-45b8-8e70-41cdf7ba1af7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "80e01c24-441c-4d0c-9825-cb0cbdb97b69", "node_type": "1", "metadata": {}, "hash": "a95d3c1e7187ffff4b61944ae5069823255fdf463e9963d3104914ea1cdd4fc1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bdcf5616-4ed3-4400-b658-e90ebbcee24f", "node_type": "1", "metadata": {}, "hash": "5b80323c248ff10e184c581845414ba36eda919354b776aa9f97e0d5acf82578", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "For the latest version, use the\nversion published to Maven central. Replace VERSION with version you'll use.\nUrlConnectionHttpClient\nTo log details for service clients that use the UrlConnectionHttpClient, first create a\nlogging.properties file with the following contents:\nhandlers=java.util.logging.ConsoleHandler\njava.util.logging.ConsoleHandler.level=FINEST\nsun.net.www.protocol.http.HttpURLConnection.level=ALL\nSet the following JVM system property with the full path of the logging.properties:\n-Djava.util.logging.config.file=/full/path/to/logging.properties\nThis configuration will log the only the headers of the request and response, for example:\n FINE: sun.net.www.MessageHeader@35a9782c11 pairs: {GET /fileuploadtest\nHTTP/1.1: null}{amz-sdk-invocation-id: 5f7e707e-4ac5-bef5-ba62-00d71034ffdc}\n{amz-sdk-request: attempt=1; max=4}{Authorization: AWS4-HMAC-SHA256\nCredential=/20220927/us-east-1/s3/aws4_request, SignedHeaders=amz-sdk-\ninvocation-id;amz-sdk-request;host;x-amz-content-sha256;x-amz-date;x-amz-te,\nSignature=e367fa0bc217a6a65675bb743e1280cf12fbe8d566196a816d948fdf0b42ca1a}{User-\nAgent: aws-sdk-java/2.17.230 Mac_OS_X/12.5 OpenJDK_64-Bit_Server_VM/25.332-b08\nJava/1.8.0_332 vendor/Amazon.com_Inc. io/sync http/UrlConnection cfg/retry-mode/\nlegacy}{x-amz-content-sha256: UNSIGNED-PAYLOAD}{X-Amz-Date: 20220927T133955Z}{x-amz-\nte: append-md5}{Host: tkhill-test1.s3.amazonaws.com}{Accept: text/html, image/gif,\nimage/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}\n FINE: sun.net.www.MessageHeader@70a36a6611 pairs: {null: HTTP/1.1\n200 OK}{x-amz-id-2: sAFeZDOKdUMsBbkdjyDZw7P0oocb4C9KbiuzfJ6TWKQsGXHM/\ndFuOvr2tUb7Y1wEHGdJ3DSIxq0=}{x-amz-request-id: P9QW9SMZ97FKZ9X7}{Date: Tue,\n27 Sep 2022 13:39:57 GMT}{Last-Modified: Tue, 13 Sep 2022 14:38:12 GMT}{ETag:\nEnable wire logging 129\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"2cbe5ad4a064cedec33b452bebf48032\"}{x-amz-transfer-encoding: append-md5}{Accept-\nRanges: bytes}{Content-Type: text/plain}{Server: AmazonS3}{Content-Length: 67}\nTo see the request/response bodies, add -Djavax.net.debug=all to the JVM properties.\nThis additional property logs a great deal of information, including all SSL information.\nWithin the log console or log file, search for \"GET\" or \"POST\" to quickly go to the section\nof the log containing actual requests and responses. Search for \"Plaintext before\nENCRYPTION\" for requests and \"Plaintext after DECRYPTION\" for responses to see the\nfull text of the headers and bodies.\nNettyNioAsyncHttpClient\nIf your asynchronous service client uses the default NettyNioAsyncHttpClient, add two\nadditional loggers to your log4j2.xml file to log HTTP headers and request/response bodies.", "mimetype": "text/plain", "start_char_idx": 263337, "end_char_idx": 266050, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bdcf5616-4ed3-4400-b658-e90ebbcee24f": {"__data__": {"id_": "bdcf5616-4ed3-4400-b658-e90ebbcee24f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "10c780ae-9a03-45b8-8e70-41cdf7ba1af7", "node_type": "1", "metadata": {}, "hash": "589db3adab3f8bba91d57bac43e1248b54023489329d93646dc7cf6f411b7e0b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "82dafc99-0d89-4ab4-9edc-b5b9574d22cf", "node_type": "1", "metadata": {}, "hash": "d40820a3ab63db7377b176397d951f2882a8af23b4baf53098a36ac0058d23d3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This additional property logs a great deal of information, including all SSL information.\nWithin the log console or log file, search for \"GET\" or \"POST\" to quickly go to the section\nof the log containing actual requests and responses. Search for \"Plaintext before\nENCRYPTION\" for requests and \"Plaintext after DECRYPTION\" for responses to see the\nfull text of the headers and bodies.\nNettyNioAsyncHttpClient\nIf your asynchronous service client uses the default NettyNioAsyncHttpClient, add two\nadditional loggers to your log4j2.xml file to log HTTP headers and request/response bodies.\n\n\nHere is a complete log4j2.xml example:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThese settings log all header details and request/response bodies.\nEnable wire logging 130\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAwsCrtAsyncHttpClient/AwsCrtHttpClient\nIf you have configured your service client to use an instance of an AWS CRT-based HTTP client,\nyou can log details by setting JVM system properties or programmatically.\nLog to a file at \"Debug\" level\nUsing system properties: Programmatically:\n-Daws.crt.log.leve import software.amazon.awssdk.crt.Log;\nl=Trace\n-Daws.crt.log.des // Execute this statement before constructing the\ntination=File SDK service client.\n-Daws.crt.log.fil Log.initLoggingToFile(Log.LogLevel.Trace,\nename= \"\");\nLog to the console at \"Debug\" level\nUsing system properties: Programmatically:\n-Daws.crt.log.leve import software.amazon.awssdk.crt.Log;\nl=Trace\n-Daws.crt.log.des // Execute this statement before constructing the\ntination=Stdout SDK service client.\nLog.initLoggingToStdout(Log.LogLevel.Trace);\nFor security reasons, at the \"Trace\" level the AWS CRT-based HTTP clients log only response\nheaders. Request headers, request bodies, and response bodies are not logged.\nSet the JVM TTL for DNS name lookups\nThe Java virtual machine (JVM) caches DNS name lookups. When the JVM resolves a hostname\nto an IP address, it caches the IP address for a specified period of time, known as the time-to-live\n(TTL).\nBecause AWS resources use DNS name entries that occasionally change, we recommend that\nyou configure your JVM with a TTL value of 5 seconds. This ensures that when a resource\u2019s IP\nSet the JVM TTL for DNS name lookups 131\nAWS SDK for Java 2.x Developer Guide for version 2.x\naddress changes, your application will be able to receive and use the resource\u2019s new IP address by\nrequerying the DNS.\nOn some Java configurations, the JVM default TTL is set so that it will never refresh DNS entries\nuntil the JVM is restarted. Thus, if the IP address for an AWS resource changes while your\napplication is still running, it won\u2019t be able to use that resource until you manually restart the JVM\nand the cached IP information is refreshed. In this case, it\u2019s crucial to set the JVM\u2019s TTL so that it\nwill periodically refresh its cached IP information.\nHow to set the JVM TTL\nTo modify the JVM\u2019s TTL, set the networkaddress.cache.ttl security property value, set\nthe networkaddress.cache.ttl property in the $JAVA_HOME/jre/lib/security/\njava.security file for Java 8 or $JAVA_HOME/conf/security/java.security file for Java\n11 or higher.\nThe following is a snippet from a java.security file that shows the TTL cache set to 5 seconds.\n#\n# This is the \"master security properties file\".", "mimetype": "text/plain", "start_char_idx": 265465, "end_char_idx": 269439, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "82dafc99-0d89-4ab4-9edc-b5b9574d22cf": {"__data__": {"id_": "82dafc99-0d89-4ab4-9edc-b5b9574d22cf", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bdcf5616-4ed3-4400-b658-e90ebbcee24f", "node_type": "1", "metadata": {}, "hash": "5b80323c248ff10e184c581845414ba36eda919354b776aa9f97e0d5acf82578", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8b887623-fe58-4988-8d05-f6537d3bc072", "node_type": "1", "metadata": {}, "hash": "cd3f152a450ebf913c1764d07b29adbcccc4020a6033a720a26fe3bea5eb6a8e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "On some Java configurations, the JVM default TTL is set so that it will never refresh DNS entries\nuntil the JVM is restarted. Thus, if the IP address for an AWS resource changes while your\napplication is still running, it won\u2019t be able to use that resource until you manually restart the JVM\nand the cached IP information is refreshed. In this case, it\u2019s crucial to set the JVM\u2019s TTL so that it\nwill periodically refresh its cached IP information.\nHow to set the JVM TTL\nTo modify the JVM\u2019s TTL, set the networkaddress.cache.ttl security property value, set\nthe networkaddress.cache.ttl property in the $JAVA_HOME/jre/lib/security/\njava.security file for Java 8 or $JAVA_HOME/conf/security/java.security file for Java\n11 or higher.\nThe following is a snippet from a java.security file that shows the TTL cache set to 5 seconds.\n#\n# This is the \"master security properties file\".\n#\n# An alternate java.security properties file may be specified\n...\n# The Java-level namelookup cache policy for successful lookups:\n#\n# any negative value: caching forever\n# any positive value: the number of seconds to cache an address for\n# zero: do not cache\n...\nnetworkaddress.cache.ttl=5\n...\nAll applications that run on the JVM represented by the$JAVA_HOME environment variable use this\nsetting.\nBest practices for AWS SDK for Java 2.x\nThis section lists best practices for using the SDK for Java 2.x.\nTopics\nHow to set the JVM TTL 132\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Reuse an SDK client, if possible\n\u2022 Close input streams from client operations\n\u2022 Tune HTTP configurations based on performance tests\n\u2022 Use OpenSSL for the Netty-based HTTP client\n\u2022 Configure API timeouts\n\u2022 Use metrics\nReuse an SDK client, if possible\nEach SDK client maintains its own HTTP connection pool. A connection that already exists in the\npool can be reused by a new request to cut down the time to establish a new connection. We\nrecommend sharing a single instance of the client to avoid the overhead of having too many\nconnection pools that aren't used effectively. All SDK clients are thread safe.\nIf you don't want to share a client instance, call close() on the instance to release the resources\nwhen the client is not needed.\nClose input streams from client operations\nFor streaming operations such as S3Client#getObject, if you are working with\nResponseInputStream directly, we recommend that you do the following:\n\u2022 Read all the data from the input stream as soon as possible.\n\u2022 Close the input stream as soon as possible.\nWe make these recommendations because the input stream is a direct stream of data from the\nHTTP connection and the underlying HTTP connection can't be reused until all data from the\nstream has been read and the stream is closed. If these rules are not followed, the client can run\nout of resources by allocating too many open, but unused, HTTP connections.\nTune HTTP configurations based on performance tests\nThe SDK provides a set of default http configurations that apply to general use cases. We\nrecommend that customers tune HTTP configurations for their applications based on their use\ncases.\nReuse an SDK client 133\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAs a good starting point, the SDK offers a smart configuration defaults feature. This feature is\navailable starting with version 2.17.102. You choose a mode depending on your use case, which\nprovides sensible configuration values.\nUse OpenSSL for the Netty-based HTTP client\nBy default, the SDK's NettyNioAsyncHttpClient uses the JDK's default SSL implementation\nas the SslProvider. Our testing found that OpenSSL performs better than JDK's default\nimplementation. The Netty community also recommends using OpenSSL.\nTo use OpenSSL, add netty-tcnative to your dependencies. For configuration details, see the\nNetty project documentation.\nAfter you have netty-tcnative configured for your project, the NettyNioAsyncHttpClient\ninstance will automatically select OpenSSL. Alternatively, you can set the SslProvider explicitly\nusing the NettyNioAsyncHttpClient builder as shown in the following snippet.\nNettyNioAsyncHttpClient.builder()\n.sslProvider(SslProvider.OPENSSL)\n.build();\nConfigure API timeouts\nThe SDK provides default values for some timeout options, such as connection timeout and socket\ntimeouts, but not for API call timeouts or individual API call attempt timeouts. It is a good practice\nto set timeouts for both the individual attempts and the entire request. This will ensure your\napplication fails fast in an optimal way when there are transient issues that could cause request\nattempts to take longer to complete or fatal network issues.", "mimetype": "text/plain", "start_char_idx": 268561, "end_char_idx": 273202, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8b887623-fe58-4988-8d05-f6537d3bc072": {"__data__": {"id_": "8b887623-fe58-4988-8d05-f6537d3bc072", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "82dafc99-0d89-4ab4-9edc-b5b9574d22cf", "node_type": "1", "metadata": {}, "hash": "d40820a3ab63db7377b176397d951f2882a8af23b4baf53098a36ac0058d23d3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f94e23dc-4e95-49e5-91eb-33b962f86837", "node_type": "1", "metadata": {}, "hash": "d4cf05c5bb303746d3023ca9653887dc2be86074067668f727331e4f93ba6496", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "To use OpenSSL, add netty-tcnative to your dependencies. For configuration details, see the\nNetty project documentation.\nAfter you have netty-tcnative configured for your project, the NettyNioAsyncHttpClient\ninstance will automatically select OpenSSL. Alternatively, you can set the SslProvider explicitly\nusing the NettyNioAsyncHttpClient builder as shown in the following snippet.\nNettyNioAsyncHttpClient.builder()\n.sslProvider(SslProvider.OPENSSL)\n.build();\nConfigure API timeouts\nThe SDK provides default values for some timeout options, such as connection timeout and socket\ntimeouts, but not for API call timeouts or individual API call attempt timeouts. It is a good practice\nto set timeouts for both the individual attempts and the entire request. This will ensure your\napplication fails fast in an optimal way when there are transient issues that could cause request\nattempts to take longer to complete or fatal network issues.\nYou can configure timeouts for all requests made by a service clients using\nClientOverrideConfiguration#apiCallAttemptTimeout and\nClientOverrideConfiguration#apiCallTimeout.\nThe following example shows the configuration of an Amazon S3 client with custom timeout\nvalues.\nS3Client.builder()\n.overrideConfiguration(\nb -> b.apiCallTimeout(Duration.ofSeconds())\n.apiCallAttemptTimeout(Duration.ofMillis()))\nUse OpenSSL for Netty 134\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\napiCallAttemptTimeout\nThis setting sets the amount of time for a single HTTP attempt, after which the API call can be\nretried.\napiCallTimeout\nThe value for this property configures the amount of time for the entire execution, including all\nretry attempts.\nAs an alternative to setting these timeout values on the service client, you\ncan use RequestOverrideConfiguration#apiCallTimeout() and\nRequestOverrideConfiguration#apiCallAttemptTimeout() to configure a single request .\nThe following example configures a single listBuckets request with custom timeout values.\ns3Client.listBuckets(lbr -> lbr.overrideConfiguration(\nb -> b.apiCallTimeout(Duration.ofSeconds())\n.apiCallAttemptTimeout(Duration.ofMillis())));\nWhen you use these properties together, you set a hard limit on the total time spent on all\nattempts across retries. You also set an individual HTTP request to fail fast on a slow request.\nUse metrics\nThe SDK for Java can collect metrics for the service clients in your application. You can use these\nmetrics to identify performance issues, review overall usage trends, review service client exceptions\nreturned, or to dig in to understand a particular issue.\nWe recommend that you collect metrics, then analyze the Amazon CloudWatch Logs, in order to\ngain a deeper understanding of your application's performance.\nTroubleshooting FAQs\nAs you use the AWS SDK for Java 2.x in your applications, you might encounter the runtime errors\nlisted in this topic. Use the suggestions here to help you uncover the root cause and resolve the\nerror.\nUse metrics 135\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHow do I fix \"java.net.SocketException: Connection reset\" or\n\"server failed to complete the response\" error?\nA connection reset error indicates that your host, the AWS service, or any intermediary party (for\nexample, a NAT gateway, a proxy, a load balancer) closed the connection before the request was\ncomplete. Because there are many causes, finding a solution requires that you know why the\nconnection is being closed. The following items commonly cause a connection to be closed.\n\u2022 The connection is inactive. This is common for streaming operations, where data is not being\nwritten to or from the wire for a period of time, so an intermediary party detects the connection\nas dead and closes it. To prevent this, be sure your application actively downloads or uploads\ndata.\n\u2022 You've closed the HTTP or SDK client. Be sure not to close resources while they are in use.\n\u2022 A misconfigured proxy. Try to bypass any proxies that you've configured to see if it fixes the\nproblem. If this fixes the issue, the proxy is closing your connection for some reason. Research\nyour specific proxy to determine why it's closing the connection.\nIf you cannot identify the problem, try running a TCP dump for an affected connection at the client\nedge of your network (for example, after any proxies that you control).\nIf you see that the AWS endpoint is sending a TCP RST (reset), contact the affected service to see if\nthey can determine why the reset is occurring. Be prepared to provide request IDs and timestamps\nof when the issue occurred. The AWS support team might also benefit from wire logs that show\nexactly what bytes your application is sending and receiving and when.\nHow do I fix \"connection timeout\"?", "mimetype": "text/plain", "start_char_idx": 272266, "end_char_idx": 277071, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f94e23dc-4e95-49e5-91eb-33b962f86837": {"__data__": {"id_": "f94e23dc-4e95-49e5-91eb-33b962f86837", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8b887623-fe58-4988-8d05-f6537d3bc072", "node_type": "1", "metadata": {}, "hash": "cd3f152a450ebf913c1764d07b29adbcccc4020a6033a720a26fe3bea5eb6a8e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "685c52f8-0af2-443f-b714-bbcd3a0b8648", "node_type": "1", "metadata": {}, "hash": "3983f7879cf7ea8251cefb3e6329ab4507da6cc6d85d8e527da3c84d60e7dfd2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 You've closed the HTTP or SDK client. Be sure not to close resources while they are in use.\n\u2022 A misconfigured proxy. Try to bypass any proxies that you've configured to see if it fixes the\nproblem. If this fixes the issue, the proxy is closing your connection for some reason. Research\nyour specific proxy to determine why it's closing the connection.\nIf you cannot identify the problem, try running a TCP dump for an affected connection at the client\nedge of your network (for example, after any proxies that you control).\nIf you see that the AWS endpoint is sending a TCP RST (reset), contact the affected service to see if\nthey can determine why the reset is occurring. Be prepared to provide request IDs and timestamps\nof when the issue occurred. The AWS support team might also benefit from wire logs that show\nexactly what bytes your application is sending and receiving and when.\nHow do I fix \"connection timeout\"?\nA connection timeout error indicates that your host, the AWS service, or any intermediary party (for\nexample, a NAT gateway, a proxy, a load balancer) failed to establish a new connection with the\nserver within the configured connection timeout. The following items describe common causes of\nthis issue.\n\u2022 The configured connection timeout is too low. By default, the connection timeout is 2 seconds\nin the AWS SDK for Java 2.x. If you set the connection timeout too low, you may get this error.\nThe recommended connection timeout is 1 second if you make only in-region calls and 3 seconds\nif you make cross-region requests.\nConnection reset 136\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 A misconfigured proxy. Try to bypass any proxies that you configured to see if it fixes the\nproblem. If this fixes the issue, the proxy is the reason for the connection timeout. Research your\nspecific proxy to determine why that is happening\nIf you cannot identify the problem, try running a TCP dump for an affected connection at the client\nedge of your network (for example, after any proxies that you control) to investigate any network\nissue.\nHow do I fix \"java.net.SocketTimeoutException: Read timed out\"?\nA read timed out error indicates that the JVM attempted to read data from the underlying\noperating system, but data was not returned within the time configured via the SDK. This error\ncan occur if the operating system, the AWS service, or any intermediary party (for example, a\nNAT gateway, a proxy, a load balancers) fails to send data within the time expected by the JVM.\nBecause there are many causes, finding a solution requires that you know why the data is not being\nreturned.\nTry running a TCP dump for an affected connection at the client edge of your network (for\nexample, after any proxies that you control).\nIf you see that the AWS endpoint is sending a TCP RST (reset), contact the affected service. Be\nprepared to provide request IDs and timestamps of when the issue occurred. The AWS support\nteam might also benefit from wire logs that show exactly what bytes your application is sending\nand receiving and when.\nHow do I fix \"Unable to execute HTTP request: Timeout waiting for\nconnection from pool\" error?\nThis error indicates that a request cannot get a connection from the pool within the specified\nmaximum time. To troubleshoot the issue, we recommend that you enable SDK client-side metrics\nto publish metrics to Amazon CloudWatch. The HTTP metrics can help narrow down the root cause.\nThe following items describe common causes of this error.\n\u2022 Connection leak. You can investigate this by checking LeasedConcurrency ,\nAvailableConcurrency, and MaxConcurrency metrics. If LeasedConcurrency increases\nuntil it reaches MaxConcurrency but never decreases, there may be a connection leak. A\ncommon cause of a leak is because a streaming operation\u2014such as a S3 getObject method\u2014\nis not closed. We recommend that your application read all data from the input stream as soon\nRead timed out 137\nAWS SDK for Java 2.x Developer Guide for version 2.x\nas possible and close the input stream afterwards. The following chart shows what SDK metrics\nmight look like for connection leak.\n\u2022 Connection pool starvation. This can happen if your request rate is too high and the connection\npool size that has been configured cannot meet the request demand. The default connection\npool size is 50, and when the connections in the pool reach the maximum, the HTTP client\nqueues incoming requests until connections become available. The following chart shows what\nSDK metrics might look like for connection pool starvation.\nConnection pool timeout 138\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo mitigate this issue, consider taking any of the following actions.\n\u2022 Increase the connection pool size,\n\u2022 Increase acquire timeout.\n\u2022 Slow the request rate.", "mimetype": "text/plain", "start_char_idx": 276148, "end_char_idx": 280944, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "685c52f8-0af2-443f-b714-bbcd3a0b8648": {"__data__": {"id_": "685c52f8-0af2-443f-b714-bbcd3a0b8648", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f94e23dc-4e95-49e5-91eb-33b962f86837", "node_type": "1", "metadata": {}, "hash": "d4cf05c5bb303746d3023ca9653887dc2be86074067668f727331e4f93ba6496", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "58aae5da-f430-4b30-8b7f-19f23c5b30ad", "node_type": "1", "metadata": {}, "hash": "39e07d5099a765126f1253f130976c40b5088544397a2e7bd7f4f07328a3bace", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "We recommend that your application read all data from the input stream as soon\nRead timed out 137\nAWS SDK for Java 2.x Developer Guide for version 2.x\nas possible and close the input stream afterwards. The following chart shows what SDK metrics\nmight look like for connection leak.\n\u2022 Connection pool starvation. This can happen if your request rate is too high and the connection\npool size that has been configured cannot meet the request demand. The default connection\npool size is 50, and when the connections in the pool reach the maximum, the HTTP client\nqueues incoming requests until connections become available. The following chart shows what\nSDK metrics might look like for connection pool starvation.\nConnection pool timeout 138\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo mitigate this issue, consider taking any of the following actions.\n\u2022 Increase the connection pool size,\n\u2022 Increase acquire timeout.\n\u2022 Slow the request rate.\nBy increasing the maximum number of connections, client throughput can increase (unless the\nnetwork interface is already fully utilized). However, you can eventually hit operation system\nlimitations on the number of file descriptors used by the process. If you already fully use your\nnetwork interface or cannot further increase your connection count, try increasing the acquire\ntimeout. With the increase, you gain extra time for requests to acquire a connection before\ntiming out. If the connections don't free up, the subsequent requests will still timeout.\nIf you are unable to fix the issue by using the first two mechanisms, slow the request rate by\ntrying the following options.\n\u2022 Smooth out your requests so that large traffic bursts don't overload the client.\n\u2022 Be more efficient with calls to AWS services.\n\u2022 Increase the number of hosts sending requests.\nConnection pool timeout 139\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 I/O Threads are too busy. This only applies if you are using an asynchronous SDK client with\nNettyNioAsyncHttpClient. If the AvailableConcurrency metric is not low\u2014indicating\nthat connections are available in the pool\u2014but ConcurrencyAcquireDuration is high, it\nmight be because I/O threads are not able to handle the requests. Be sure you are not passing\nRunnable:run as a future completion executor and performing time-consuming task in the\nresponse future completion chain since this can block an I/O thread. If that is not the case,\nconsider increasing the number of I/O threads by using the eventLoopGroupBuilder method.\nFor reference, the default number of I/O threads for a NettyNioAsyncHttpClient instance is\ntwice the number of CPU cores of the host.\n\u2022 High TLS handshake latency. If your AvailableConcurrency metric is near 0 and\nLeasedConcurrency is lower than MaxConcurrency, it might be because the TLS handshake\nlatency is high. The following chart shows what SDK metrics might look like for high TLS\nhandshake latency.\nFor HTTP clients offered by the Java SDK that are not based on CRT, try enabling TLS logs to\ntroubleshoot TLS issues. For the AWS CRT-based HTTP client, try enabling AWS CRT logs. If you\nsee that the AWS endpoint seems to take a long time to perform a TLS handshake, you should\ncontact the affected service.\nConnection pool timeout 140\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHow do I fix a NoClassDefFoundError, NoSuchMethodError or\nNoSuchFieldError?\nA NoClassDefFoundError indicates that a class could not be loaded at runtime. The two most\ncommon causes for this error are:\n\u2022 the class does not exist in the classpath because the JAR is missing or the wrong version of the\nJAR is on the classpath.\n\u2022 the class failed to load because its static initializer threw an exception.\nSimilarly, NoSuchMethodErrors and NoSuchFieldErrors typically result from a mismatched\nJAR version. We recommend that you perform the following steps.\n1. Check your dependencies to make sure that you're using the same version of all SDK jars. The\nmost common reason that a class, method, or field cannot be found is when you upgrade to a\nnew client version but you continue to use an old 'shared' SDK dependency version. The new\nclient version might attempt to use classes that exist only in newer 'shared' SDK dependencies.\nTry running mvn dependency:tree or gradle dependencies (for Gradle) to verify that the\nSDK library versions all match. To avoid this issue completely in the future, we recommend using\nBOM (Bill of Materials) to manage SDK module versions.\nThe following example shows you an example of mixed SDK versions.", "mimetype": "text/plain", "start_char_idx": 279993, "end_char_idx": 284548, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "58aae5da-f430-4b30-8b7f-19f23c5b30ad": {"__data__": {"id_": "58aae5da-f430-4b30-8b7f-19f23c5b30ad", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "685c52f8-0af2-443f-b714-bbcd3a0b8648", "node_type": "1", "metadata": {}, "hash": "3983f7879cf7ea8251cefb3e6329ab4507da6cc6d85d8e527da3c84d60e7dfd2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c00b08c4-8091-4f8e-b987-49fcc82fbbba", "node_type": "1", "metadata": {}, "hash": "1867b9a8dab61d940d1a48bb0c1cf5183645cb4156121b98e274a4a0bfaa6964", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 the class failed to load because its static initializer threw an exception.\nSimilarly, NoSuchMethodErrors and NoSuchFieldErrors typically result from a mismatched\nJAR version. We recommend that you perform the following steps.\n1. Check your dependencies to make sure that you're using the same version of all SDK jars. The\nmost common reason that a class, method, or field cannot be found is when you upgrade to a\nnew client version but you continue to use an old 'shared' SDK dependency version. The new\nclient version might attempt to use classes that exist only in newer 'shared' SDK dependencies.\nTry running mvn dependency:tree or gradle dependencies (for Gradle) to verify that the\nSDK library versions all match. To avoid this issue completely in the future, we recommend using\nBOM (Bill of Materials) to manage SDK module versions.\nThe following example shows you an example of mixed SDK versions.\n[INFO] +- software.amazon.awssdk:dynamodb:jar:2.20.00:compile\n[INFO] | +- software.amazon.awssdk:aws-core:jar:2.13.19:compile\n[INFO] +- software.amazon.awssdk:netty-nio-client:jar:2.20.00:compile\nThe version of dynamodb is 2.20.00 and the version of aws-core is 2.13.19. The aws-core\nartifact version should also be 2.20.00.\n2. Check statements early in your logs to see if a class is failing to load because of a static\ninitialization failure. The first time the class fails to load, it may throw a different, more useful\nexception that specifies why the class cannot be loaded. This potentially useful exception occurs\nonly once, so later log statements will only report that the class is not found.\n3. Check your deployment process to make sure that it actually deploys required JAR files along\nwith your application. It's possible that you're building with the correct version, but the process\nthat creates the classpath for your application is excluding a required dependency.\nClasspath errors 141\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHow do I fix a \"SignatureDoesNotMatch\" error or \"The request\nsignature we calculated does not match the signature you provided\"\nerror?\nA SignatureDoesNotMatch error indicates that the signature generated by the AWS SDK for\nJava and the signature generated by the AWS service do not match. The following items describe\npotential causes.\n\u2022 A proxy or intermediary party modifies the request. For example, a proxy or load balancer might\nmodify a header, path or query string that was signed by the SDK.\n\u2022 The service and SDK differ in the way they encode the request when each generates the string to\nsign.\nTo debug this issue, we recommend that you enable debug logging for the SDK. Try to reproduce\nthe error and find the canonical request that the SDK generated. In the log, the canonical request\nis labeled with AWS4 Canonical Request: ... and the string to sign is labeled AWS4 String\nto sign: ... .\nIf you cannot enable debugging\u2014for example, because it's only reproducible in production\u2014add\nlogic to your application that logs information about the request when the error occurs. You can\nthen use that information to try to replicate the error outside of production in an integration test\nwith debug logging enabled.\nAfter you have collected the canonical request and string to sign, compare them against the AWS\nSignature Version 4 specification to determine if there are any issues in the way the SDK generated\nthe string to sign. If something seems wrong, you can create a GitHub bug report to the AWS SDK\nfor Java.\nIf nothing appears wrong, you can compare the SDK's string to sign with the string to sign that\nsome AWS services return as part of the failure response (Amazon S3, for example) . If this isn't\navailable, you should contact the affected service to see what canonical request and string to sign\nthey generated for comparison. These comparisons can help to identify intermediary parties that\nmight have modified the request or encoding differences between the service and client.\nFor more background information about signing requests, see Signing AWS API requests in the\nAWS Identity and Access Management User Guide.", "mimetype": "text/plain", "start_char_idx": 283641, "end_char_idx": 287744, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c00b08c4-8091-4f8e-b987-49fcc82fbbba": {"__data__": {"id_": "c00b08c4-8091-4f8e-b987-49fcc82fbbba", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "58aae5da-f430-4b30-8b7f-19f23c5b30ad", "node_type": "1", "metadata": {}, "hash": "39e07d5099a765126f1253f130976c40b5088544397a2e7bd7f4f07328a3bace", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "422f1b1e-f734-4c25-96a6-a2fa099e2223", "node_type": "1", "metadata": {}, "hash": "41b0c13c10637dc1fdb7e241c135ed0cc4382cf30317a7a6b2025a0e84c66946", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "After you have collected the canonical request and string to sign, compare them against the AWS\nSignature Version 4 specification to determine if there are any issues in the way the SDK generated\nthe string to sign. If something seems wrong, you can create a GitHub bug report to the AWS SDK\nfor Java.\nIf nothing appears wrong, you can compare the SDK's string to sign with the string to sign that\nsome AWS services return as part of the failure response (Amazon S3, for example) . If this isn't\navailable, you should contact the affected service to see what canonical request and string to sign\nthey generated for comparison. These comparisons can help to identify intermediary parties that\nmight have modified the request or encoding differences between the service and client.\nFor more background information about signing requests, see Signing AWS API requests in the\nAWS Identity and Access Management User Guide.\nSignature errors 142\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExample of a canonical request\nPUT\n/Example-Bucket/Example-Object\npartNumber=19&uploadId=string\namz-sdk-invocation-id:f8c2799d-367c-f024-e8fa-6ad6d0a1afb9\namz-sdk-request:attempt=1; max=4\ncontent-encoding:aws-chunked\ncontent-length:51\ncontent-type:application/octet-stream\nhost:xxxxx\nx-amz-content-sha256:STREAMING-UNSIGNED-PAYLOAD-TRAILER\nx-amz-date:20240308T034733Z\nx-amz-decoded-content-length:10\nx-amz-sdk-checksum-algorithm:CRC32\nx-amz-trailer:x-amz-checksum-crc32\nExample of a string to sign\nAWS4-HMAC-SHA256\n20240308T034435Z\n20240308/us-east-1/s3/aws4_request\n5f20a7604b1ef65dd89c333fd66736fdef9578d11a4f5d22d289597c387dc713\nHow do I fix \"java.lang.IllegalStateException: Connection pool\nshut down\" error?\nThis error indicates the underlying Apache HTTP connection pool was closed. The following items\ndescribe potential causes.\n\u2022 The SDK client was closed prematurely. The SDK only closes the connection pool when the\nassociated client is closed. Be sure not to close resources while they are in use.\n\u2022 A java.lang.Error was thrown. Errors such as OutOfMemoryError cause an Apache HTTP\nconnection pool to shut down. Examine your logs for error stack traces. Also review your code for\nplaces where it catches Throwables or Errors but swallows the output that prevents the error\nfrom surfacing. If your code does not report errors, rewrite the code so information is logged.\nThe logged information helps determine the root cause of the error.\n\u2022 You attempted to use the credentials provider returned from\nDefaultCredentialsProvider#create() after it was closed.\nConnection pool shut down 143\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDefaultCredentialsProvider#create returns a singleton instance, so if it's closed and your\ncode calls the resolveCredentials method, the exception is thrown after cached credentials\n(or token) expire.\nCheck your code for places where the DefaultCredentialsProvider is closed, as shown in\nthe following examples.\n\u2022 The singleton instance is closed by calling DefaultCredentialsProvider#close().\nDefaultCredentialsProvider defaultCredentialsProvider =\nDefaultCredentialsProvider.create(); // Singleton instance returned.\nAwsCredentials credentials = defaultCredentialsProvider.resolveCredentials();\n// Make calls to AWS services.\ndefaultCredentialsProvider.close(); // Explicit close.\n// Make calls to AWS services.\n// After the credentials expire, either of the following calls eventually results\nin a \"Connection pool shut down\" exception.\ncredentials = defaultCredentialsProvider.resolveCredentials();\n// Or\ncredentials = DefaultCredentialsProvider.create().resolveCredentials();\n\u2022 Invoke DefaultCredentialsProvider#create() in a try-with-resources block.\ntry (DefaultCredentialsProvider defaultCredentialsProvider =\nDefaultCredentialsProvider.create()) {\nAwsCredentials credentials = defaultCredentialsProvider.resolveCredentials();\n// Make calls to AWS services.\n} // After the try-with-resources block exits, the singleton\nDefaultCredentialsProvider is closed.\n// Make calls to AWS services.\nDefaultCredentialsProvider defaultCredentialsProvider =\nDefaultCredentialsProvider.create(); // The closed singleton instance is returned.\n// If the credentials (or token) has expired, the following call results in the\nerror.\nAwsCredentials credentials = defaultCredentialsProvider.resolveCredentials();\nConnection pool shut down 144\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a new, non-singleton instance by calling\nDefaultCredentialsProvider.builder().build() if your code has closed the singleton\ninstance and you need to resolve credentials by using a DefaultCredentialsProvider.", "mimetype": "text/plain", "start_char_idx": 286826, "end_char_idx": 291467, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "422f1b1e-f734-4c25-96a6-a2fa099e2223": {"__data__": {"id_": "422f1b1e-f734-4c25-96a6-a2fa099e2223", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c00b08c4-8091-4f8e-b987-49fcc82fbbba", "node_type": "1", "metadata": {}, "hash": "1867b9a8dab61d940d1a48bb0c1cf5183645cb4156121b98e274a4a0bfaa6964", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "38c6d081-a462-46ca-b14c-a6cd9cadbc2e", "node_type": "1", "metadata": {}, "hash": "62de4e1a575837ec61771512dfd9fd386136de469f0d55b2ee213154fc03e554", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "try (DefaultCredentialsProvider defaultCredentialsProvider =\nDefaultCredentialsProvider.create()) {\nAwsCredentials credentials = defaultCredentialsProvider.resolveCredentials();\n// Make calls to AWS services.\n} // After the try-with-resources block exits, the singleton\nDefaultCredentialsProvider is closed.\n// Make calls to AWS services.\nDefaultCredentialsProvider defaultCredentialsProvider =\nDefaultCredentialsProvider.create(); // The closed singleton instance is returned.\n// If the credentials (or token) has expired, the following call results in the\nerror.\nAwsCredentials credentials = defaultCredentialsProvider.resolveCredentials();\nConnection pool shut down 144\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a new, non-singleton instance by calling\nDefaultCredentialsProvider.builder().build() if your code has closed the singleton\ninstance and you need to resolve credentials by using a DefaultCredentialsProvider.\nConnection pool shut down 145\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse features of the AWS SDK for Java 2.x\nGeneral features\nThe SDK for Java 2.x contains several features that make programming against AWS services easier.\n\u2022 The SDK hides the complex mechanisms behind retrieving paginated results and polling for\nresources.\n\u2022 Asynchronous programming with non-blocking I/O helps you write concurrent code with better\nperformance. The SDK provides the benefits of HTTP/2, such as reduced latency, where possible.\n\u2022 The Java SDK can generate metrics to help you monitor the operational health of your\napplications.\nService-specific features\nIn addition to the general features mentioned previously, the Java SDK provides features for\nspecific AWS services.\n\u2022 Amazon S3 \u2013 To simplify your work with files and directories with Amazon S3, the SDK provides\nthe S3 Transfer Manager. To improve performance and reliability while using the SDK's standard\nasynchronous S3 API, the SDK offers the AWS CRT-based S3 client.\n\u2022 DynamoDB \u2013 Object-oriented, mapping capability is provided by the DynamoDB Enhanced Client\nAPI. Work with JSON-style, document-oriented data by using the Enhanced Document API.\n\u2022 IAM \u2013 The IAM Policy Builder API provides a type-safe, object-oriented way to create IAM\npolicies.\nWork with paginated results using the AWS SDK for Java 2.x\nMany AWS operations return paginated results when the response object is too large to return in\na single response. In the AWS SDK for Java 1.0, the response contains a token you use to retrieve\nthe next page of results. In contrast, the AWS SDK for Java 2.x has autopagination methods that\nmake multiple service calls to get the next page of results for you automatically. You only have\nto write code that processes the results. Autopagination is available for both synchronous and\nasynchronous clients.\nGeneral features 146\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nThese code snippets assume that you understand the basics of using the SDK, and have\nconfigured your environment with single sign-on access.\nSynchronous pagination\nThe following examples demonstrate synchronous pagination methods to list objects in an Amazon\nS3 bucket.\nIterate over pages\nThe first example demonstrates the use of a listRes paginator object, a\nListObjectsV2Iterable instance, to iterate through all the response pages with the stream\nmethod. The code streams over the response pages, converts the response stream to a stream of\nS3Object content, and then processes the content of the Amazon S3 object.\nThe following imports apply to all examples in this synchronous pagination section.", "mimetype": "text/plain", "start_char_idx": 290527, "end_char_idx": 294120, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "38c6d081-a462-46ca-b14c-a6cd9cadbc2e": {"__data__": {"id_": "38c6d081-a462-46ca-b14c-a6cd9cadbc2e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "422f1b1e-f734-4c25-96a6-a2fa099e2223", "node_type": "1", "metadata": {}, "hash": "41b0c13c10637dc1fdb7e241c135ed0cc4382cf30317a7a6b2025a0e84c66946", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "07f4f88c-1d50-404d-af6f-a3b6f3466c36", "node_type": "1", "metadata": {}, "hash": "c997bec4a8526b1c4d1508ce246488625966bf7be3f556cc189020d91befe668", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "You only have\nto write code that processes the results. Autopagination is available for both synchronous and\nasynchronous clients.\nGeneral features 146\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nThese code snippets assume that you understand the basics of using the SDK, and have\nconfigured your environment with single sign-on access.\nSynchronous pagination\nThe following examples demonstrate synchronous pagination methods to list objects in an Amazon\nS3 bucket.\nIterate over pages\nThe first example demonstrates the use of a listRes paginator object, a\nListObjectsV2Iterable instance, to iterate through all the response pages with the stream\nmethod. The code streams over the response pages, converts the response stream to a stream of\nS3Object content, and then processes the content of the Amazon S3 object.\nThe following imports apply to all examples in this synchronous pagination section.\nImports\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.Random;\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.s3.model.S3Exception;\nimport software.amazon.awssdk.services.s3.model.PutObjectRequest;\nimport software.amazon.awssdk.services.s3.model.ListObjectsV2Request;\nimport software.amazon.awssdk.services.s3.model.ListObjectsV2Response;\nimport software.amazon.awssdk.services.s3.model.S3Object;\nimport software.amazon.awssdk.services.s3.model.GetObjectRequest;\nimport software.amazon.awssdk.services.s3.model.DeleteObjectRequest;\nimport software.amazon.awssdk.services.s3.model.DeleteBucketRequest;\nimport software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;\nSynchronous pagination 147\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;\nimport software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;\nimport software.amazon.awssdk.services.s3.model.CreateBucketRequest;\nimport software.amazon.awssdk.services.s3.model.CompletedPart;\nimport software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;\nimport software.amazon.awssdk.services.s3.model.UploadPartRequest;\nimport software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;\nimport software.amazon.awssdk.services.s3.waiters.S3Waiter;\nimport software.amazon.awssdk.services.s3.model.HeadBucketRequest;\nimport software.amazon.awssdk.services.s3.model.HeadBucketResponse;\nListObjectsV2Request listReq = ListObjectsV2Request.builder()\n.bucket(bucketName)\n.maxKeys(1)\n.build();\nListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq);\n// Process response pages\nlistRes.stream()\n.flatMap(r -> r.contents().stream())\n.forEach(content -> System.out\n.println(\" Key: \" + content.key() + \" size = \" + content.size()));\nSee the complete example on GitHub.\nIterate over objects\nThe following examples show ways to iterate over the objects returned in the response instead of\nthe pages of the response. The contents method of ListObjectsV2Iterable class returns an\nSdkIterable that provides several methods to process the underlying content elements.\nUse a stream\nThe following snippet uses the stream method on the response content to iterate over the\npaginated item collection.\n// Helper method to work with paginated collection of items directly.\nlistRes.contents().stream()\n.forEach(content -> System.out\n.println(\" Key: \" + content.key() + \" size = \" + content.size()));\nSynchronous pagination 148\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example on GitHub.\nUse a for-each loop\nSince SdkIterable extends the Iterable interface, you can process the contents like any\nIterable. The following snippet uses standard for-each loop to iterate through the contents of\nthe response.\nfor (S3Object content : listRes.contents()) {\nSystem.out.println(\" Key: \" + content.key() + \" size = \" + content.size());\n}\nSee the complete example on GitHub.\nManual pagination\nIf your use case requires it, manual pagination is still available. Use the next token in the response\nobject for the subsequent requests. The following example uses a while loop.", "mimetype": "text/plain", "start_char_idx": 293208, "end_char_idx": 297580, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "07f4f88c-1d50-404d-af6f-a3b6f3466c36": {"__data__": {"id_": "07f4f88c-1d50-404d-af6f-a3b6f3466c36", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "38c6d081-a462-46ca-b14c-a6cd9cadbc2e", "node_type": "1", "metadata": {}, "hash": "62de4e1a575837ec61771512dfd9fd386136de469f0d55b2ee213154fc03e554", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "793d79d1-2aa7-479e-a8a4-0b1437d18a4d", "node_type": "1", "metadata": {}, "hash": "98635858869e56d277bd0e22ef968d11d96ab3145b2d2daf76a2d89e1b7e5166", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Helper method to work with paginated collection of items directly.\nlistRes.contents().stream()\n.forEach(content -> System.out\n.println(\" Key: \" + content.key() + \" size = \" + content.size()));\nSynchronous pagination 148\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example on GitHub.\nUse a for-each loop\nSince SdkIterable extends the Iterable interface, you can process the contents like any\nIterable. The following snippet uses standard for-each loop to iterate through the contents of\nthe response.\nfor (S3Object content : listRes.contents()) {\nSystem.out.println(\" Key: \" + content.key() + \" size = \" + content.size());\n}\nSee the complete example on GitHub.\nManual pagination\nIf your use case requires it, manual pagination is still available. Use the next token in the response\nobject for the subsequent requests. The following example uses a while loop.\nListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder()\n.bucket(bucketName)\n.maxKeys(1)\n.build();\nboolean done = false;\nwhile (!done) {\nListObjectsV2Response listObjResponse =\ns3.listObjectsV2(listObjectsReqManual);\nfor (S3Object content : listObjResponse.contents()) {\nSystem.out.println(content.key());\n}\nif (listObjResponse.nextContinuationToken() == null) {\ndone = true;\n}\nlistObjectsReqManual = listObjectsReqManual.toBuilder()\n.continuationToken(listObjResponse.nextContinuationToken())\n.build();\n}\nSee the complete example on GitHub.\nSynchronous pagination 149\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAsynchronous pagination\nThe following examples demonstrate asynchronous pagination methods to list DynamoDB tables.\nIterate over pages of table names\nThe following two examples use an asynchronous DynamoDB client that call the\nlistTablesPaginator method with a request to get a ListTablesPublisher.\nListTablesPublisher implements two interfaces, which provides many options to process\nresponses. We'll look at methods of each interface.\nUse a Subscriber\nThe following code example demonstrates how to process paginated results by using the\norg.reactivestreams.Publisher interface implemented by ListTablesPublisher. To\nlearn more about the reactive streams model, see the Reactive Streams GitHub repo.\nThe following imports apply to all examples in this asynchronous pagination section.\nImports\nimport io.reactivex.rxjava3.core.Flowable;\nimport org.reactivestreams.Subscriber;\nimport org.reactivestreams.Subscription;\nimport reactor.core.publisher.Flux;\nimport software.amazon.awssdk.core.async.SdkPublisher;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport software.amazon.awssdk.services.dynamodb.paginators.ListTablesPublisher;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\nThe following code acquires a ListTablesPublisher instance.\n// Creates a default client with credentials and region loaded from the\n// environment.\nfinal DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();\nAsynchronous pagination 150\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListTablesRequest listTablesRequest =\nListTablesRequest.builder().limit(3).build();\nListTablesPublisher publisher =\nasyncClient.listTablesPaginator(listTablesRequest);\nThe following code uses an anonymous implementation of org.reactivestreams.Subscriber\nto process the results for each page.\nThe onSubscribe method calls the Subscription.request method to initiate requests for\ndata from the publisher. This method must be called to start getting data from the publisher.\nThe subscriber's onNext method processes a response page by accessing all the table names and\nprinting out each one. After the page is processed, another page is requested from the publisher.\nThis method that is called repeatedly until all pages are retrieved.\nThe onError method is triggered if an error occurs while retrieving data. Finally, the onComplete\nmethod is called when all pages have been requested.\n// A Subscription represents a one-to-one life-cycle of a Subscriber\nsubscribing\n// to a Publisher.\npublisher.subscribe(new Subscriber() {\n// Maintain a reference to the subscription object, which is required to\nrequest\n// data from the publisher.\nprivate Subscription subscription;\n@Override\npublic void onSubscribe(Subscription s) {\nsubscription = s;\n// Request method should be called to demand data. Here we request a\nsingle\n// page.\nsubscription.request(1);\n}\n@Override\npublic void onNext(ListTablesResponse response) {\nresponse.tableNames().forEach(System.out::println);\n// After you process the current page, call the request method to\nsignal that\n// you are ready for next page.", "mimetype": "text/plain", "start_char_idx": 296694, "end_char_idx": 301533, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "793d79d1-2aa7-479e-a8a4-0b1437d18a4d": {"__data__": {"id_": "793d79d1-2aa7-479e-a8a4-0b1437d18a4d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "07f4f88c-1d50-404d-af6f-a3b6f3466c36", "node_type": "1", "metadata": {}, "hash": "c997bec4a8526b1c4d1508ce246488625966bf7be3f556cc189020d91befe668", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2439a6d2-6998-4ceb-a2b6-656fe8c84cf9", "node_type": "1", "metadata": {}, "hash": "ca53f9c2048411f4c750435e90f450080dd50060dad4ea89d5a101e04d6d3a8d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This method that is called repeatedly until all pages are retrieved.\nThe onError method is triggered if an error occurs while retrieving data. Finally, the onComplete\nmethod is called when all pages have been requested.\n// A Subscription represents a one-to-one life-cycle of a Subscriber\nsubscribing\n// to a Publisher.\npublisher.subscribe(new Subscriber() {\n// Maintain a reference to the subscription object, which is required to\nrequest\n// data from the publisher.\nprivate Subscription subscription;\n@Override\npublic void onSubscribe(Subscription s) {\nsubscription = s;\n// Request method should be called to demand data. Here we request a\nsingle\n// page.\nsubscription.request(1);\n}\n@Override\npublic void onNext(ListTablesResponse response) {\nresponse.tableNames().forEach(System.out::println);\n// After you process the current page, call the request method to\nsignal that\n// you are ready for next page.\nAsynchronous pagination 151\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsubscription.request(1);\n}\n@Override\npublic void onError(Throwable t) {\n// Called when an error has occurred while processing the requests.\n}\n@Override\npublic void onComplete() {\n// This indicates all the results are delivered and there are no more\npages\n// left.\n}\n});\nSee the complete example on GitHub.\nUse a Consumer\nThe SdkPublisher interface that ListTablesPublisher implements has a subscribe method\nthat takes a Consumer and returns a CompletableFuture.\nThe subscribe method from this interface can be used for simple use cases when an\norg.reactivestreams.Subscriber might be too much overhead. As the code below consumes\neach page, it calls the tableNames method on each. The tableNames method returns a\njava.util.List of DynamoDB table names that are processed with the forEach method.\n// Use a Consumer for simple use cases.\nCompletableFuture future = publisher.subscribe(\nresponse -> response.tableNames()\n.forEach(System.out::println));\nSee the complete example on GitHub.\nIterate over table names\nThe following examples show ways to iterate over the objects returned in the response instead of\nthe pages of the response. Similar to the synchronous Amazon S3 example previously shown with\nits contents method, the DynamoDB asynchronous result class, ListTablesPublisher has\nthe tableNames convenience method to interact with the underlying item collection. The return\nAsynchronous pagination 152\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntype of the tableNames method is an SdkPublisher that can be used to request items across all\npages.\nUse a Subscriber\nThe following code acquires an SdkPublisher of the underlying collection of table names.\n// Create a default client with credentials and region loaded from the\n// environment.\nfinal DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();\nListTablesRequest listTablesRequest =\nListTablesRequest.builder().limit(3).build();\nListTablesPublisher listTablesPublisher =\nasyncClient.listTablesPaginator(listTablesRequest);\nSdkPublisher publisher = listTablesPublisher.tableNames();\nThe following code uses an anonymous implementation of org.reactivestreams.Subscriber\nto process the results for each page.\nThe subscriber's onNext method processes an individual element of the collection. In this case,\nit's a table name. After the table name is processed, another table name is requested from the\npublisher. This method that is called repeatedly until all table names are retrieved.\n// Use a Subscriber.\npublisher.subscribe(new Subscriber() {\nprivate Subscription subscription;\n@Override\npublic void onSubscribe(Subscription s) {\nsubscription = s;\nsubscription.request(1);\n}\n@Override\npublic void onNext(String tableName) {\nSystem.out.println(tableName);\nsubscription.request(1);\n}\n@Override\npublic void onError(Throwable t) {\n}\nAsynchronous pagination 153\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic void onComplete() {\n}\n});\nSee the complete example on GitHub.\nUse a Consumer\nThe following example uses the subscribe method of SdkPublisher that takes a Consumer to\nprocess each item.\n// Use a Consumer.\nCompletableFuture future = publisher.subscribe(System.out::println);\nfuture.get();\nSee the complete example on GitHub.\nUse third-party library\nYou can use other third party libraries instead of implementing a custom subscriber. This example\ndemonstrates the use of RxJava, but any library that implements the reactive stream interfaces can\nbe used. See the RxJava wiki page on GitHub for more information on that library.\nTo use the library, add it as a dependency. If using Maven, the example shows the POM snippet to\nuse.", "mimetype": "text/plain", "start_char_idx": 300607, "end_char_idx": 305284, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2439a6d2-6998-4ceb-a2b6-656fe8c84cf9": {"__data__": {"id_": "2439a6d2-6998-4ceb-a2b6-656fe8c84cf9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "793d79d1-2aa7-479e-a8a4-0b1437d18a4d", "node_type": "1", "metadata": {}, "hash": "98635858869e56d277bd0e22ef968d11d96ab3145b2d2daf76a2d89e1b7e5166", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c8a9cc22-3df2-43a0-ad72-97d260a710c6", "node_type": "1", "metadata": {}, "hash": "99cab1aa58db6292dfc913300351d11df50ec1f5f7884b4fd2876d07b29dc7cf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use a Consumer\nThe following example uses the subscribe method of SdkPublisher that takes a Consumer to\nprocess each item.\n// Use a Consumer.\nCompletableFuture future = publisher.subscribe(System.out::println);\nfuture.get();\nSee the complete example on GitHub.\nUse third-party library\nYou can use other third party libraries instead of implementing a custom subscriber. This example\ndemonstrates the use of RxJava, but any library that implements the reactive stream interfaces can\nbe used. See the RxJava wiki page on GitHub for more information on that library.\nTo use the library, add it as a dependency. If using Maven, the example shows the POM snippet to\nuse.\nPOM Entry\n\nio.reactivex.rxjava3\nrxjava\n3.1.6\n\nCode\nDynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();\nListTablesPublisher publisher =\nasyncClient.listTablesPaginator(ListTablesRequest.builder()\n.build());\nAsynchronous pagination 154\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// The Flowable class has many helper methods that work with\n// an implementation of an org.reactivestreams.Publisher.\nList tables = Flowable.fromPublisher(publisher)\n.flatMapIterable(ListTablesResponse::tableNames)\n.toList()\n.blockingGet();\nSystem.out.println(tables);\nSee the complete example on GitHub.\nPoll for resource states in the AWS SDK for Java 2.x: Waiters\nThe waiters utility of the AWS SDK for Java 2.x enables you to validate that AWS resources are in a\nspecified state before performing operations on those resources.\nA waiter is an abstraction used to poll AWS resources, such as DynamoDB tables or Amazon S3\nbuckets, until a desired state is reached (or until a determination is made that the resource won\u2019t\never reach the desired state). Instead of writing logic to continuously poll your AWS resources,\nwhich can be cumbersome and error-prone, you can use waiters to poll a resource and have your\ncode continue to run after the resource is ready.\nPrerequisites\nBefore you can use waiters in a project with the AWS SDK for Java, you must complete the steps in\nSetting up the AWS SDK for Java 2.x.\nYou must also configure your project dependencies (for example, in your pom.xml or\nbuild.gradle file) to use version 2.15.0 or later of the AWS SDK for Java.\nFor example:\n\n\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\nPoll for resource states 155\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\n\n\nUsing waiters\nTo instantiate a waiters object, first create a service client. Set the service client\u2019s waiter()\nmethod as the value of the waiter object. Once the waiter instance exists, set its response options\nto execute the appropriate code.\nSynchronous programming\nThe following code snippet shows how to wait for a DynamoDB table to exist and be in an ACTIVE\nstate.\nDynamoDbClient dynamo = DynamoDbClient.create();\nDynamoDbWaiter waiter = dynamo.waiter();\nWaiterResponse waiterResponse =\nwaiter.waitUntilTableExists(r -> r.tableName(\"myTable\"));\n// print out the matched response with a tableStatus of ACTIVE\nwaiterResponse.matched().response().ifPresent(System.out::println);\nAsynchronous programming\nThe following code snippet shows how to wait for a DynamoDB table to no longer exist.\nDynamoDbAsyncClient asyncDynamo = DynamoDbAsyncClient.create();\nDynamoDbAsyncWaiter asyncWaiter = asyncDynamo.waiter();\nCompletableFuture> waiterResponse =\nasyncWaiter.waitUntilTableNotExists(r -> r.tableName(\"myTable\"));\nwaiterResponse.whenComplete((r, t) -> {\nif (t == null) {\n// print out the matched ResourceNotFoundException\nr.matched().exception().ifPresent(System.out::println);\n}\n}).join();\nUsing waiters 156\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConfigure waiters\nYou can customize the configuration for a waiter by using the overrideConfiguration() on its\nbuilder. For some operations, you can apply a custom configuration when you make the request.\nConfigure a waiter\nThe following code snippet shows how to override the configuration on a waiter.", "mimetype": "text/plain", "start_char_idx": 304613, "end_char_idx": 308938, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c8a9cc22-3df2-43a0-ad72-97d260a710c6": {"__data__": {"id_": "c8a9cc22-3df2-43a0-ad72-97d260a710c6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2439a6d2-6998-4ceb-a2b6-656fe8c84cf9", "node_type": "1", "metadata": {}, "hash": "ca53f9c2048411f4c750435e90f450080dd50060dad4ea89d5a101e04d6d3a8d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "23a43a67-22a5-4f0d-bdc1-3a6938e2a137", "node_type": "1", "metadata": {}, "hash": "929089f98939829c5f4f05644e6b05385cdeccb87111a392cb289270e4b6b220", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DynamoDbAsyncClient asyncDynamo = DynamoDbAsyncClient.create();\nDynamoDbAsyncWaiter asyncWaiter = asyncDynamo.waiter();\nCompletableFuture> waiterResponse =\nasyncWaiter.waitUntilTableNotExists(r -> r.tableName(\"myTable\"));\nwaiterResponse.whenComplete((r, t) -> {\nif (t == null) {\n// print out the matched ResourceNotFoundException\nr.matched().exception().ifPresent(System.out::println);\n}\n}).join();\nUsing waiters 156\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConfigure waiters\nYou can customize the configuration for a waiter by using the overrideConfiguration() on its\nbuilder. For some operations, you can apply a custom configuration when you make the request.\nConfigure a waiter\nThe following code snippet shows how to override the configuration on a waiter.\n// sync\nDynamoDbWaiter waiter =\nDynamoDbWaiter.builder()\n.overrideConfiguration(b -> b.maxAttempts(10))\n.client(dynamoDbClient)\n.build();\n// async\nDynamoDbAsyncWaiter asyncWaiter =\nDynamoDbAsyncWaiter.builder()\n.client(dynamoDbAsyncClient)\n.overrideConfiguration(o -> o.backoffStrategy(\nFixedDelayBackoffStrategy.create(Duration.ofSeconds(2))))\n.scheduledExecutorService(Executors.newScheduledThreadPool(3))\n.build();\nOverride configuration for a specific request\nThe following code snippet shows how to override the configuration for a waiter on a per-request\nbasis. Note that only some operations have customizable configurations.\nwaiter.waitUntilTableNotExists(b -> b.tableName(\"myTable\"),\no -> o.maxAttempts(10));\nasyncWaiter.waitUntilTableExists(b -> b.tableName(\"myTable\"),\no -> o.waitTimeout(Duration.ofMinutes(1)));\nCode examples\nFor a complete example using waiters with DynamoDB, see CreateTable.java in the AWS Code\nExamples Repository.\nFor a complete example using waiters with Amazon S3, see S3BucketOps.java in the AWS Code\nExamples Repository.\nConfigure waiters 157\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse asynchronous programming\nThe AWS SDK for Java 2.x features asynchronous clients with non-blocking I/O support that\nimplement high concurrency across a few threads. However, total non-blocking I/O is not\nguaranteed. Asynchronous client may perform blocking calls in some cases such as credential\nretrieval, request signing using AWS Signature Version 4 (SigV4), or endpoint discovery.\nSynchronous methods block your thread\u2019s execution until the client receives a response from\nthe service. Asynchronous methods return immediately, giving control back to the calling thread\nwithout waiting for a response.\nBecause an asynchronous method returns before a response is available, you need a way to get\nthe response when it\u2019s ready. The methods for asynchronous client in 2.x of the AWS SDK for Java\nreturn CompletableFuture objects that allow you to access the response when it\u2019s ready.\nUse asynchronous client APIs\nThe signatures of asynchronous client methods are the same their synchronous counterpart, but\nthe asynchronous methods return a CompletableFuture object that contains the results of the\nasynchronous operation in the future. If an error is thrown while the SDK's asynchronous method\nexecutes, the error is thrown as CompletionException.\nOne approach you can use to get the result is to chain a whenComplete() method onto the\nCompletableFuture returned by the SDK method call. The whenComplete() method receives\nthe result or a Throwable object of type CompletionException depending on how the\nasynchronous call completed. You provide an action to whenComplete() to process or check the\nresults before it is returned to the calling code.\nIf you want to return something other than the object returned by the SDK method, use\nthe handle() method instead. The handle() method takes the same parameters as\nwhenComplete(), but you can process the result and return an object.\nTo wait for the asynchronous chain to complete and retrieve the completion results, you can\ncall the join() method. If the Throwable object was not handled in the chain, the join()\nmethod throws an unchecked CompletionException that wraps the original exception. You\naccess the original exception with CompletionException#getCause(). You can also call the\nCompletableFuture#get() method to get the completion results. The get() method, however,\ncan throw checked exceptions.\nUse asynchronous programming 158\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following example shows two variations of how you can work with the listTables()\nmethod of the DynamoDB asynchronous client. The action passed to whenComplete() simply\nlogs a successful response, whereas the handle() version extracts the list of table names and\nreturns the list. In both cases if an error is generated in the asynchronous chain, the error is\nrethrown so the client code has a chance to handle it.", "mimetype": "text/plain", "start_char_idx": 308127, "end_char_idx": 312935, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "23a43a67-22a5-4f0d-bdc1-3a6938e2a137": {"__data__": {"id_": "23a43a67-22a5-4f0d-bdc1-3a6938e2a137", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c8a9cc22-3df2-43a0-ad72-97d260a710c6", "node_type": "1", "metadata": {}, "hash": "99cab1aa58db6292dfc913300351d11df50ec1f5f7884b4fd2876d07b29dc7cf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a731d2be-754a-4e05-8808-bcf6ca968782", "node_type": "1", "metadata": {}, "hash": "e30ac3b20a97ac6bd8e146634f3a6c21f54e6724560611fe1e53f4ff3dd612a8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If the Throwable object was not handled in the chain, the join()\nmethod throws an unchecked CompletionException that wraps the original exception. You\naccess the original exception with CompletionException#getCause(). You can also call the\nCompletableFuture#get() method to get the completion results. The get() method, however,\ncan throw checked exceptions.\nUse asynchronous programming 158\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following example shows two variations of how you can work with the listTables()\nmethod of the DynamoDB asynchronous client. The action passed to whenComplete() simply\nlogs a successful response, whereas the handle() version extracts the list of table names and\nreturns the list. In both cases if an error is generated in the asynchronous chain, the error is\nrethrown so the client code has a chance to handle it.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\nCode\nwhenComplete() variation\npublic class DynamoDbAsyncListTables {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nDynamoDbAsyncClient dynamoDbAsyncClient =\nDynamoDbAsyncClient.builder().region(region).build();\ntry {\nListTablesResponse listTablesResponse =\nlistTablesWhenComplete(dynamoDbAsyncClient).join(); // The join() method may throw\na CompletionException.\nif (listTablesResponse.hasTableNames()){\nSystem.out.println(\"Table exist in this region: \" + region.id());\n}\n} catch (RuntimeException e) {\n// Handle as needed. Here we simply print out the class names.\nSystem.out.println(e.getClass()); // Prints 'class\njava.util.concurrent.CompletionException'.\nSystem.out.println(e.getCause().getClass()); // Prints 'class\nsoftware.amazon.awssdk.services.dynamodb.model.DynamoDbException'.\n}\n}\nUse asynchronous client APIs 159\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static CompletableFuture\nlistTablesWhenComplete(DynamoDbAsyncClient client) {\nreturn client.listTables(ListTablesRequest.builder().build())\n.whenComplete((listTablesResponse, throwable) -> {\nif (listTablesResponse != null) { // Consume the response.\nSystem.out.println(\"The SDK's listTables method completed\nsuccessfully.\");\n} else {\nRuntimeException cause = (RuntimeException)\nthrowable.getCause(); // If an error was thrown during the SDK's listTables method\nit is wrapped in a CompletionException.\n// The SDK throws only RuntimeExceptions, so this is a safe cast.\nSystem.out.println(cause.getMessage()); // Log error here, but\nrethrow so the calling code can handle as needed.\nthrow cause;\n}\n});\n}\nhandle() variation\npublic class DynamoDbAsyncListTables {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nDynamoDbAsyncClient dynamoDbAsyncClient =\nDynamoDbAsyncClient.builder().region(region).build();\ntry {\nList tableNames =\nlistTablesHandle(dynamoDbAsyncClient).join(); // The join() method may throw a\nCompletionException.\ntableNames.forEach(System.out::println);\n} catch (RuntimeException e) {\n// Handle as needed. Here we simply print out the class names.\nSystem.out.println(e.getClass()); // Prints 'class\njava.util.concurrent.CompletionException'.\nSystem.out.println(e.getCause().getClass()); // Prints 'class\nsoftware.amazon.awssdk.services.dynamodb.model.DynamoDbException'.\n}\n}\nUse asynchronous client APIs 160\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static CompletableFuture>\nlistTablesHandle(DynamoDbAsyncClient client) {\nreturn client.listTables(ListTablesRequest.builder().build())\n.handle((listTablesResponse, throwable) -> {\nif (listTablesResponse != null) {\nreturn listTablesResponse.tableNames(); // Return the list of\ntable names.\n} else {\nRuntimeException cause = (RuntimeException)\nthrowable.getCause(); // If an error was thrown during the SDK's listTables method\nit is wrapped in a CompletionException.\n// The SDK throws only RuntimeExceptions, so this is a safe cast.\nSystem.out.println(cause.getMessage()); // Log error here, but\nrethrow so the calling code can handle as needed.\nthrow cause;\n}\n});\n}\n}\nHandle streaming in asynchronous methods\nFor asynchronous methods with streaming content, you must provide an AsyncRequestBody to\nprovide the content incrementally, or an AsyncResponseTransformer to receive and process the\nresponse.\nThe following example uploads a file to Amazon S3 asynchronously by using the asynchronous\nform of the PutObject operation.", "mimetype": "text/plain", "start_char_idx": 312073, "end_char_idx": 316764, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a731d2be-754a-4e05-8808-bcf6ca968782": {"__data__": {"id_": "a731d2be-754a-4e05-8808-bcf6ca968782", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "23a43a67-22a5-4f0d-bdc1-3a6938e2a137", "node_type": "1", "metadata": {}, "hash": "929089f98939829c5f4f05644e6b05385cdeccb87111a392cb289270e4b6b220", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ef788bd3-af02-4fa1-b0aa-963d036441ce", "node_type": "1", "metadata": {}, "hash": "30a122333175d32aefe20c4b54a9f73221878b2a876c399e60a102b8f2ea9eed", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "else {\nRuntimeException cause = (RuntimeException)\nthrowable.getCause(); // If an error was thrown during the SDK's listTables method\nit is wrapped in a CompletionException.\n// The SDK throws only RuntimeExceptions, so this is a safe cast.\nSystem.out.println(cause.getMessage()); // Log error here, but\nrethrow so the calling code can handle as needed.\nthrow cause;\n}\n});\n}\n}\nHandle streaming in asynchronous methods\nFor asynchronous methods with streaming content, you must provide an AsyncRequestBody to\nprovide the content incrementally, or an AsyncResponseTransformer to receive and process the\nresponse.\nThe following example uploads a file to Amazon S3 asynchronously by using the asynchronous\nform of the PutObject operation.\nImports\nimport software.amazon.awssdk.core.async.AsyncRequestBody;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport software.amazon.awssdk.services.s3.model.PutObjectRequest;\nimport software.amazon.awssdk.services.s3.model.PutObjectResponse;\nimport java.nio.file.Paths;\nimport java.util.concurrent.CompletableFuture;\nCode\nHandle streaming in asynchronous methods 161\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* To run this AWS code example, ensure that you have setup your development\nenvironment, including your AWS credentials.\n*\n* For information, see this documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class S3AsyncOps {\npublic static void main(String[] args) {\nfinal String USAGE = \"\\n\" +\n\"Usage:\\n\" +\n\" S3AsyncOps \\n\\n\" +\n\"Where:\\n\" +\n\" bucketName - the name of the Amazon S3 bucket (for example,\nbucket1). \\n\\n\" +\n\" key - the name of the object (for example, book.pdf). \\n\" +\n\" path - the local path to the file (for example, C:/AWS/book.pdf).\n\\n\" ;\nif (args.length != 3) {\nSystem.out.println(USAGE);\nSystem.exit(1);\n}\nString bucketName = args[0];\nString key = args[1];\nString path = args[2];\nRegion region = Region.US_WEST_2;\nS3AsyncClient client = S3AsyncClient.builder()\n.region(region)\n.build();\nPutObjectRequest objectRequest = PutObjectRequest.builder()\n.bucket(bucketName)\n.key(key)\n.build();\n// Put the object into the bucket\nHandle streaming in asynchronous methods 162\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture future = client.putObject(objectRequest,\nAsyncRequestBody.fromFile(Paths.get(path))\n);\nfuture.whenComplete((resp, err) -> {\ntry {\nif (resp != null) {\nSystem.out.println(\"Object uploaded. Details: \" + resp);\n} else {\n// Handle error\nerr.printStackTrace();\n}\n} finally {\n// Only close the client when you are completely done with it\nclient.close();\n}\n});\nfuture.join();\n}\n}\nThe following example gets a file from Amazon S3 by using the asynchronous form of the\nGetObject operation.\nImports\nimport software.amazon.awssdk.core.async.AsyncResponseTransformer;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport software.amazon.awssdk.services.s3.model.GetObjectRequest;\nimport software.amazon.awssdk.services.s3.model.GetObjectResponse;\nimport java.nio.file.Paths;\nimport java.util.concurrent.CompletableFuture;\nCode\n/**\n* To run this AWS code example, ensure that you have setup your development\nenvironment, including your AWS credentials.\n*\n* For information, see this documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\nHandle streaming in asynchronous methods 163\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic class S3AsyncStreamOps {\npublic static void main(String[] args) {\nfinal String USAGE = \"\\n\" +\n\"Usage:\\n\" +\n\" S3AsyncStreamOps \\n\\n\" +\n\"Where:\\n\" +\n\" bucketName - the name of the Amazon S3 bucket (for example,\nbucket1). \\n\\n\" +\n\" objectKey - the name of the object (for example, book.pdf). \\n\" +\n\" path - the local path to the file (for example, C:/AWS/book.pdf).", "mimetype": "text/plain", "start_char_idx": 316032, "end_char_idx": 320045, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ef788bd3-af02-4fa1-b0aa-963d036441ce": {"__data__": {"id_": "ef788bd3-af02-4fa1-b0aa-963d036441ce", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a731d2be-754a-4e05-8808-bcf6ca968782", "node_type": "1", "metadata": {}, "hash": "e30ac3b20a97ac6bd8e146634f3a6c21f54e6724560611fe1e53f4ff3dd612a8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e39006a1-ecfe-4cd7-9e07-f488a42ea4ec", "node_type": "1", "metadata": {}, "hash": "c4ba64320ccefb553784fa935cad61154a5171f4d21d771b3a1f35aa60795994", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For information, see this documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\nHandle streaming in asynchronous methods 163\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic class S3AsyncStreamOps {\npublic static void main(String[] args) {\nfinal String USAGE = \"\\n\" +\n\"Usage:\\n\" +\n\" S3AsyncStreamOps \\n\\n\" +\n\"Where:\\n\" +\n\" bucketName - the name of the Amazon S3 bucket (for example,\nbucket1). \\n\\n\" +\n\" objectKey - the name of the object (for example, book.pdf). \\n\" +\n\" path - the local path to the file (for example, C:/AWS/book.pdf).\n\\n\" ;\nif (args.length != 3) {\nSystem.out.println(USAGE);\nSystem.exit(1);\n}\nString bucketName = args[0];\nString objectKey = args[1];\nString path = args[2];\nRegion region = Region.US_WEST_2;\nS3AsyncClient client = S3AsyncClient.builder()\n.region(region)\n.build();\nGetObjectRequest objectRequest = GetObjectRequest.builder()\n.bucket(bucketName)\n.key(objectKey)\n.build();\nCompletableFuture futureGet =\nclient.getObject(objectRequest,\nAsyncResponseTransformer.toFile(Paths.get(path)));\nfutureGet.whenComplete((resp, err) -> {\ntry {\nif (resp != null) {\nSystem.out.println(\"Object downloaded. Details: \"+resp);\n} else {\nHandle streaming in asynchronous methods 164\nAWS SDK for Java 2.x Developer Guide for version 2.x\nerr.printStackTrace();\n}\n} finally {\n// Only close the client when you are completely done with it\nclient.close();\n}\n});\nfutureGet.join();\n}\n}\nConfigure advanced asynchronous options\nThe AWS SDK for Java 2.x uses Netty, an asynchronous event-driven network application\nframework, to handle I/O threads. The AWS SDK for Java 2.x creates an ExecutorService behind\nNetty, to complete the futures returned from the HTTP client request through to the Netty client.\nThis abstraction reduces the risk of an application breaking the async process if developers choose\nto stop or sleep threads. By default, each asynchronous client creates a threadpool based on the\nnumber of processors and manages the tasks in a queue within the ExecutorService.\nYou can specify a specific JDK implementation of ExecutorService when you build your\nasynchronous client. The following snippet create an ExecutorService with a fixed number of\nthreads.\nCode\nS3AsyncClient clientThread = S3AsyncClient.builder()\n.asyncConfiguration(\nb -> b.advancedOption(SdkAdvancedAsyncClientOption\n.FUTURE_COMPLETION_EXECUTOR,\nExecutors.newFixedThreadPool(10)\n)\n)\n.build();\nTo optimize performance, you can manage your own thread pool executor, and include it when you\nconfigure your client.\nThreadPoolExecutor executor = new ThreadPoolExecutor(50, 50,\n10, TimeUnit.SECONDS,\nnew LinkedBlockingQueue<>(),\nConfigure advanced asynchronous options 165\nAWS SDK for Java 2.x Developer Guide for version 2.x\nnew ThreadFactoryBuilder()\n.threadNamePrefix(\"sdk-async-response\").build());\n// Allow idle core threads to time out\nexecutor.allowCoreThreadTimeOut(true);\nS3AsyncClient clientThread = S3AsyncClient.builder()\n.asyncConfiguration(\nb -> b.advancedOption(SdkAdvancedAsyncClientOption\n.FUTURE_COMPLETION_EXECUTOR,\nexecutor\n)\n)\n.build();\nWork with HTTP/2 in the AWS SDK for Java\nHTTP/2 is a major revision of the HTTP protocol. This new version has several enhancements to\nimprove performance:\n\u2022 Binary data encoding provides more efficient data transfer.\n\u2022 Header compression reduces the overhead bytes downloaded by the client, helping get\nthe content to the client sooner. This is especially useful for mobile clients that are already\nconstrained on bandwidth.\n\u2022 Bidirectional asynchronous communication (multiplexing) allows multiple requests and response\nmessages between the client and AWS to be in flight at the same time over a single connection,\ninstead of over multiple connections, which improves performance.\nDevelopers upgrading to the latest SDKs will automatically use HTTP/2 when it\u2019s supported by the\nservice they\u2019re working with. New programming interfaces seamlessly take advantage of HTTP/2\nfeatures and provide new ways to build applications.\nThe AWS SDK for Java 2.x features new APIs for event streaming that implement the HTTP/2\nprotocol. For examples of how to use these new APIs, see Working with Kinesis.\nUse SDK metrics from the AWS SDK for Java\nWith the AWS SDK for Java 2.x, you can collect metrics about the service clients in your application,\nanalyze the output in Amazon CloudWatch, and then act on it.", "mimetype": "text/plain", "start_char_idx": 319408, "end_char_idx": 323878, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e39006a1-ecfe-4cd7-9e07-f488a42ea4ec": {"__data__": {"id_": "e39006a1-ecfe-4cd7-9e07-f488a42ea4ec", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ef788bd3-af02-4fa1-b0aa-963d036441ce", "node_type": "1", "metadata": {}, "hash": "30a122333175d32aefe20c4b54a9f73221878b2a876c399e60a102b8f2ea9eed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5be5e087-c96f-436d-bea0-cfd2992982e1", "node_type": "1", "metadata": {}, "hash": "a9173fa4f0a3002c545ddd84357e3bb903bf8c8c1cd1c43c3c8fe627bcf5393e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This is especially useful for mobile clients that are already\nconstrained on bandwidth.\n\u2022 Bidirectional asynchronous communication (multiplexing) allows multiple requests and response\nmessages between the client and AWS to be in flight at the same time over a single connection,\ninstead of over multiple connections, which improves performance.\nDevelopers upgrading to the latest SDKs will automatically use HTTP/2 when it\u2019s supported by the\nservice they\u2019re working with. New programming interfaces seamlessly take advantage of HTTP/2\nfeatures and provide new ways to build applications.\nThe AWS SDK for Java 2.x features new APIs for event streaming that implement the HTTP/2\nprotocol. For examples of how to use these new APIs, see Working with Kinesis.\nUse SDK metrics from the AWS SDK for Java\nWith the AWS SDK for Java 2.x, you can collect metrics about the service clients in your application,\nanalyze the output in Amazon CloudWatch, and then act on it.\nWork with HTTP/2 166\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBy default, metrics collection is disabled in the SDK. This topic helps you to enable and configure it.\nPrerequisites\nBefore you can enable and use metrics, you must complete the following steps:\n\u2022 Complete the steps in Setup.\n\u2022 Configure your project dependencies (for example, in your pom.xml or build.gradle file) to\nuse version 2.14.0 or later of the AWS SDK for Java.\nTo enabling publishing of metrics to CloudWatch, also include the artifactId cloudwatch-\nmetric-publisher with the version number 2.14.0 or later in your project\u2019s dependencies.\nFor example:\n\n\n\n\nsoftware.amazon.awssdk\nbom\n2.27.21\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ncloudwatch-metric-publisher\n\n\n\n\u2022 Enable cloudwatch:PutMetricData permissions for the IAM identity used by the metrics\npublisher to allow the SDK for Java to write metrics.\nHow to enable metrics collection\nYou can enable metrics in your application for a service client or on individual requests.\nPrerequisites 167\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnable metrics for a specific request\nThe following class shows how to enable the CloudWatch metrics publisher for a request to\nAmazon DynamoDB. It uses the default metrics publisher configuration.\nimport software.amazon.awssdk.metrics.MetricPublisher;\nimport software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\npublic class DefaultConfigForRequest {\n// Use one MetricPublisher for your application. It can be used with requests or\nservice clients.\nstatic MetricPublisher metricsPub = CloudWatchMetricPublisher.create();\npublic static void main(String[] args) {\nDynamoDbClient ddb = DynamoDbClient.create();\n// Publish metrics the for ListTables operation.\nddb.listTables(ListTablesRequest.builder()\n.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))\n.build());\n// Perform more work in your application.\n// A MetricsPublisher has its own lifecycle independent of any service client\nor request that uses it.\n// If you no longer need the publisher, close it to free up resources.\nmetricsPub.close(); // All metrics stored in memory are flushed to CloudWatch.\n// Perform more work with the DynamoDbClient instance without publishing\nmetrics.\n// Close the service client when you no longer need it.\nddb.close();\n}\n}\nImportant\nMake sure your application calls close on the MetricPublisher instance when the\nservice client is no longer in use. Failure to do so results in possible thread or file descriptor\nleaks.\nHow to enable metrics collection 168\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnable summary metrics for a specific service client\nThe following code snippet shows how to enable a CloudWatch metrics publisher with default\nsettings for a service client.\nMetricPublisher metricsPub = CloudWatchMetricPublisher.create();\nDynamoDbClient ddb = DynamoDbClient.builder()\n.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))\n.build();\nCustomize metrics publisher\nThe following class demonstrates how to set up a custom configuration for the metrics publisher\nfor a specific service client. The customizations include loading a specific profile, specifying a AWS\nRegion where the metrics publisher sends requests, and customizing how often the publisher sends\nmetrics to CloudWatch.", "mimetype": "text/plain", "start_char_idx": 322918, "end_char_idx": 327647, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5be5e087-c96f-436d-bea0-cfd2992982e1": {"__data__": {"id_": "5be5e087-c96f-436d-bea0-cfd2992982e1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e39006a1-ecfe-4cd7-9e07-f488a42ea4ec", "node_type": "1", "metadata": {}, "hash": "c4ba64320ccefb553784fa935cad61154a5171f4d21d771b3a1f35aa60795994", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f7592766-8d31-4ec8-9c35-afc9b3861b31", "node_type": "1", "metadata": {}, "hash": "84a54811b13fd2fe3dd641403d5b3d3720553790b08961e2aa6ebdac3538c831", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ddb.close();\n}\n}\nImportant\nMake sure your application calls close on the MetricPublisher instance when the\nservice client is no longer in use. Failure to do so results in possible thread or file descriptor\nleaks.\nHow to enable metrics collection 168\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnable summary metrics for a specific service client\nThe following code snippet shows how to enable a CloudWatch metrics publisher with default\nsettings for a service client.\nMetricPublisher metricsPub = CloudWatchMetricPublisher.create();\nDynamoDbClient ddb = DynamoDbClient.builder()\n.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))\n.build();\nCustomize metrics publisher\nThe following class demonstrates how to set up a custom configuration for the metrics publisher\nfor a specific service client. The customizations include loading a specific profile, specifying a AWS\nRegion where the metrics publisher sends requests, and customizing how often the publisher sends\nmetrics to CloudWatch.\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.core.metrics.CoreMetric;\nimport software.amazon.awssdk.metrics.MetricPublisher;\nimport software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport java.time.Duration;\npublic class CustomConfigForDDBClient {\n// Use one MetricPublisher for your application. It can be used with requests or\nservice clients.\nstatic MetricPublisher metricsPub = CloudWatchMetricPublisher.builder()\n.cloudWatchClient(CloudWatchAsyncClient.builder()\n.region(Region.US_WEST_2)\n.credentialsProvider(ProfileCredentialsProvider.create(\"cloudwatch\"))\n.build())\n.uploadFrequency(Duration.ofMinutes(5))\n.maximumCallsPerUpload(100)\n.namespace(\"ExampleSDKV2Metrics\")\n.detailedMetrics(CoreMetric.API_CALL_DURATION)\n.build();\nCustomize metrics publisher 169\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void main(String[] args) {\nDynamoDbClient ddb = DynamoDbClient.builder()\n.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))\n.build();\n// Publish metrics for DynamoDB operations.\nddb.listTables();\nddb.describeEndpoints();\nddb.describeLimits();\n// Perform more work in your application.\n// A MetricsPublisher has its own lifecycle independent of any service client\nor request that uses it.\n// If you no longer need the publisher, close it to free up resources.\nmetricsPub.close(); // All metrics stored in memory are flushed to CloudWatch.\n// Perform more work with the DynamoDbClient instance without publishing\nmetrics.\n// Close the service client when you no longer need it.\nddb.close();\n}\n}\nThe customizations shown in the previous snippet have the following effects.\n\u2022 The cloudWatchClient method lets you customize the CloudWatch client used to send\nmetrics. In this example, we use a different region from the default of us-east-1 where the\nclient sends metrics. We also use a different named profile, cloudwatch, whose credentials will\nbe used to authenticate requests to CloudWatch. Those credentials must have permissions to\ncloudwatch:PutMetricData.\n\u2022 The uploadFrequency method allows you to specify how frequently the metrics publisher\nuploads metrics to CloudWatch. The default is once a minute.\n\u2022 The maximumCallsPerUpload method limits the number of calls made per upload. The default\nis unlimited.\n\u2022 By default, the SDK for Java 2.x publishes metrics under the namespace AwsSdk/JavaSdk2. You\ncan use the namespace method to specify a different value.\n\u2022 By default, the SDK publishes summary metrics. Summary metrics consist of average,\nminimum, maximum, sum, and sample count. By specifying one or more SDK metrics in the\ndetailedMetrics method, the SDK publishes additional data for each metric. This additional\ndata enables percentile statistics like p90 and p99 that you can query in CloudWatch. The\nCustomize metrics publisher 170\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndetailed metrics are especially useful for latency metrics like APICallDuration, which\nmeasures the end-to-end latency for SDK client requests. You can use fields of the CoreMetric\nclass to specify other common SDK metrics.\nWhen are metrics available?\nMetrics are generally available within 5-10 minutes after the SDK for Java emits them. For accurate\nand up-to-date metrics, check Cloudwatch at least 10 minutes after emitting the metrics from your\nJava applications.\nWhat information is collected?", "mimetype": "text/plain", "start_char_idx": 326640, "end_char_idx": 331267, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f7592766-8d31-4ec8-9c35-afc9b3861b31": {"__data__": {"id_": "f7592766-8d31-4ec8-9c35-afc9b3861b31", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5be5e087-c96f-436d-bea0-cfd2992982e1", "node_type": "1", "metadata": {}, "hash": "a9173fa4f0a3002c545ddd84357e3bb903bf8c8c1cd1c43c3c8fe627bcf5393e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1bf9c4e8-1201-4385-9ed1-f4714f7ce405", "node_type": "1", "metadata": {}, "hash": "15f90945e74913661c58bbe5b45367dad9f4225ce6fd56cadb4ebc3aa09f1390", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Summary metrics consist of average,\nminimum, maximum, sum, and sample count. By specifying one or more SDK metrics in the\ndetailedMetrics method, the SDK publishes additional data for each metric. This additional\ndata enables percentile statistics like p90 and p99 that you can query in CloudWatch. The\nCustomize metrics publisher 170\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndetailed metrics are especially useful for latency metrics like APICallDuration, which\nmeasures the end-to-end latency for SDK client requests. You can use fields of the CoreMetric\nclass to specify other common SDK metrics.\nWhen are metrics available?\nMetrics are generally available within 5-10 minutes after the SDK for Java emits them. For accurate\nand up-to-date metrics, check Cloudwatch at least 10 minutes after emitting the metrics from your\nJava applications.\nWhat information is collected?\nMetrics collection includes the following:\n\u2022 Number of API requests, including whether they succeed or fail\n\u2022 Information about the AWS services you call in your API requests, including exceptions returned\n\u2022 The duration for various operations such as Marshalling, Signing, and HTTP requests\n\u2022 HTTP client metrics, such as the number of open connections, the number of pending requests,\nand the name of the HTTP client used\nNote\nThe metrics available vary by HTTP client.\nFor a complete list, see Service client metrics.\nHow can I use this information?\nYou can use the metrics the SDK collects to monitor the service clients in your application. You can\nlook at overall usage trends, identify anomalies, review service client exceptions returned, or to dig\nin to understand a particular issue. Using Amazon CloudWatch, you can also create alarms to notify\nyou as soon as your application reaches a condition that you define.\nFor more information, see Using Amazon CloudWatch Metrics and Using Amazon CloudWatch\nAlarms in the Amazon CloudWatch User Guide.\nWhen are metrics available? 171\nAWS SDK for Java 2.x Developer Guide for version 2.x\nService client metrics\nWith the AWS SDK for Java 2.x, you can collect metrics from the service clients in your application\nand then publish (output) those metrics to Amazon CloudWatch.\nThese tables list the metrics that you can collect and any HTTP client usage requirement.\nFor more information about enabling and configuring metrics for the SDK, see Enabling SDK\nmetrics.\nMetrics collected with each request\nMetric name Description Type\nApiCallDuration The total time taken to finish Duration*\na request (inclusive of all\nretries).\nApiCallSuccessful True if the API call was Boolean\nsuccessful; false if not.\nCredentialsFetchDuration The time taken to fetch AWS Duration*\nsigning credentials for the\nrequest.\nEndpointResolveDuration The duration of time it took Duration*\nto resolve the endpoint used\nfor the API call.\nMarshallingDuration The time it takes to marshall Duration*\nan SDK request to an HTTP\nrequest.\nOperationName The name of the AWS API the String\nrequest is made to.\nRetryCount Number of times the SDK Integer\nretried the API call.\nService client metrics 172\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMetric name Description Type\nServiceId Service ID of the AWS service String\nthat the API request is made\nagainst.\nTokenFetchDuration The time taken to fetch token Duration*\nsigning credentials for the\nrequest.\n*java.time.Duration.\nMetrics collected for each request attempt\nEach API call might require multiple attempts before a response is received. These metrics are\ncollected for each attempt.\nCore metrics\nMetric name Description Type\nAwsExtendedRequestId The extended request ID of String\nthe service request.\nAwsRequestId The request ID of the service String\nrequest.\nBackoffDelayDuration The duration of time the SDK Duration*\nwaited before this API call\nattempt.\nErrorType The type of error that String\noccurred for a call attempt.\nReadThroughput The read throughput of the Double\nclient in bytes/second.\nServiceCallDuration The time it takes to connect Duration*\nto the service, send the\nService client metrics 173\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMetric name Description Type\nrequest, and receive the HTTP\nstatus code and header from\nthe response.\nSigningDuration The time it takes to sign the Duration*\nHTTP request.\nTimeToFirstByte Elapsed time from sending Duration*\nthe HTTP request (includin\ng acquiring a connection) to\nreceiving the first byte of the\nheaders in the response.\nTimeToLastByte Elapsed time from sending Duration*\nthe HTTP request (includin\ng acquiring a connection) to\nreceiving the last byte of the\nresponse.\nUnmarshallingDuration The time it takes to Duration*\nunmarshall an HTTP response\nto an SDK response.\n*java.time.Duration.", "mimetype": "text/plain", "start_char_idx": 330380, "end_char_idx": 335120, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1bf9c4e8-1201-4385-9ed1-f4714f7ce405": {"__data__": {"id_": "1bf9c4e8-1201-4385-9ed1-f4714f7ce405", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f7592766-8d31-4ec8-9c35-afc9b3861b31", "node_type": "1", "metadata": {}, "hash": "84a54811b13fd2fe3dd641403d5b3d3720553790b08961e2aa6ebdac3538c831", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2604f5b6-57b3-4c0e-a687-b8ae3c6acc49", "node_type": "1", "metadata": {}, "hash": "6d907a0cb9ee2d1d3bbff88993bf46d0b6c987769364c500852d2d14957c60d0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ReadThroughput The read throughput of the Double\nclient in bytes/second.\nServiceCallDuration The time it takes to connect Duration*\nto the service, send the\nService client metrics 173\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMetric name Description Type\nrequest, and receive the HTTP\nstatus code and header from\nthe response.\nSigningDuration The time it takes to sign the Duration*\nHTTP request.\nTimeToFirstByte Elapsed time from sending Duration*\nthe HTTP request (includin\ng acquiring a connection) to\nreceiving the first byte of the\nheaders in the response.\nTimeToLastByte Elapsed time from sending Duration*\nthe HTTP request (includin\ng acquiring a connection) to\nreceiving the last byte of the\nresponse.\nUnmarshallingDuration The time it takes to Duration*\nunmarshall an HTTP response\nto an SDK response.\n*java.time.Duration.\nHTTP Metrics\nMetric name Description Type HTTP client\nrequired*\nAvailableConcurrency The number of Integer Apache, Netty, CRT\nremaining concurren\nt requests that can\nbe supported by the\nHTTP client without\nService client metrics 174\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMetric name Description Type HTTP client\nrequired*\nneeding to establish\nanother connection.\nConcurrencyAcquire The time taken to Duration* Apache, Netty, CRT\nDuration acquire a channel\nfrom the connection\npool.\nHttpClientName The name of the String Apache, Netty, CRT\nHTTP being use for\nthe request.\nHttpStatusCode The status code Integer Any\nreturned with the\nHTTP response.\nLeasedConcurrency The number of Integer Apache, Netty, CRT\nrequest currently\nbeing executed by\nthe HTTP client.\nLocalStreamWindowS The local HTTP/2 Integer Netty\nize window size in bytes\nfor the stream that\nthis request was\nexecuted on.\nMaxConcurrency The max number of Integer Apache, Netty, CRT\nconcurrent requests\nsupported by the\nHTTP client.\nService client metrics 175\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMetric name Description Type HTTP client\nrequired*\nPendingConcurrency The number of Integer Apache, Netty, CRT\nAcquires requests that are\nblocked, waiting\nfor another TCP\nconnection or a\nnew stream to be\navailable from the\nconnection pool.\nRemoteStr The remote HTTP/2 Integer Netty\neamWindowSize window size in bytes\nfor the stream that\nthis request was\nexecuted on.\n*java.time.Duration.\nThe terms used in the column mean:\n\u2022 Apache: the Apache-based HTTP client (ApacheHttpClient)\n\u2022 Netty: the Netty-based HTTP client (NettyNioAsyncHttpClient)\n\u2022 CRT: the AWS CRT-based HTTP client (AwsCrtAsyncHttpClient)\n\u2022 Any: the collection of metric data does not depend on the HTTP client; this includes the\nURLConnection-based HTTP client (UrlConnectionHttpClient)\nService client metrics 176\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWork with AWS services using the AWS SDK for Java 2.x\nThis section provides short tutorials and guidance for how to work with select AWS services. For a\ncomplete set of examples, see the Code Examples section.\nTopics\n\u2022 Work with CloudWatch\n\u2022 AWS database services and AWS SDK for Java 2.x\n\u2022 Work with DynamoDB\n\u2022 Work with Amazon EC2\n\u2022 Work with IAM\n\u2022 Work with Kinesis\n\u2022 Invoke, list, and delete AWS Lambda functions\n\u2022 Work with Amazon S3\n\u2022 Work with Amazon Simple Notification Service\n\u2022 Work with Amazon Simple Queue Service\n\u2022 Work with Amazon Transcribe\nWork with CloudWatch\nThis section provides examples of programming Amazon CloudWatch by using the AWS SDK for\nJava 2.x.\nAmazon CloudWatch monitors your Amazon Web Services (AWS) resources and the applications\nyou run on AWS in real time. You can use CloudWatch to collect and track metrics, which\nare variables you can measure for your resources and applications. CloudWatch alarms send\nnotifications or automatically make changes to the resources you are monitoring based on rules\nthat you define.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\nCloudWatch 177\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Get metrics from CloudWatch\n\u2022 Publish custom metric data to CloudWatch\n\u2022 Work with CloudWatch alarms\n\u2022 Use Amazon CloudWatch Events\nGet metrics from CloudWatch\nListing metrics\nTo list CloudWatch metrics, create a ListMetricsRequest and call the CloudWatchClient\u2019s\nlistMetrics method. You can use the ListMetricsRequest to filter the returned metrics by\nnamespace, metric name, or dimensions.", "mimetype": "text/plain", "start_char_idx": 334278, "end_char_idx": 338824, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2604f5b6-57b3-4c0e-a687-b8ae3c6acc49": {"__data__": {"id_": "2604f5b6-57b3-4c0e-a687-b8ae3c6acc49", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1bf9c4e8-1201-4385-9ed1-f4714f7ce405", "node_type": "1", "metadata": {}, "hash": "15f90945e74913661c58bbe5b45367dad9f4225ce6fd56cadb4ebc3aa09f1390", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3a9f6df5-5960-483f-87ff-7e198dff1ee4", "node_type": "1", "metadata": {}, "hash": "a80030c4817fd85fee841fe7df8400e799b491db9ee03ea34c5f95ebce683605", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CloudWatch alarms send\nnotifications or automatically make changes to the resources you are monitoring based on rules\nthat you define.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\nCloudWatch 177\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Get metrics from CloudWatch\n\u2022 Publish custom metric data to CloudWatch\n\u2022 Work with CloudWatch alarms\n\u2022 Use Amazon CloudWatch Events\nGet metrics from CloudWatch\nListing metrics\nTo list CloudWatch metrics, create a ListMetricsRequest and call the CloudWatchClient\u2019s\nlistMetrics method. You can use the ListMetricsRequest to filter the returned metrics by\nnamespace, metric name, or dimensions.\nNote\nA list of metrics and dimensions that are posted by AWS services can be found within the\nAmazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User\nGuide.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest;\nimport software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.Metric;\nCode\npublic static void listMets( CloudWatchClient cw, String namespace) {\nboolean done = false;\nString nextToken = null;\ntry {\nwhile(!done) {\nGet metrics from CloudWatch 178\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListMetricsResponse response;\nif (nextToken == null) {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.build();\nresponse = cw.listMetrics(request);\n} else {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.nextToken(nextToken)\n.build();\nresponse = cw.listMetrics(request);\n}\nfor (Metric metric : response.metrics()) {\nSystem.out.printf(\n\"Retrieved metric %s\", metric.metricName());\nSystem.out.println();\n}\nif(response.nextToken() == null) {\ndone = true;\n} else {\nnextToken = response.nextToken();\n}\n}\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nThe metrics are returned in a ListMetricsResponse by calling its getMetrics method.\nThe results may be paged. To retrieve the next batch of results, call nextToken on the response\nobject and use the token value to build a new request object. Then call the listMetrics method\nagain with the new request.\nSee the complete example on GitHub.\nGet metrics from CloudWatch 179\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMore information\n\u2022 ListMetrics in the Amazon CloudWatch API Reference\nPublish custom metric data to CloudWatch\nA number of AWS services publish their own metrics in namespaces beginning with \" AWS \" You can\nalso publish custom metric data using your own namespace (as long as it doesn\u2019t begin with \" AWS\n\").\nPublish custom metric data\nTo publish your own metric data, call the CloudWatchClient\u2019s putMetricData method with a\nPutMetricDataRequest. The PutMetricDataRequest must include the custom namespace to use\nfor the data, and information about the data point itself in a MetricDatum object.\nNote\nYou cannot specify a namespace that begins with \" AWS \". Namespaces that begin with \"\nAWS \" are reserved for use by Amazon Web Services products.", "mimetype": "text/plain", "start_char_idx": 337964, "end_char_idx": 341496, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3a9f6df5-5960-483f-87ff-7e198dff1ee4": {"__data__": {"id_": "3a9f6df5-5960-483f-87ff-7e198dff1ee4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2604f5b6-57b3-4c0e-a687-b8ae3c6acc49", "node_type": "1", "metadata": {}, "hash": "6d907a0cb9ee2d1d3bbff88993bf46d0b6c987769364c500852d2d14957c60d0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4506b57-3a8b-43b6-a960-5101883be3b7", "node_type": "1", "metadata": {}, "hash": "f8179c167c93c30ec1d3800bc438ac83e4234f8dae74e20f69d4be9078885cd5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Then call the listMetrics method\nagain with the new request.\nSee the complete example on GitHub.\nGet metrics from CloudWatch 179\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMore information\n\u2022 ListMetrics in the Amazon CloudWatch API Reference\nPublish custom metric data to CloudWatch\nA number of AWS services publish their own metrics in namespaces beginning with \" AWS \" You can\nalso publish custom metric data using your own namespace (as long as it doesn\u2019t begin with \" AWS\n\").\nPublish custom metric data\nTo publish your own metric data, call the CloudWatchClient\u2019s putMetricData method with a\nPutMetricDataRequest. The PutMetricDataRequest must include the custom namespace to use\nfor the data, and information about the data point itself in a MetricDatum object.\nNote\nYou cannot specify a namespace that begins with \" AWS \". Namespaces that begin with \"\nAWS \" are reserved for use by Amazon Web Services products.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.Dimension;\nimport software.amazon.awssdk.services.cloudwatch.model.MetricDatum;\nimport software.amazon.awssdk.services.cloudwatch.model.StandardUnit;\nimport software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport java.time.Instant;\nimport java.time.ZoneOffset;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nCode\npublic static void putMetData(CloudWatchClient cw, Double dataPoint ) {\nPublish custom metric data to CloudWatch 180\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nDimension dimension = Dimension.builder()\n.name(\"UNIQUE_PAGES\")\n.value(\"URLS\")\n.build();\n// Set an Instant object\nString time =\nZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT );\nInstant instant = Instant.parse(time);\nMetricDatum datum = MetricDatum.builder()\n.metricName(\"PAGES_VISITED\")\n.unit(StandardUnit.NONE)\n.value(dataPoint)\n.timestamp(instant)\n.dimensions(dimension).build();\nPutMetricDataRequest request = PutMetricDataRequest.builder()\n.namespace(\"SITE/TRAFFIC\")\n.metricData(datum).build();\ncw.putMetricData(request);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.printf(\"Successfully put data point %f\", dataPoint);\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Use Amazon CloudWatch Metrics in the Amazon CloudWatch User Guide.\n\u2022 AWS Namespaces in the Amazon CloudWatch User Guide.\n\u2022 PutMetricData in the Amazon CloudWatch API Reference.\nPublish custom metric data to CloudWatch 181\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWork with CloudWatch alarms\nCreate an alarm\nTo create an alarm based on a CloudWatch metric, call the CloudWatchClient\u2019s putMetricAlarm\nmethod with a PutMetricAlarmRequest filled with the alarm conditions.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.Dimension;\nimport software.amazon.awssdk.services.cloudwatch.model.PutMetricAlarmRequest;\nimport software.amazon.awssdk.services.cloudwatch.model.ComparisonOperator;\nimport software.amazon.awssdk.services.cloudwatch.model.Statistic;\nimport software.amazon.awssdk.services.cloudwatch.model.StandardUnit;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nCode\npublic static void putMetricAlarm(CloudWatchClient cw, String alarmName, String\ninstanceId) {\ntry {\nDimension dimension = Dimension.builder()\n.name(\"InstanceId\")\n.value(instanceId).build();\nPutMetricAlarmRequest request = PutMetricAlarmRequest.builder()\n.alarmName(alarmName)\n.comparisonOperator(\nComparisonOperator.GREATER_THAN_THRESHOLD)\n.evaluationPeriods(1)\n.metricName(\"CPUUtilization\")\n.namespace(\"AWS/EC2\")\n.period(60)\n.statistic(Statistic.AVERAGE)\n.threshold(70.0)\n.actionsEnabled(false)\n.alarmDescription(\n\"Alarm when server CPU utilization exceeds 70%\")\n.unit(StandardUnit.SECONDS)\n.dimensions(dimension)\nWork with CloudWatch alarms 182\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\ncw.putMetricAlarm(request);\nSystem.out.printf(\n\"Successfully created alarm with name %s\", alarmName);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nList alarms\nTo list the CloudWatch alarms that you have created, call the CloudWatchClient\u2019s\ndescribeAlarms method with a DescribeAlarmsRequest that you can use to set options for the\nresult.", "mimetype": "text/plain", "start_char_idx": 340569, "end_char_idx": 345267, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b4506b57-3a8b-43b6-a960-5101883be3b7": {"__data__": {"id_": "b4506b57-3a8b-43b6-a960-5101883be3b7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3a9f6df5-5960-483f-87ff-7e198dff1ee4", "node_type": "1", "metadata": {}, "hash": "a80030c4817fd85fee841fe7df8400e799b491db9ee03ea34c5f95ebce683605", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7998eff4-6958-426e-a167-bbabf80a4bc1", "node_type": "1", "metadata": {}, "hash": "0ec6c1136bafbd03edf6e6338458e620905894bdda439e9159a8324332c4932c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "List alarms\nTo list the CloudWatch alarms that you have created, call the CloudWatchClient\u2019s\ndescribeAlarms method with a DescribeAlarmsRequest that you can use to set options for the\nresult.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsRequest;\nimport software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.MetricAlarm;\nCode\npublic static void desCWAlarms( CloudWatchClient cw) {\ntry {\nboolean done = false;\nString newToken = null;\nwhile(!done) {\nDescribeAlarmsResponse response;\nif (newToken == null) {\nWork with CloudWatch alarms 183\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeAlarmsRequest request =\nDescribeAlarmsRequest.builder().build();\nresponse = cw.describeAlarms(request);\n} else {\nDescribeAlarmsRequest request = DescribeAlarmsRequest.builder()\n.nextToken(newToken)\n.build();\nresponse = cw.describeAlarms(request);\n}\nfor(MetricAlarm alarm : response.metricAlarms()) {\nSystem.out.printf(\"\\n Retrieved alarm %s\", alarm.alarmName());\n}\nif(response.nextToken() == null) {\ndone = true;\n} else {\nnewToken = response.nextToken();\n}\n}\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.printf(\"Done\");\n}\nThe list of alarms can be obtained by calling MetricAlarms on the DescribeAlarmsResponse that\nis returned by describeAlarms.\nThe results may be paged. To retrieve the next batch of results, call nextToken on the response\nobject and use the token value to build a new request object. Then call the describeAlarms\nmethod again with the new request.\nNote\nYou can also retrieve alarms for a specific metric by using the CloudWatchClient\u2019s\ndescribeAlarmsForMetric method. Its use is similar to describeAlarms.\nSee the complete example on GitHub.\nWork with CloudWatch alarms 184\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDelete alarms\nTo delete CloudWatch alarms, call the CloudWatchClient\u2019s deleteAlarms method with a\nDeleteAlarmsRequest containing one or more names of alarms that you want to delete.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsRequest;\nCode\npublic static void deleteCWAlarm(CloudWatchClient cw, String alarmName) {\ntry {\nDeleteAlarmsRequest request = DeleteAlarmsRequest.builder()\n.alarmNames(alarmName)\n.build();\ncw.deleteAlarms(request);\nSystem.out.printf(\"Successfully deleted alarm %s\", alarmName);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Using Amazon CloudWatch alarms in the Amazon CloudWatch User Guide\n\u2022 PutMetricAlarm in the Amazon CloudWatch API Reference\n\u2022 DescribeAlarms in the Amazon CloudWatch API Reference\n\u2022 DeleteAlarms in the Amazon CloudWatch API Reference\nWork with CloudWatch alarms 185\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse Amazon CloudWatch Events\nCloudWatch Events delivers a near real-time stream of system events that describe changes in AWS\nresources to Amazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step\nFunctions state machines, Amazon SNS topics, Amazon SQS queues, or built-in targets. You can\nmatch events and route them to one or more target functions or streams by using simple rules.\nAmazon EventBridge is the evolution of CloudWatch Events. Both services use the same API, so\nyou can continue using the CloudWatch Events client provided by the SDK or migrate to the SDK\nfor Java's EventBridge client for CloudWatch Events functionality. CloudWatch Events User Guide\ndocumentation and API reference are now available through the EventBridge documentation sites.\nAdd events\nTo add custom CloudWatch events, call the CloudWatchEventsClient\u2019s putEvents method\nwith a PutEventsRequest object that contains one or more PutEventsRequestEntry objects\nthat provide details about each event. You can specify several parameters for the entry such as the\nsource and type of the event, resources associated with the event, and so on.\nNote\nYou can specify a maximum of 10 events per call to putEvents.", "mimetype": "text/plain", "start_char_idx": 345076, "end_char_idx": 349612, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7998eff4-6958-426e-a167-bbabf80a4bc1": {"__data__": {"id_": "7998eff4-6958-426e-a167-bbabf80a4bc1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b4506b57-3a8b-43b6-a960-5101883be3b7", "node_type": "1", "metadata": {}, "hash": "f8179c167c93c30ec1d3800bc438ac83e4234f8dae74e20f69d4be9078885cd5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7a0b5048-d3d8-4144-87ca-f996353fb2b7", "node_type": "1", "metadata": {}, "hash": "4bdc196b1d000afc19f9dbace22627c18ad4cfd3debad280c2e387e90bdd3468", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "You can\nmatch events and route them to one or more target functions or streams by using simple rules.\nAmazon EventBridge is the evolution of CloudWatch Events. Both services use the same API, so\nyou can continue using the CloudWatch Events client provided by the SDK or migrate to the SDK\nfor Java's EventBridge client for CloudWatch Events functionality. CloudWatch Events User Guide\ndocumentation and API reference are now available through the EventBridge documentation sites.\nAdd events\nTo add custom CloudWatch events, call the CloudWatchEventsClient\u2019s putEvents method\nwith a PutEventsRequest object that contains one or more PutEventsRequestEntry objects\nthat provide details about each event. You can specify several parameters for the entry such as the\nsource and type of the event, resources associated with the event, and so on.\nNote\nYou can specify a maximum of 10 events per call to putEvents.\nImports\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequestEntry;\nCode\npublic static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn ) {\ntry {\nfinal String EVENT_DETAILS =\n\"{ \\\"key1\\\": \\\"value1\\\", \\\"key2\\\": \\\"value2\\\" }\";\nPutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder()\nUse Amazon CloudWatch Events 186\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.detail(EVENT_DETAILS)\n.detailType(\"sampleSubmitted\")\n.resources(resourceArn)\n.source(\"aws-sdk-java-cloudwatch-example\")\n.build();\nPutEventsRequest request = PutEventsRequest.builder()\n.entries(requestEntry)\n.build();\ncwe.putEvents(request);\nSystem.out.println(\"Successfully put CloudWatch event\");\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nAdd rules\nTo create or update a rule, call the CloudWatchEventsClient\u2019s putRule method with a\nPutRuleRequest with the name of the rule and optional parameters such as the event pattern,\nIAM role to associate with the rule, and a scheduling expression that describes how often the rule is\nrun.\nImports\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutRuleResponse;\nimport software.amazon.awssdk.services.cloudwatchevents.model.RuleState;\nCode\npublic static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String\nroleArn) {\ntry {\nPutRuleRequest request = PutRuleRequest.builder()\nUse Amazon CloudWatch Events 187\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.name(ruleName)\n.roleArn(roleArn)\n.scheduleExpression(\"rate(5 minutes)\")\n.state(RuleState.ENABLED)\n.build();\nPutRuleResponse response = cwe.putRule(request);\nSystem.out.printf(\n\"Successfully created CloudWatch events rule %s with arn %s\",\nroleArn, response.ruleArn());\n} catch (\nCloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nAdd targets\nTargets are the resources that are invoked when a rule is triggered. Example targets include\nAmazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state\nmachines, and built-in targets.\nTo add a target to a rule, call the CloudWatchEventsClient\u2019s putTargets method with a\nPutTargetsRequest containing the rule to update and a list of targets to add to the rule.", "mimetype": "text/plain", "start_char_idx": 348706, "end_char_idx": 352466, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7a0b5048-d3d8-4144-87ca-f996353fb2b7": {"__data__": {"id_": "7a0b5048-d3d8-4144-87ca-f996353fb2b7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7998eff4-6958-426e-a167-bbabf80a4bc1", "node_type": "1", "metadata": {}, "hash": "0ec6c1136bafbd03edf6e6338458e620905894bdda439e9159a8324332c4932c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5698fc7a-45c6-47e8-9dbc-841e5f8e4c60", "node_type": "1", "metadata": {}, "hash": "23c6fd52b72ff9e7f9188d08b33009adefb53ccae1ac0e91e68ffdaaba4f707a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Add targets\nTargets are the resources that are invoked when a rule is triggered. Example targets include\nAmazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state\nmachines, and built-in targets.\nTo add a target to a rule, call the CloudWatchEventsClient\u2019s putTargets method with a\nPutTargetsRequest containing the rule to update and a list of targets to add to the rule.\nImports\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsResponse;\nimport software.amazon.awssdk.services.cloudwatchevents.model.Target;\nCode\npublic static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String\nfunctionArn, String targetId ) {\ntry {\nTarget target = Target.builder()\nUse Amazon CloudWatch Events 188\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.arn(functionArn)\n.id(targetId)\n.build();\nPutTargetsRequest request = PutTargetsRequest.builder()\n.targets(target)\n.rule(ruleName)\n.build();\nPutTargetsResponse response = cwe.putTargets(request);\nSystem.out.printf(\n\"Successfully created CloudWatch events target for rule %s\",\nruleName);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Adding Events with PutEvents in the Amazon EventBridge User Guide\n\u2022 Schedule Expressions for Rules in the Amazon EventBridge User Guide\n\u2022 Event Types for CloudWatch Events in the Amazon EventBridge User Guide\n\u2022 Event Patterns in the Amazon EventBridge User Guide\n\u2022 PutEvents in the Amazon EventBridge API Reference\n\u2022 PutTargets in the Amazon EventBridge API Reference\n\u2022 PutRule in the Amazon EventBridge API Reference\nAWS database services and AWS SDK for Java 2.x\nAWS offers several database types: relational, key-value, in-memory, document, and several others.\nThe SDK for Java 2.x support varies depending the nature of the database service in AWS.\nSome database services, for example Amazon DynamoDB service, have web service APIs to manage\nthe AWS resource (database) as well as web service APIs to interact with the data. In the SDK for\nJava 2.x these types of services have dedicated service clients, for example DynamoDBClient.\nAWS database services 189\nAWS SDK for Java 2.x Developer Guide for version 2.x\nOther database services have web service APIs that interact with the resource, such the Amazon\nDocumentDB API (for cluster, instance and resource management), but do not have a web service\nAPI for working with the data. The SDK for Java 2.x has a corresponding DocDbClient interface for\nworking with the resource. However, you need another Java API, such as MongoDB for Java to work\nwith the data.\nUse the examples below to learn how you use the SDK for Java 2.x service clients with the different\ntypes of databases.\nAmazon DynamoDB examples\nWorking with the data Working with the database\nSDK service client: DynamoDbClient SDK service client: DynamoDbClient\nExample: React/Spring REST application using Examples: CreateTable, ListTables, DeleteTable\nDynamoDB\nExamples: Several DynamoDB examples\nSDK service client: DynamoDbEnhancedClient\nExample: React/Spring REST application using\nDynamoDB\nExamples: Several DynamoDB examples\n(names starting with 'Enhanced\")\nSee additional DynamoDB examples in the guided code examples section of this guide.\nAmazon RDS examples\nWorking with the data Working with the database\nNon-SDK API: JDBC, database-specific SQL SDK service client: RdsClient\nflavor; your code manages database connectio\nns or a connection pool.", "mimetype": "text/plain", "start_char_idx": 352058, "end_char_idx": 355836, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5698fc7a-45c6-47e8-9dbc-841e5f8e4c60": {"__data__": {"id_": "5698fc7a-45c6-47e8-9dbc-841e5f8e4c60", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7a0b5048-d3d8-4144-87ca-f996353fb2b7", "node_type": "1", "metadata": {}, "hash": "4bdc196b1d000afc19f9dbace22627c18ad4cfd3debad280c2e387e90bdd3468", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cd80467c-7146-4b84-b439-f62d57f2b603", "node_type": "1", "metadata": {}, "hash": "cad3929e4eef563758fa27a9c49b71be050ec2534396e04a450c082bc6ed73fc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use the examples below to learn how you use the SDK for Java 2.x service clients with the different\ntypes of databases.\nAmazon DynamoDB examples\nWorking with the data Working with the database\nSDK service client: DynamoDbClient SDK service client: DynamoDbClient\nExample: React/Spring REST application using Examples: CreateTable, ListTables, DeleteTable\nDynamoDB\nExamples: Several DynamoDB examples\nSDK service client: DynamoDbEnhancedClient\nExample: React/Spring REST application using\nDynamoDB\nExamples: Several DynamoDB examples\n(names starting with 'Enhanced\")\nSee additional DynamoDB examples in the guided code examples section of this guide.\nAmazon RDS examples\nWorking with the data Working with the database\nNon-SDK API: JDBC, database-specific SQL SDK service client: RdsClient\nflavor; your code manages database connectio\nns or a connection pool.\nAmazon DynamoDB 190\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWorking with the data Working with the database\nExample: React/Spring REST application using Examples: Several RdsClient examples\nMySQL\nAmazon Redshift examples\nWorking with the data Working with the database\nSDK service client: RedshiftDataClient SDK service client: RedshiftClient\nExamples: Several RedshiftDataClient Examples: Several RedshiftClient examples\nexamples\nExample: React/Spring REST application using\nRedshiftDataClient\nAmazon Aurora Serverless v2 examples\nWorking with the data Working with the database\nSDK service client: RdsDataClient SDK service client: RdsClient\nExample: React/Spring REST application using Examples: Several RdsClient examples\nRdsDataClient\nAmazon DocumentDB examples\nWorking with the data Working with the database\nNon-SDK API: MongoDB-specific Java library SDK service client: DocDbClient\n(for example MongoDB for Java); your code\nmanages database connections or a connectio\nn pool.\nAmazon Redshift 191\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWorking with the data Working with the database\nExamples: DocumentDB (Mongo) Developer\nGuide (select 'Java' tab)\nWork with DynamoDB\nThis section provides examples that show you how to work with DynamoDB.\nThe following examples use the standard, low-level DynamoDB client (DynamoDbClient) of the\nAWS SDK for Java 2.x.\n\u2022 the section called \u201cWork with tables in DynamoDB\u201d\n\u2022 the section called \u201cWork with items in DynamoDB\u201d\nThe SDK also offers the DynamoDB Enhanced Client that provides a high-level, object-oriented\napproach for working with DynamoDB. The following section discusses this client in depth.\n\u2022 the section called \u201c Map objects to DynamoDB items\u201d\nUse AWS account-based endpoints\nDynamoDB offers AWS account-based endpoints that can improve performance by using your AWS\naccount ID to streamline request routing.\nTo take advantage of this feature, you need to use version 2.28.4 or greater of version 2 of AWS\nSDK for Java. You can find the latest version of the SDK listed in the Maven central repository. After\na supported version of SDK is active, it automatically uses the new endpoints.\nIf you want to opt out of the account-based routing, you have four options:\n\u2022 Configure a DynamoDB service client with the AccountIdEndpointMode set to DISABLED.\n\u2022 Set an environment variable.\n\u2022 Set a JVM system property.\n\u2022 Update the shared AWS config file setting.\nDynamoDB 192\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following snippet is an example of how to disable account-based routing by configuring a\nDynamoDB service client:\nDynamoDbClient.builder()\n.accountIdEndpointMode(AccountIdEndpointMode.DISABLED)\n.build();\nThe AWS SDKs and Tools Reference Guide provides more information on the last three\nconfiguration options.\nWork with tables in DynamoDB\nTables are the containers for all items in a DynamoDB database. Before you can add or remove data\nfrom DynamoDB, you must create a table.\nFor each table, you must define:\n\u2022 A table name that is unique for your account and Region.\n\u2022 A primary key for which every value must be unique; no two items in your table can have the\nsame primary key value.\nA primary key can be simple, consisting of a single partition (HASH) key, or composite, consisting\nof a partition and a sort (RANGE) key.\nEach key value has an associated data type, enumerated by the ScalarAttributeType class.\nThe key value can be binary (B), numeric (N), or a string (S). For more information, see Naming\nRules and Data Types in the Amazon DynamoDB Developer Guide.\n\u2022 Provisioned throughput are values that define the number of reserved read/write capacity units\nfor the table.", "mimetype": "text/plain", "start_char_idx": 354978, "end_char_idx": 359527, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cd80467c-7146-4b84-b439-f62d57f2b603": {"__data__": {"id_": "cd80467c-7146-4b84-b439-f62d57f2b603", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5698fc7a-45c6-47e8-9dbc-841e5f8e4c60", "node_type": "1", "metadata": {}, "hash": "23c6fd52b72ff9e7f9188d08b33009adefb53ccae1ac0e91e68ffdaaba4f707a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c5ae0006-3bc3-401d-9b5d-82434b8394cc", "node_type": "1", "metadata": {}, "hash": "91548391d40076edc91f2ac8844b13a82e407b750765a49dd609c084ebd8fc39", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Work with tables in DynamoDB\nTables are the containers for all items in a DynamoDB database. Before you can add or remove data\nfrom DynamoDB, you must create a table.\nFor each table, you must define:\n\u2022 A table name that is unique for your account and Region.\n\u2022 A primary key for which every value must be unique; no two items in your table can have the\nsame primary key value.\nA primary key can be simple, consisting of a single partition (HASH) key, or composite, consisting\nof a partition and a sort (RANGE) key.\nEach key value has an associated data type, enumerated by the ScalarAttributeType class.\nThe key value can be binary (B), numeric (N), or a string (S). For more information, see Naming\nRules and Data Types in the Amazon DynamoDB Developer Guide.\n\u2022 Provisioned throughput are values that define the number of reserved read/write capacity units\nfor the table.\nNote\nAmazon DynamoDB pricing is based on the provisioned throughput values that you set\non your tables, so reserve only as much capacity as you think you\u2019ll need for your table.\nProvisioned throughput for a table can be modified at any time, so you can adjust capacity as\nyour needs change.\nWork with tables in DynamoDB 193\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a table\nUse the DynamoDbClient\u2019s createTable method to create a new DynamoDB table. You need\nto construct table attributes and a table schema, both of which are used to identify the primary\nkey of your table. You must also supply initial provisioned throughput values and a table name.\nNote\nIf a table with the name you chose already exists, a DynamoDbException is thrown.\nCreate a table with a simple primary key\nThis code creates a table with one attribute that is the table's simple primary key. the example uses\nAttributeDefinition and KeySchemaElement objects for the CreateTableRequest.\nImports\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;\nimport software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;\nimport software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;\nimport software.amazon.awssdk.services.dynamodb.model.KeyType;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;\nCode\npublic static String createTable(DynamoDbClient ddb, String tableName, String key)\n{\nDynamoDbWaiter dbWaiter = ddb.waiter();\nCreateTableRequest request = CreateTableRequest.builder()\n.attributeDefinitions(AttributeDefinition.builder()\nWork with tables in DynamoDB 194\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.attributeName(key)\n.attributeType(ScalarAttributeType.S)\n.build())\n.keySchema(KeySchemaElement.builder()\n.attributeName(key)\n.keyType(KeyType.HASH)\n.build())\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(new Long(10))\n.writeCapacityUnits(new Long(10))\n.build())\n.tableName(tableName)\n.build();\nString newTable =\"\";\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nnewTable = response.tableDescription().tableName();\nreturn newTable;\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nCreate a table with a composite primary key\nThe following example creates a table with two attributes. Both attributes are used for the\ncomposite primary key.", "mimetype": "text/plain", "start_char_idx": 358655, "end_char_idx": 362979, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c5ae0006-3bc3-401d-9b5d-82434b8394cc": {"__data__": {"id_": "c5ae0006-3bc3-401d-9b5d-82434b8394cc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cd80467c-7146-4b84-b439-f62d57f2b603", "node_type": "1", "metadata": {}, "hash": "cad3929e4eef563758fa27a9c49b71be050ec2534396e04a450c082bc6ed73fc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7868bd27-338c-4837-abff-ee89a92f4e88", "node_type": "1", "metadata": {}, "hash": "e246911c493ca9da6f250930a7c4a59935a49a5309e23fefc71b5a45c2eca145", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Create a table with a composite primary key\nThe following example creates a table with two attributes. Both attributes are used for the\ncomposite primary key.\nImports\nWork with tables in DynamoDB 195\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;\nimport software.amazon.awssdk.services.dynamodb.model.KeyType;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;\nimport software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nCode\npublic static String createTableComKey(DynamoDbClient ddb, String tableName) {\nCreateTableRequest request = CreateTableRequest.builder()\n.attributeDefinitions(\nAttributeDefinition.builder()\n.attributeName(\"Language\")\n.attributeType(ScalarAttributeType.S)\n.build(),\nAttributeDefinition.builder()\n.attributeName(\"Greeting\")\n.attributeType(ScalarAttributeType.S)\n.build())\n.keySchema(\nKeySchemaElement.builder()\n.attributeName(\"Language\")\n.keyType(KeyType.HASH)\n.build(),\nKeySchemaElement.builder()\n.attributeName(\"Greeting\")\n.keyType(KeyType.RANGE)\n.build())\n.provisionedThroughput(\nProvisionedThroughput.builder()\n.readCapacityUnits(new Long(10))\n.writeCapacityUnits(new Long(10)).build())\n.tableName(tableName)\n.build();\nString tableId = \"\";\ntry {\nWork with tables in DynamoDB 196\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateTableResponse result = ddb.createTable(request);\ntableId = result.tableDescription().tableId();\nreturn tableId;\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nList tables\nYou can list the tables in a particular Region by calling the DynamoDbClient\u2019s listTables\nmethod.\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport java.util.List;\nCode\npublic static void listAllTables(DynamoDbClient ddb){\nboolean moreTables = true;\nString lastName = null;\nwhile(moreTables) {\nWork with tables in DynamoDB 197\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nListTablesResponse response = null;\nif (lastName == null) {\nListTablesRequest request = ListTablesRequest.builder().build();\nresponse = ddb.listTables(request);\n} else {\nListTablesRequest request = ListTablesRequest.builder()\n.exclusiveStartTableName(lastName).build();\nresponse = ddb.listTables(request);\n}\nList tableNames = response.tableNames();\nif (tableNames.size() > 0) {\nfor (String curName : tableNames) {\nSystem.out.format(\"* %s\\n\", curName);\n}\n} else {\nSystem.out.println(\"No tables found!\");\nSystem.exit(0);\n}\nlastName = response.lastEvaluatedTableName();\nif (lastName == null) {\nmoreTables = false;\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSystem.out.println(\"\\nDone!\");\n}\nBy default, up to 100 tables are returned per call\u2014use lastEvaluatedTableName on the\nreturned ListTablesResponse object to get the last table that was evaluated. You can use this\nvalue to start the listing after the last returned value of the previous listing.\nSee the complete example on GitHub.\nDescribe (get information about) a table\nUse the DynamoDbClient\u2019s describeTable method to get information about a table.\nWork with tables in DynamoDB 198\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.", "mimetype": "text/plain", "start_char_idx": 362821, "end_char_idx": 367010, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7868bd27-338c-4837-abff-ee89a92f4e88": {"__data__": {"id_": "7868bd27-338c-4837-abff-ee89a92f4e88", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c5ae0006-3bc3-401d-9b5d-82434b8394cc", "node_type": "1", "metadata": {}, "hash": "91548391d40076edc91f2ac8844b13a82e407b750765a49dd609c084ebd8fc39", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d7a1f09a-124b-4e30-8cf1-4e631ceaf8a7", "node_type": "1", "metadata": {}, "hash": "e7c8cb13d8e6d39b6676f7ce88f370e77fc44d2d9e760efdf4eeff447d393d91", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nSystem.exit(0);\n}\nlastName = response.lastEvaluatedTableName();\nif (lastName == null) {\nmoreTables = false;\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSystem.out.println(\"\\nDone!\");\n}\nBy default, up to 100 tables are returned per call\u2014use lastEvaluatedTableName on the\nreturned ListTablesResponse object to get the last table that was evaluated. You can use this\nvalue to start the listing after the last returned value of the previous listing.\nSee the complete example on GitHub.\nDescribe (get information about) a table\nUse the DynamoDbClient\u2019s describeTable method to get information about a table.\nWork with tables in DynamoDB 198\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;\nimport software.amazon.awssdk.services.dynamodb.model.TableDescription;\nimport java.util.List;\nCode\npublic static void describeDymamoDBTable(DynamoDbClient ddb,String tableName ) {\nDescribeTableRequest request = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nTableDescription tableInfo =\nddb.describeTable(request).table();\nif (tableInfo != null) {\nSystem.out.format(\"Table name : %s\\n\",\ntableInfo.tableName());\nSystem.out.format(\"Table ARN : %s\\n\",\ntableInfo.tableArn());\nSystem.out.format(\"Status : %s\\n\",\ntableInfo.tableStatus());\nSystem.out.format(\"Item count : %d\\n\",\ntableInfo.itemCount().longValue());\nSystem.out.format(\"Size (bytes): %d\\n\",\ntableInfo.tableSizeBytes().longValue());\nProvisionedThroughputDescription throughputInfo =\nWork with tables in DynamoDB 199\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntableInfo.provisionedThroughput();\nSystem.out.println(\"Throughput\");\nSystem.out.format(\" Read Capacity : %d\\n\",\nthroughputInfo.readCapacityUnits().longValue());\nSystem.out.format(\" Write Capacity: %d\\n\",\nthroughputInfo.writeCapacityUnits().longValue());\nList attributes =\ntableInfo.attributeDefinitions();\nSystem.out.println(\"Attributes\");\nfor (AttributeDefinition a : attributes) {\nSystem.out.format(\" %s (%s)\\n\",\na.attributeName(), a.attributeType());\n}\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"\\nDone!\");\n}\nSee the complete example on GitHub.\nModify (update) a table\nYou can modify your table\u2019s provisioned throughput values at any time by calling the\nDynamoDbClient\u2019s updateTable method.\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest;\nWork with tables in DynamoDB 200\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nCode\npublic static void updateDynamoDBTable(DynamoDbClient ddb,\nString tableName,\nLong readCapacity,\nLong writeCapacity) {\nSystem.out.format(\n\"Updating %s with new provisioned throughput values\\n\",\ntableName);\nSystem.out.format(\"Read capacity : %d\\n\", readCapacity);\nSystem.out.format(\"Write capacity : %d\\n\", writeCapacity);\nProvisionedThroughput tableThroughput = ProvisionedThroughput.builder()\n.readCapacityUnits(readCapacity)\n.writeCapacityUnits(writeCapacity)\n.build();\nUpdateTableRequest request = UpdateTableRequest.builder()\n.provisionedThroughput(tableThroughput)\n.tableName(tableName)\n.build();\ntry {\nddb.updateTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done!\");\n}\nSee the complete example on GitHub.\nDelete a table\nTo delete a table, call DynamoDbClient\u2019s deleteTable method and provide the table\u2019s name.\nWork with tables in DynamoDB 201\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.", "mimetype": "text/plain", "start_char_idx": 366166, "end_char_idx": 370690, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d7a1f09a-124b-4e30-8cf1-4e631ceaf8a7": {"__data__": {"id_": "d7a1f09a-124b-4e30-8cf1-4e631ceaf8a7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7868bd27-338c-4837-abff-ee89a92f4e88", "node_type": "1", "metadata": {}, "hash": "e246911c493ca9da6f250930a7c4a59935a49a5309e23fefc71b5a45c2eca145", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cf3c96f4-c37b-4f57-863e-843987b94137", "node_type": "1", "metadata": {}, "hash": "4f5315ac400457c8b837a6885c5eccac77598731e453f213d26443a297a3edd9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\nSee the complete example on GitHub.\nDelete a table\nTo delete a table, call DynamoDbClient\u2019s deleteTable method and provide the table\u2019s name.\nWork with tables in DynamoDB 201\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf the named table doesn\u2019t exist for your account and Region, a\nResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;\nCode\npublic static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {\nDeleteTableRequest request = DeleteTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nddb.deleteTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(tableName +\" was successfully deleted!\");\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Guidelines for Working with Tables in the Amazon DynamoDB Developer Guide\n\u2022 Working with Tables in DynamoDB in the Amazon DynamoDB Developer Guide\nWork with tables in DynamoDB 202\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWork with items in DynamoDB\nIn DynamoDB, an item is a collection of attributes, each of which has a name and a value. An\nattribute value can be a scalar, set, or document type. For more information, see Naming Rules and\nData Types in the Amazon DynamoDB Developer Guide.\nRetrieve (get) an item from a table\nCall the DynamoDbClient\u2019s getItem method and pass it a GetItemRequest object with the table\nname and primary key value of the item you want. It returns a GetItemResponse object with\nall of the attributes for that item. You can specify one or more projection expressions in the\nGetItemRequest to retrieve specific attributes.\nYou can use the returned GetItemResponse object\u2019s item() method to retrieve a Map of key\n(String) and value (AttributeValue) pairs that are associated with the item.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.GetItemRequest;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nCode\npublic static void getDynamoDBItem(DynamoDbClient ddb,String tableName,String\nkey,String keyVal ) {\nHashMap keyToGet = new HashMap();\nkeyToGet.put(key, AttributeValue.builder()\n.s(keyVal).build());\nGetItemRequest request = GetItemRequest.builder()\n.key(keyToGet)\n.tableName(tableName)\n.build();\nWork with items in DynamoDB 203\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nMap returnedItem = ddb.getItem(request).item();\nif (returnedItem != null) {\nSet keys = returnedItem.keySet();\nSystem.out.println(\"Amazon DynamoDB table attributes: \\n\");\nfor (String key1 : keys) {\nSystem.out.format(\"%s: %s\\n\", key1,\nreturnedItem.get(key1).toString());\n}\n} else {\nSystem.out.format(\"No item found with the key %s!\\n\", key);\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nRetrieve (get) an item from a table using the asynchronous client\nInvoke the getItem method of the DynamoDbAsyncClient and pass it a GetItemRequest object\nwith the table name and primary key value of the item you want.\nYou can return a Collection instance with all of the attributes for that item (refer to the following\nexample).", "mimetype": "text/plain", "start_char_idx": 370352, "end_char_idx": 374062, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cf3c96f4-c37b-4f57-863e-843987b94137": {"__data__": {"id_": "cf3c96f4-c37b-4f57-863e-843987b94137", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d7a1f09a-124b-4e30-8cf1-4e631ceaf8a7", "node_type": "1", "metadata": {}, "hash": "e7c8cb13d8e6d39b6676f7ce88f370e77fc44d2d9e760efdf4eeff447d393d91", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7230461e-4629-4114-8211-5c39af38b6b5", "node_type": "1", "metadata": {}, "hash": "c9b7f7cacf2e6f76da254e818cb742bf6fc57a2c00b6c24082daa84a2c2237e0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Retrieve (get) an item from a table using the asynchronous client\nInvoke the getItem method of the DynamoDbAsyncClient and pass it a GetItemRequest object\nwith the table name and primary key value of the item you want.\nYou can return a Collection instance with all of the attributes for that item (refer to the following\nexample).\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.GetItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nWork with items in DynamoDB 204\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\npublic static void getItem(DynamoDbAsyncClient client, String tableName, String\nkey, String keyVal) {\nHashMap keyToGet =\nnew HashMap();\nkeyToGet.put(key, AttributeValue.builder()\n.s(keyVal).build());\ntry {\n// Create a GetItemRequest instance\nGetItemRequest request = GetItemRequest.builder()\n.key(keyToGet)\n.tableName(tableName)\n.build();\n// Invoke the DynamoDbAsyncClient object's getItem\njava.util.Collection returnedItem =\nclient.getItem(request).join().item().values();\n// Convert Set to Map\nMap map =\nreturnedItem.stream().collect(Collectors.toMap(AttributeValue::s, s->s));\nSet keys = map.keySet();\nfor (String sinKey : keys) {\nSystem.out.format(\"%s: %s\\n\", sinKey, map.get(sinKey).toString());\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSee the complete example on GitHub.\nAdd a new item to a table\nCreate a Map of key-value pairs that represent the item\u2019s attributes. These must include values for\nthe table\u2019s primary key fields. If the item identified by the primary key already exists, its fields are\nupdated by the request.\nWork with items in DynamoDB 205\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nIf the named table doesn\u2019t exist for your account and region, a ResourceNotFoundException\nis thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.PutItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport java.util.HashMap;\nCode\npublic static void putItemInTable(DynamoDbClient ddb,\nString tableName,\nString key,\nString keyVal,\nString albumTitle,\nString albumTitleValue,\nString awards,\nString awardVal,\nString songTitle,\nString songTitleVal){\nHashMap itemValues = new\nHashMap();\n// Add all content to the table\nitemValues.put(key, AttributeValue.builder().s(keyVal).build());\nitemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());\nitemValues.put(albumTitle,\nAttributeValue.builder().s(albumTitleValue).build());\nitemValues.put(awards, AttributeValue.builder().s(awardVal).build());\nPutItemRequest request = PutItemRequest.builder()\n.tableName(tableName)\n.item(itemValues)\nWork with items in DynamoDB 206\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\ntry {\nddb.putItem(request);\nSystem.out.println(tableName +\" was successfully updated\");\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be found.\n\\n\", tableName);\nSystem.err.println(\"Be sure that it exists and that you've typed its name\ncorrectly!\");\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nUpdate an existing item in a table\nYou can update an attribute for an item that already exists in a table by using the\nDynamoDbClient\u2019s updateItem method, providing a table name, primary key value, and a map of\nfields to update.\nNote\nIf the named table doesn\u2019t exist for your account and region, or if the item identified by the\nprimary key you passed in doesn\u2019t exist, a ResourceNotFoundException is thrown.", "mimetype": "text/plain", "start_char_idx": 373732, "end_char_idx": 378067, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7230461e-4629-4114-8211-5c39af38b6b5": {"__data__": {"id_": "7230461e-4629-4114-8211-5c39af38b6b5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cf3c96f4-c37b-4f57-863e-843987b94137", "node_type": "1", "metadata": {}, "hash": "4f5315ac400457c8b837a6885c5eccac77598731e453f213d26443a297a3edd9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "91596306-ff18-457c-bee4-486932861f98", "node_type": "1", "metadata": {}, "hash": "f54d51d4e1ad0a5e9ce09531cbdec50cbdaf5a134f7da603f14079079c4d35fd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\\n\", tableName);\nSystem.err.println(\"Be sure that it exists and that you've typed its name\ncorrectly!\");\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nUpdate an existing item in a table\nYou can update an attribute for an item that already exists in a table by using the\nDynamoDbClient\u2019s updateItem method, providing a table name, primary key value, and a map of\nfields to update.\nNote\nIf the named table doesn\u2019t exist for your account and region, or if the item identified by the\nprimary key you passed in doesn\u2019t exist, a ResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeAction;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;\nWork with items in DynamoDB 207\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport java.util.HashMap;\nCode\npublic static void updateTableItem(DynamoDbClient ddb,\nString tableName,\nString key,\nString keyVal,\nString name,\nString updateVal){\nHashMap itemKey = new HashMap();\nitemKey.put(key, AttributeValue.builder().s(keyVal).build());\nHashMap updatedValues =\nnew HashMap();\n// Update the column specified by name with updatedVal\nupdatedValues.put(name, AttributeValueUpdate.builder()\n.value(AttributeValue.builder().s(updateVal).build())\n.action(AttributeAction.PUT)\n.build());\nUpdateItemRequest request = UpdateItemRequest.builder()\n.tableName(tableName)\n.key(itemKey)\n.attributeUpdates(updatedValues)\n.build();\ntry {\nddb.updateItem(request);\n} catch (ResourceNotFoundException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done!\");\n}\nWork with items in DynamoDB 208\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example on GitHub.\nDelete an existing item in a table\nYou can delete an item that exists in a table by using the DynamoDbClient\u2019s deleteItem method\nand providing a table name as well as the primary key value.\nNote\nIf the named table doesn\u2019t exist for your account and region, or if the item identified by the\nprimary key you passed in doesn\u2019t exist, a ResourceNotFoundException is thrown.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport java.util.HashMap;\nCode\npublic static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String\nkey, String keyVal) {\nHashMap keyToGet =\nnew HashMap();\nkeyToGet.put(key, AttributeValue.builder()\n.s(keyVal)\n.build());\nDeleteItemRequest deleteReq = DeleteItemRequest.builder()\n.tableName(tableName)\n.key(keyToGet)\n.build();\ntry {\nddb.deleteItem(deleteReq);\n} catch (DynamoDbException e) {\nWork with items in DynamoDB 209\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Guidelines for Working with Items in the Amazon DynamoDB Developer Guide\n\u2022 Working with Items in DynamoDB in the Amazon DynamoDB Developer Guide\nMap Java objects to DynamoDB items with the AWS SDK for Java 2.x\nThe DynamoDB Enhanced Client API is a high-level library that is the successor to the\nDynamoDBMapper class of in the SDK for Java v1.x. It offers a straightforward way to map\nclient-side classes to DynamoDB tables. You define the relationships between tables and their\ncorresponding data classes in your code. After you define those relationships, you can intuitively\nperform various create, read, update, or delete (CRUD) operations on tables or items in DynamoDB.\nThe DynamoDB Enhanced Client API also includes the Enhanced Document API that enables you to\nwork with document-type items that do not follow a defined schema.\nThe DynamoDB Enhanced Client API is discussed in the following topics.", "mimetype": "text/plain", "start_char_idx": 377414, "end_char_idx": 382073, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "91596306-ff18-457c-bee4-486932861f98": {"__data__": {"id_": "91596306-ff18-457c-bee4-486932861f98", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7230461e-4629-4114-8211-5c39af38b6b5", "node_type": "1", "metadata": {}, "hash": "c9b7f7cacf2e6f76da254e818cb742bf6fc57a2c00b6c24082daa84a2c2237e0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "682e836e-43fc-4e9d-98bf-40185f053000", "node_type": "1", "metadata": {}, "hash": "e6942c88c6a5036f563edafca3b8ad45f3ca733ce2dc78858944c9bfc034bd1d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "More information\n\u2022 Guidelines for Working with Items in the Amazon DynamoDB Developer Guide\n\u2022 Working with Items in DynamoDB in the Amazon DynamoDB Developer Guide\nMap Java objects to DynamoDB items with the AWS SDK for Java 2.x\nThe DynamoDB Enhanced Client API is a high-level library that is the successor to the\nDynamoDBMapper class of in the SDK for Java v1.x. It offers a straightforward way to map\nclient-side classes to DynamoDB tables. You define the relationships between tables and their\ncorresponding data classes in your code. After you define those relationships, you can intuitively\nperform various create, read, update, or delete (CRUD) operations on tables or items in DynamoDB.\nThe DynamoDB Enhanced Client API also includes the Enhanced Document API that enables you to\nwork with document-type items that do not follow a defined schema.\nThe DynamoDB Enhanced Client API is discussed in the following topics.\n\u2022 Get Started using the DynamoDB Enhanced Client API\n\u2022 Learn the basics of the DynamoDB Enhanced Client API\n\u2022 Use advanced mapping features\n\u2022 Work with JSON documents with the Enhanced Document API for DynamoDB\n\u2022 Use extensions\n\u2022 Use the DynamoDB Enhanced Client API asynchronously\n\u2022 Data class annotations\nGet Started using the DynamoDB Enhanced Client API\nThe following tutorial introduces you to fundamentals that you need to work with the DynamoDB\nEnhanced Client API.\nMap objects to DynamoDB items 210\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAdd dependencies\nTo begin working with the DynamoDB Enhanced Client API in your project, add a dependency on\nthe dynamodb-enhanced Maven artifact. This is shown in the following examples.\nMaven\n\n\n\n\nsoftware.amazon.awssdk\nbom\n\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ndynamodb-enhanced\n\n\n...\n\nPerform a search of the Maven central repository for the latest version and replace \nwith this value.\nGradle\nrepositories {\nmavenCentral()\n}\ndependencies {\nimplementation(platform(\"software.amazon.awssdk:bom:\"))\nimplementation(\"software.amazon.awssdk:dynamodb-enhanced\")\n...\n}\nMap objects to DynamoDB items 211\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPerform a search of the Maven central repository for the latest version and replace \nwith this value.\nGenerate a TableSchema from a data class\nA TableSchema enables the enhanced client to map DynamoDB attribute values to and from your\nclient-side classes. In this tutorial, you learn about TableSchemas derived from a static data class\nand generated from code by using a builder.\nUse an annotated data class\nThe SDK for Java 2.x includes a set of annotations that you can use with a data class to quickly\ngenerate a TableSchema for mapping your classes to tables.\nStart by creating a data class that conforms to the JavaBean specification. The specification\nrequires that a class has a no-argument public constructor and has getters and setters for\neach attribute in the class. Include a class-level annotation to indicate that the data class is a\nDynamoDbBean. Also, at a minimum, include a DynamoDbPartitionKey annotation on the getter\nor setter for the primary key attribute.\nYou can apply attribute-level annotations to getters or setters, but not both.\nNote\nThe term property is normally used for a value encapsulated in a JavaBean. However, this\nguide uses the term attribute instead, to be consistent with the terminology used by\nDynamoDB.\nThe following Customer class shows annotations that link the class definition to a DynamoDB\ntable.", "mimetype": "text/plain", "start_char_idx": 381148, "end_char_idx": 384976, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "682e836e-43fc-4e9d-98bf-40185f053000": {"__data__": {"id_": "682e836e-43fc-4e9d-98bf-40185f053000", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "91596306-ff18-457c-bee4-486932861f98", "node_type": "1", "metadata": {}, "hash": "f54d51d4e1ad0a5e9ce09531cbdec50cbdaf5a134f7da603f14079079c4d35fd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1ea05da0-6897-4ecc-be81-3df8ea758bb7", "node_type": "1", "metadata": {}, "hash": "3408df058b7727f98a8bb1fac7f3962a7d03a4b7c159a7c69e5877c8a7c55969", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Start by creating a data class that conforms to the JavaBean specification. The specification\nrequires that a class has a no-argument public constructor and has getters and setters for\neach attribute in the class. Include a class-level annotation to indicate that the data class is a\nDynamoDbBean. Also, at a minimum, include a DynamoDbPartitionKey annotation on the getter\nor setter for the primary key attribute.\nYou can apply attribute-level annotations to getters or setters, but not both.\nNote\nThe term property is normally used for a value encapsulated in a JavaBean. However, this\nguide uses the term attribute instead, to be consistent with the terminology used by\nDynamoDB.\nThe following Customer class shows annotations that link the class definition to a DynamoDB\ntable.\nCustomer class\npackage org.example.tests.model;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;\nMap objects to DynamoDB items 212\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;\nimport java.time.Instant;\n@DynamoDbBean\npublic class Customer {\nprivate String id;\nprivate String name;\nprivate String email;\nprivate Instant regDate;\n@DynamoDbPartitionKey\npublic String getId() { return this.id; }\npublic void setId(String id) { this.id = id; }\npublic String getCustName() { return this.name; }\npublic void setCustName(String name) { this.name = name; }\n@DynamoDbSortKey\npublic String getEmail() { return this.email; }\npublic void setEmail(String email) { this.email = email; }\npublic Instant getRegistrationDate() { return this.regDate; }\npublic void setRegistrationDate(Instant registrationDate) { this.regDate =\nregistrationDate; }\n@Override\npublic String toString() {\nreturn \"Customer [id=\" + id + \", name=\" + name + \", email=\" + email\n+ \", regDate=\" + regDate + \"]\";\n}\n}\nAfter you have created an annotated data class, use it to create the TableSchema, as shown in the\nfollowing snippet.\nstatic final TableSchema customerTableSchema =\nTableSchema.fromBean(Customer.class);\nMap objects to DynamoDB items 213\nAWS SDK for Java 2.x Developer Guide for version 2.x\nA TableSchema is designed to be static and immutable. You can usually instantiate it at class-load\ntime.\nThe static TableSchema.fromBean() factory method introspects the bean to generate the\nmapping of data class attributes (properties) to and from DynamoDB attributes.\nFor an example of working with a data model made up of several data classes, see the Person\nclass in the ??? section.\nUse a builder\nYou can skip the cost of bean introspection if you define the table schema in code. If you code the\nschema, your class does not need to follow JavaBean naming standards nor does it need to be\nannotated. The following example uses a builder and is equivalent to the Customer class example\nthat uses annotations.\nstatic final TableSchema customerTableSchema =\nTableSchema.builder(Customer.class)\n.newItemSupplier(Customer::new)\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(Customer::getId)\n.setter(Customer::setId)\n.tags(StaticAttributeTags.primaryPartitionKey()))\n.addAttribute(String.class, a -> a.name(\"email\")\n.getter(Customer::getEmail)\n.setter(Customer::setEmail)\n.tags(StaticAttributeTags.primarySortKey()))\n.addAttribute(String.class, a -> a.name(\"name\")\n.getter(Customer::getCustName)\n.setter(Customer::setCustName))\n.addAttribute(Instant.class, a -> a.name(\"registrationDate\")\n.getter(Customer::getRegistrationDate)\n.setter(Customer::setRegistrationDate))\n.build();\nCreate an enhanced client and DynamoDbTable\nCreate an enhanced client\nThe DynamoDbEnhancedClient class or its asynchronous counterpart,\nDynamoDbEnhancedAsyncClient, is the entry point to working with the DynamoDB Enhanced\nClient API.\nMap objects to DynamoDB items 214\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe enhanced client requires a standard DynamoDbClient to perform work. The API offers two\nways to create a DynamoDbEnhancedClient instance. The first option, shown in the following\nsnippet, creates a standard DynamoDbClient with default settings picked up from configuration\nsettings.\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.create();\nIf you want to configure the underlying standard client, you can supply it to the enhanced client's\nbuilder method as shown in the following snippet.\n// Configure an instance of the standard DynamoDbClient.", "mimetype": "text/plain", "start_char_idx": 384195, "end_char_idx": 388739, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1ea05da0-6897-4ecc-be81-3df8ea758bb7": {"__data__": {"id_": "1ea05da0-6897-4ecc-be81-3df8ea758bb7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "682e836e-43fc-4e9d-98bf-40185f053000", "node_type": "1", "metadata": {}, "hash": "e6942c88c6a5036f563edafca3b8ad45f3ca733ce2dc78858944c9bfc034bd1d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34f6d956-cf0d-4b65-a5f7-fdadcfaec330", "node_type": "1", "metadata": {}, "hash": "6760f74e0818785d607289e133d79ca607ea51e66644b39742124283358a13b7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Map objects to DynamoDB items 214\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe enhanced client requires a standard DynamoDbClient to perform work. The API offers two\nways to create a DynamoDbEnhancedClient instance. The first option, shown in the following\nsnippet, creates a standard DynamoDbClient with default settings picked up from configuration\nsettings.\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.create();\nIf you want to configure the underlying standard client, you can supply it to the enhanced client's\nbuilder method as shown in the following snippet.\n// Configure an instance of the standard DynamoDbClient.\nDynamoDbClient standardClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.credentialsProvider(ProfileCredentialsProvider.create())\n.build();\n// Use the configured standard client with the enhanced client.\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(standardClient)\n.build();\nCreate a DynamoDbTable instance\nThink of a DynamoDbTable as the client-side representation of a DynamoDB table that uses the\nmapping functionality provided by a TableSchema. The DynamoDbTable class provides methods\nfor CRUD operations that let you interact with a single DynamoDB table.\nDynamoDbTable is a generic class that takes a single type argument, whether it is a custom\nclass or an EnhancedDocument when working with document-type items. This argument type\nestablishes the relationship between the class that you use and the single DynamoDB table.\nUse the table() factory method of the DynamoDbEnhancedClient to create a DynamoDbTable\ninstance as shown in the following snippet.\nstatic final DynamoDbTable customerTable =\nenhancedClient.table(\"Customer\", TableSchema.fromBean(Customer.class));\nDynamoDbTable instances are candidates for singletons because they are immutable and can be\nused throughout your application.\nMap objects to DynamoDB items 215\nAWS SDK for Java 2.x Developer Guide for version 2.x\nYour code now has an in-memory representation of a DynamoDB table that can work with\nCustomer instances. The actual DynamoDB table might or might not exist. If the table named\nCustomer already exists, you can begin performing CRUD operations against it. If it doesn't exist,\nuse the DynamoDbTable instance to create the table as discussed in the next section.\nCreate a DynamoDB table if needed\nAfter you have created a DynamoDbTable instance, use it to perform a one-time creation of a table\nin DynamoDB.\nCreate table example code\nThe following example creates a DynamoDB table based on the Customer data class.\nThis example creates a DynamoDB table with the name Customer\u2014identical to the class name\n\u2014but the table name can be something else. Whatever you name the table, you must use\nthis name in additional applications to work with the table. Supply this name to the table()\nmethod anytime you create another DynamoDbTable object in order to work with the underlying\nDynamoDB table.\nThe Java lambda parameter, builder, passed to the createTable method lets you customize\nthe table. In this example, provisioned throughput is configured. If you want to use default settings\nwhen you create a table, skip the builder as shown in the following snippet.\ncustomerTable.createTable();\nWhen default settings are used, values for provisioned throughput are not set. Instead, the billing\nmode for the table is set to on-demand.\nThe example also uses a DynamoDbWaiter before attempting to print out the table name received\nin the response. The creation of a table takes some time. Therefore, using a waiter means you don't\nhave to write logic that polls the DynamoDB service to see if the table exists before using the table.\nImports\nimport com.example.dynamodb.Customer;\nimport software.amazon.awssdk.core.internal.waiters.ResponseOrException;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;\nimport software.amazon.awssdk.enhanced.dynamodb.TableSchema;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;\nMap objects to DynamoDB items 216\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;\nCode\npublic static void createCustomerTable(DynamoDbTable customerTable,\nDynamoDbClient standardClient) {\n// Create the DynamoDB table using the 'customerTable' DynamoDbTable instance.", "mimetype": "text/plain", "start_char_idx": 388087, "end_char_idx": 392563, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "34f6d956-cf0d-4b65-a5f7-fdadcfaec330": {"__data__": {"id_": "34f6d956-cf0d-4b65-a5f7-fdadcfaec330", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1ea05da0-6897-4ecc-be81-3df8ea758bb7", "node_type": "1", "metadata": {}, "hash": "3408df058b7727f98a8bb1fac7f3962a7d03a4b7c159a7c69e5877c8a7c55969", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b706988-3999-437e-965c-2fa0c6558f6e", "node_type": "1", "metadata": {}, "hash": "49c1880c6e1ffa413179ef65db15ee6a855573b157736bf854ca18d470845273", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Therefore, using a waiter means you don't\nhave to write logic that polls the DynamoDB service to see if the table exists before using the table.\nImports\nimport com.example.dynamodb.Customer;\nimport software.amazon.awssdk.core.internal.waiters.ResponseOrException;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;\nimport software.amazon.awssdk.enhanced.dynamodb.TableSchema;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;\nMap objects to DynamoDB items 216\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;\nCode\npublic static void createCustomerTable(DynamoDbTable customerTable,\nDynamoDbClient standardClient) {\n// Create the DynamoDB table using the 'customerTable' DynamoDbTable instance.\ncustomerTable.createTable(builder -> builder\n.provisionedThroughput(b -> b\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n);\n// The DynamoDbClient instance (named 'standardClient') passed to the builder for\nthe DynamoDbWaiter is the same instance\n// that was passed to the builder of the DynamoDbEnhancedClient instance that we\ncreated previously.\n// By using the same instance, it ensures that the same Region that was configured\non the standard DynamoDbClient\n// instance is used for other service clients that accept a DynamoDbClient during\nconstruction.\ntry (DynamoDbWaiter waiter =\nDynamoDbWaiter.builder().client(standardClient).build()) { // DynamoDbWaiter is\nAutocloseable\nResponseOrException response = waiter\n.waitUntilTableExists(builder ->\nbuilder.tableName(\"Customer\").build())\n.matched();\nDescribeTableResponse tableDescription = response.response().orElseThrow(\n() -> new RuntimeException(\"Customer table was not created.\"));\n// The actual error can be inspected in response.exception()\nlogger.info(\"Customer table was created.\");\n}\n}\nNote\nA DynamoDB table's attribute names begin with a lowercase letter when the table is\ngenerated from a data class. If you want the table's attribute name to begin with an\nuppercase letter, use the @DynamoDbAttribute(NAME) annotation and provide the name\nyou want as a parameter.\nMap objects to DynamoDB items 217\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPerform operations\nAfter the table is created, use the DynamoDbTable instance to perform operations against the\nDynamoDB table.\nIn the following example, a singleton DynamoDbTable is passed as a parameter along\nwith a Customer data class instance to add a new item to the table.\npublic static void putItemExample(DynamoDbTable customerTable, Customer\ncustomer){\nlogger.info(customer.toString());\ncustomerTable.putItem(customer);\n}\nCustomer object\nCustomer customer = new Customer();\ncustomer.setId(\"1\");\ncustomer.setCustName(\"Customer Name\");\ncustomer.setEmail(\"customer@example.com\");\ncustomer.setRegistrationDate(Instant.parse(\"2023-07-03T10:15:30.00Z\"));\nBefore sending the customer object to the DynamoDB service, log the output of the object's\ntoString() method to compare it to what the enhanced client sends.\nCustomer [id=1, name=Customer Name, email=customer@example.com,\nregDate=2023-07-03T10:15:30Z]\nWire-level logging shows the payload of the generated request. The enhanced client generated the\nlow-level representation from the data class. The regDate attribute, which is an Instant type in\nJava, is represented as a DynamoDB string.\n{\n\"TableName\": \"Customer\",\n\"Item\": {\n\"registrationDate\": {\n\"S\": \"2023-07-03T10:15:30Z\"\n},\n\"id\": {\n\"S\": \"1\"\nMap objects to DynamoDB items 218\nAWS SDK for Java 2.x Developer Guide for version 2.x\n},\n\"custName\": {\n\"S\": \"Customer Name\"\n},\n\"email\": {\n\"S\": \"customer@example.com\"\n}\n}\n}\nWork with an existing table\nThe previous section showed how to create a DynamoDB table starting with a Java data class. If\nyou already have an existing table and want to use the features of the enhanced client, you can\ncreate a Java data class to work with the table. You need to examine the DynamoDB table and add\nthe necessary annotations to the data class.\nBefore you work with an existing table, call the DynamoDbEnhanced.table() method. This was\ndone in the previous example with the following statement.", "mimetype": "text/plain", "start_char_idx": 391673, "end_char_idx": 395973, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2b706988-3999-437e-965c-2fa0c6558f6e": {"__data__": {"id_": "2b706988-3999-437e-965c-2fa0c6558f6e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34f6d956-cf0d-4b65-a5f7-fdadcfaec330", "node_type": "1", "metadata": {}, "hash": "6760f74e0818785d607289e133d79ca607ea51e66644b39742124283358a13b7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c8a9c2b7-206d-40b3-a610-4dbe6d282882", "node_type": "1", "metadata": {}, "hash": "463e13a5781b5ddc3b46a53701741c0695a6951f8e9c6d06620fb4b37e211d55", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If\nyou already have an existing table and want to use the features of the enhanced client, you can\ncreate a Java data class to work with the table. You need to examine the DynamoDB table and add\nthe necessary annotations to the data class.\nBefore you work with an existing table, call the DynamoDbEnhanced.table() method. This was\ndone in the previous example with the following statement.\nDynamoDbTable customerTable = enhancedClient.table(\"Customer\",\nTableSchema.fromBean(Customer.class));\nAfter the DynamoDbTable instance is returned, you can begin working right away\nwith the underlying table. You do not need to recreate the table by calling the\nDynamoDbTable.createTable() method.\nThe following example demonstrates this by immediately retrieving a Customer instance from the\nDynamoDB table.\nDynamoDbTable customerTable = enhancedClient.table(\"Customer\",\nTableSchema.fromBean(Customer.class));\n// The Customer table exists already and has an item with a primary key value of \"1\"\nand a sort key value of \"customer@example.com\".\ncustomerTable.getItem(\nKey.builder().\npartitionValue(\"1\").\nsortValue(\"customer@example.com\").build());\nMap objects to DynamoDB items 219\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImportant\nThe table name used in the table() method must match the existing DynamoDB table\nname.\nLearn the basics of the DynamoDB Enhanced Client API\nThis topic discusses the basic features of the DynamoDB Enhanced Client API and compares it to\nthe standard DynamoDB client API.\nIf you are new to the DynamoDB Enhanced Client API, we recommend that you go through the\nintroductory tutorial to familiarize yourself with fundamental classes.\nDynamoDB items in Java\nDynamoDB tables store items. Depending on your use case, items on the Java side can take the\nform of statically structured data or structures created dynamically.\nIf your use case calls for items with a consistent set of attributes, use annotated classes or use a\nbuilder to generate the appropriate statically-typed TableSchema.\nAlternatively, if you need to store items that consist of varying structures, create a\nDocumentTableSchema. DocumentTableSchema is part of the Enhanced Document API and\nrequires only a statically-typed primary key and works with EnhancedDocument instances to hold\nthe data elements. The Enhanced Document API is covered in another topic.\nAttribute types for data model classes\nAlthough DynamoDB supports a small number of attribute types compared to the rich type system\nof Java, the DynamoDB Enhanced Client API provides mechanisms to convert members of a Java\nclass to and from DynamoDB attribute types.\nThe attribute types (properties) of your Java data classes should be objects types, not primitives.\nFor example, always use Long and Integer object data types, not long and int primitives.\nBy default, the DynamoDB Enhanced Client API supports attribute converters for a large number of\ntypes, such as Integer, String, BigDecimal, and Instant. The list appears in the known implementing\nclasses of the AttributeConverter interface. The list includes many types and collections such as\nmaps, lists, and sets.\nMap objects to DynamoDB items 220\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo store the data for an attribute type that isn't supported by default or doesn't conform to the\nJavaBean convention, you can write a custom AttributeConverter implementation to do the\nconversion. See the attribute conversion section for an example.\nTo store the data for an attribute type whose class conforms to the Java beans specification (or an\nimmutable data class), you can take two approaches.\n\u2022 If you have access to the source file, you can annotate the class with @DynamoDbBean (or\n@DynamoDbImmutable). The section that discusses nested attributes shows examples of using\nannotated classes.\n\u2022 If do not have access to the source file of the JavaBean data class for the attribute (or you don't\nwant to annotate the source file of a class that you do have access to), then you can use the\nbuilder approach. This creates a table schema without defining the keys. Then, you can nest this\ntable schema inside another table schema to perform the mapping. The nested attribute section\nhas an example showing use of nested schemas.\nNull values\nWhen you use the putItem method, the enhanced client does not include null-valued attributes of\na mapped data object in the request to DynamoDB.\nThe SDK's default behavior for updateItem requests removes attributes from the item in\nDynamoDB that are set to null in the object that you submit in the updateItem method. If you\nintend to update some attribute values and keep the others unchanged, you have two options.\n\u2022 Retrieve the item (by using getItem) before you make changes to values. By using this\napproach, the SDK submits all updated and old values to DynamoDB.", "mimetype": "text/plain", "start_char_idx": 395584, "end_char_idx": 400438, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c8a9c2b7-206d-40b3-a610-4dbe6d282882": {"__data__": {"id_": "c8a9c2b7-206d-40b3-a610-4dbe6d282882", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b706988-3999-437e-965c-2fa0c6558f6e", "node_type": "1", "metadata": {}, "hash": "49c1880c6e1ffa413179ef65db15ee6a855573b157736bf854ca18d470845273", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca5f9ce7-1a71-42b1-acd3-37195165f13d", "node_type": "1", "metadata": {}, "hash": "0886cf906a1a3a420ae15edc851f2f751efe059c361e5e97aea5334b30d8ca21", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This creates a table schema without defining the keys. Then, you can nest this\ntable schema inside another table schema to perform the mapping. The nested attribute section\nhas an example showing use of nested schemas.\nNull values\nWhen you use the putItem method, the enhanced client does not include null-valued attributes of\na mapped data object in the request to DynamoDB.\nThe SDK's default behavior for updateItem requests removes attributes from the item in\nDynamoDB that are set to null in the object that you submit in the updateItem method. If you\nintend to update some attribute values and keep the others unchanged, you have two options.\n\u2022 Retrieve the item (by using getItem) before you make changes to values. By using this\napproach, the SDK submits all updated and old values to DynamoDB.\n\u2022 Use either the IgnoreNullsMode.SCALAR_ONLY or IgnoreNullsMode.MAPS_ONLY when\nyou build the request to update the item. Both modes ignore null-valued properties in the object\nthat represent scalar attributes in DynamoDB. The the section called \u201cUpdate items that contain\ncomplex types\u201d topic in this guide contains more information about the IgnoreNullsMode\nvalues and how to work with complex types.\nThe following example demonstrates ignoreNullsMode() for the updateItem() method.\npublic static void updateItemNullsExample() {\nCustomer customer = new Customer();\nMap objects to DynamoDB items 221\nAWS SDK for Java 2.x Developer Guide for version 2.x\ncustomer.setCustName(\"CustomerName\");\ncustomer.setEmail(\"email\");\ncustomer.setId(\"1\");\ncustomer.setRegistrationDate(Instant.now());\nlogger.info(\"Original customer: {}\", customer);\n// Put item with values for all attributes.\ntry {\ncustomerAsyncDynamoDbTable.putItem(customer).join();\n} catch (RuntimeException rte) {\nlogger.error(\"A exception occurred during putItem: {}\",\nrte.getCause().getMessage(), rte);\nreturn;\n}\n// Create a Customer instance with the same 'id' and 'email' values, but a\ndifferent 'name' value.\n// Do not set the 'registrationDate' attribute.\nCustomer customerForUpdate = new Customer();\ncustomerForUpdate.setCustName(\"NewName\");\ncustomerForUpdate.setEmail(\"email\");\ncustomerForUpdate.setId(\"1\");\n// Update item without setting the 'registrationDate' property and set\nIgnoreNullsMode to SCALAR_ONLY.\ntry {\nCustomer updatedWithNullsIgnored = customerAsyncDynamoDbTable.updateItem(b\n-> b\n.item(customerForUpdate)\n.ignoreNullsMode(IgnoreNullsMode.SCALAR_ONLY))\n.join();\nlogger.info(\"Customer updated with nulls ignored: {}\",\nupdatedWithNullsIgnored.toString());\n} catch (RuntimeException rte) {\nlogger.error(\"An exception occurred during updateItem: {}\",\nrte.getCause().getMessage(), rte);\nreturn;\n}\n// Update item without setting the registrationDate attribute and not setting\nignoreNulls to true.\ntry {\nMap objects to DynamoDB items 222\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCustomer updatedWithNullsUsed =\ncustomerAsyncDynamoDbTable.updateItem(customerForUpdate)\n.join();\nlogger.info(\"Customer updated with nulls used: {}\",\nupdatedWithNullsUsed.toString());\n} catch (RuntimeException rte) {\nlogger.error(\"An exception occurred during updateItem: {}\",\nrte.getCause().getMessage(), rte);\n}\n}\n// Logged lines.\nOriginal customer: Customer [id=1, name=CustomerName, email=email,\nregDate=2024-10-11T14:12:30.222858Z]\nCustomer updated with nulls ignored: Customer [id=1, name=NewName, email=email,\nregDate=2024-10-11T14:12:30.222858Z]\nCustomer updated with nulls used: Customer [id=1, name=NewName, email=email,\nregDate=null]\nDynamoDB Enhanced Client basic methods\nBasic methods of the enhanced client map to the DynamoDB service operations that they're named\nafter. The following examples show the simplest variation of each method. You can customize each\nmethod by passing in an enhanced request object. Enhanced request objects offer most of the\nfeatures available in the standard DynamoDB client. They are fully documented in the AWS SDK for\nJava 2.x API Reference.\nThe example uses the the section called \u201cCustomer class\u201d shown previously.", "mimetype": "text/plain", "start_char_idx": 399637, "end_char_idx": 403665, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ca5f9ce7-1a71-42b1-acd3-37195165f13d": {"__data__": {"id_": "ca5f9ce7-1a71-42b1-acd3-37195165f13d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c8a9c2b7-206d-40b3-a610-4dbe6d282882", "node_type": "1", "metadata": {}, "hash": "463e13a5781b5ddc3b46a53701741c0695a6951f8e9c6d06620fb4b37e211d55", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "35efb14a-e80b-4a18-b523-e16794538adb", "node_type": "1", "metadata": {}, "hash": "b81b9a2c930e3605e37eefd404cb0a6d9e2c9df0e233318d47a68214f816e179", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following examples show the simplest variation of each method. You can customize each\nmethod by passing in an enhanced request object. Enhanced request objects offer most of the\nfeatures available in the standard DynamoDB client. They are fully documented in the AWS SDK for\nJava 2.x API Reference.\nThe example uses the the section called \u201cCustomer class\u201d shown previously.\n// CreateTable\ncustomerTable.createTable();\n// GetItem\nCustomer customer =\ncustomerTable.getItem(Key.builder().partitionValue(\"a123\").build());\n// UpdateItem\nCustomer updatedCustomer = customerTable.updateItem(customer);\n// PutItem\ncustomerTable.putItem(customer);\nMap objects to DynamoDB items 223\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// DeleteItem\nCustomer deletedCustomer =\ncustomerTable.deleteItem(Key.builder().partitionValue(\"a123\").sortValue(456).build());\n// Query\nPageIterable customers = customerTable.query(keyEqualTo(k ->\nk.partitionValue(\"a123\")));\n// Scan\nPageIterable customers = customerTable.scan();\n// BatchGetItem\nBatchGetResultPageIterable batchResults =\nenhancedClient.batchGetItem(r -> r.addReadBatch(ReadBatch.builder(Customer.class)\n.mappedTableResource(customerTable)\n.addGetItem(key1)\n.addGetItem(key2)\n.addGetItem(key3)\n.build()));\n// BatchWriteItem\nbatchResults = enhancedClient.batchWriteItem(r ->\nr.addWriteBatch(WriteBatch.builder(Customer.class)\n.mappedTableResource(customerTable)\n.addPutItem(customer)\n.addDeleteItem(key1)\n.addDeleteItem(key1)\n.build()));\n// TransactGetItems\ntransactResults = enhancedClient.transactGetItems(r -> r.addGetItem(customerTable,\nkey1)\n.addGetItem(customerTable,\nkey2));\n// TransactWriteItems\nenhancedClient.transactWriteItems(r -> r.addConditionCheck(customerTable,\ni -> i.key(orderKey)\n.conditionExpression(conditionExpression))\n.addUpdateItem(customerTable, customer)\n.addDeleteItem(customerTable, key));\nMap objects to DynamoDB items 224\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompare DynamoDB Enhanced Client to standard DynamoDB client\nBoth DynamoDB client APIs\u2014standard and enhanced\u2014let you work with DynamoDB tables to\nperform CRUD (create, read, update and delete) data-level operations. The difference between the\nclient APIs is how that is accomplished. Using the standard client, you work directly with low-level\ndata attributes. The enhanced client API uses familiar Java classes and maps to the low-level API\nbehind the scenes.\nWhile both client APIs support data-level operations, the standard DynamoDB client also supports\nresource-level operations. Resource-level operations manage the database, such as creating\nbackups, listing tables, and updating tables. The enhanced client API supports a select number of\nresource-level operations such as creating, describing, and deleting tables.\nTo illustrate the different approaches used by the two client APIs, the following code examples\nshow the creation of the same ProductCatalog table using the standard client and the enhanced\nclient.", "mimetype": "text/plain", "start_char_idx": 403288, "end_char_idx": 406281, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "35efb14a-e80b-4a18-b523-e16794538adb": {"__data__": {"id_": "35efb14a-e80b-4a18-b523-e16794538adb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca5f9ce7-1a71-42b1-acd3-37195165f13d", "node_type": "1", "metadata": {}, "hash": "0886cf906a1a3a420ae15edc851f2f751efe059c361e5e97aea5334b30d8ca21", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0a0a8d26-a299-4b96-bbce-bac234211899", "node_type": "1", "metadata": {}, "hash": "0dd9263950a7f37fc8c61ff61cb9c9450af8be701fd5ad3f469835bb16176268", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The difference between the\nclient APIs is how that is accomplished. Using the standard client, you work directly with low-level\ndata attributes. The enhanced client API uses familiar Java classes and maps to the low-level API\nbehind the scenes.\nWhile both client APIs support data-level operations, the standard DynamoDB client also supports\nresource-level operations. Resource-level operations manage the database, such as creating\nbackups, listing tables, and updating tables. The enhanced client API supports a select number of\nresource-level operations such as creating, describing, and deleting tables.\nTo illustrate the different approaches used by the two client APIs, the following code examples\nshow the creation of the same ProductCatalog table using the standard client and the enhanced\nclient.\nCompare: Create a table using the standard DynamoDB client\nDependencyFactory.dynamoDbClient().createTable(builder -> builder\n.tableName(TABLE_NAME)\n.attributeDefinitions(\nb -> b.attributeName(\"id\").attributeType(ScalarAttributeType.N),\nb -> b.attributeName(\"title\").attributeType(ScalarAttributeType.S),\nb -> b.attributeName(\"isbn\").attributeType(ScalarAttributeType.S)\n)\n.keySchema(\nbuilder1 -> builder1.attributeName(\"id\").keyType(KeyType.HASH),\nbuilder2 -> builder2.attributeName(\"title\").keyType(KeyType.RANGE)\n)\n.globalSecondaryIndexes(builder3 -> builder3\n.indexName(\"products_by_isbn\")\n.keySchema(builder2 -> builder2\n.attributeName(\"isbn\").keyType(KeyType.HASH))\n.projection(builder2 -> builder2\n.projectionType(ProjectionType.INCLUDE)\n.nonKeyAttributes(\"price\", \"authors\"))\n.provisionedThroughput(builder4 -> builder4\n.writeCapacityUnits(5L).readCapacityUnits(5L))\n)\n.provisionedThroughput(builder1 -> builder1\n.readCapacityUnits(5L).writeCapacityUnits(5L))\nMap objects to DynamoDB items 225\nAWS SDK for Java 2.x Developer Guide for version 2.x\n);\nCompare: Create a table using the DynamoDB Enhanced Client\nDynamoDbEnhancedClient enhancedClient = DependencyFactory.enhancedClient();\nproductCatalog = enhancedClient.table(TABLE_NAME,\nTableSchema.fromImmutableClass(ProductCatalog.class));\nproductCatalog.createTable(b -> b\n.provisionedThroughput(b1 -> b1.readCapacityUnits(5L).writeCapacityUnits(5L))\n.globalSecondaryIndices(b2 -> b2.indexName(\"products_by_isbn\")\n.projection(b4 -> b4\n.projectionType(ProjectionType.INCLUDE)\n.nonKeyAttributes(\"price\", \"authors\"))\n.provisionedThroughput(b3 ->\nb3.writeCapacityUnits(5L).readCapacityUnits(5L))\n)\n);\nThe enhanced client uses the following annotated data class. The DynamoDB Enhanced Client\nmaps Java data types to DynamoDB data types for less verbose code that is easier to follow.\nProductCatalog is an example of using an immutable class with the DynamoDB Enhanced Client.\nThe use of Immutable classes for mapped data classes is discussed later in this topic.", "mimetype": "text/plain", "start_char_idx": 405476, "end_char_idx": 408297, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0a0a8d26-a299-4b96-bbce-bac234211899": {"__data__": {"id_": "0a0a8d26-a299-4b96-bbce-bac234211899", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "35efb14a-e80b-4a18-b523-e16794538adb", "node_type": "1", "metadata": {}, "hash": "b81b9a2c930e3605e37eefd404cb0a6d9e2c9df0e233318d47a68214f816e179", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "beb37876-5399-4104-8c40-a30a8896b53b", "node_type": "1", "metadata": {}, "hash": "a4bd33257d683c0f97db6c0c4440cd5d62ebd96807d5836ea075694af045d186", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The DynamoDB Enhanced Client\nmaps Java data types to DynamoDB data types for less verbose code that is easier to follow.\nProductCatalog is an example of using an immutable class with the DynamoDB Enhanced Client.\nThe use of Immutable classes for mapped data classes is discussed later in this topic.\nProductCatalog class\npackage org.example.tests.model;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;\nimport java.math.BigDecimal;\nimport java.util.Objects;\nimport java.util.Set;\n@DynamoDbImmutable(builder = ProductCatalog.Builder.class)\npublic class ProductCatalog implements Comparable {\nprivate Integer id;\nMap objects to DynamoDB items 226\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate String title;\nprivate String isbn;\nprivate Set authors;\nprivate BigDecimal price;\nprivate ProductCatalog(Builder builder){\nthis.authors = builder.authors;\nthis.id = builder.id;\nthis.isbn = builder.isbn;\nthis.price = builder.price;\nthis.title = builder.title;\n}\npublic static Builder builder(){ return new Builder(); }\n@DynamoDbPartitionKey\npublic Integer id() { return id; }\n@DynamoDbSortKey\npublic String title() { return title; }\n@DynamoDbSecondaryPartitionKey(indexNames = \"products_by_isbn\")\npublic String isbn() { return isbn; }\npublic Set authors() { return authors; }\npublic BigDecimal price() { return price; }\npublic static final class Builder {\nprivate Integer id;\nprivate String title;\nprivate String isbn;\nprivate Set authors;\nprivate BigDecimal price;\nprivate Builder(){}\npublic Builder id(Integer id) { this.id = id; return this; }\npublic Builder title(String title) { this.title = title; return this; }\npublic Builder isbn(String ISBN) { this.isbn = ISBN; return this; }\npublic Builder authors(Set authors) { this.authors = authors; return\nthis; }\npublic Builder price(BigDecimal price) { this.price = price; return this; }\npublic ProductCatalog build() { return new ProductCatalog(this); }\n}\nMap objects to DynamoDB items 227\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic String toString() {\nfinal StringBuffer sb = new StringBuffer(\"ProductCatalog{\");\nsb.append(\"id=\").append(id);\nsb.append(\", title='\").append(title).append('\\'');\nsb.append(\", isbn='\").append(isbn).append('\\'');\nsb.append(\", authors=\").append(authors);\nsb.append(\", price=\").append(price);\nsb.append('}');\nreturn sb.toString();\n}\n@Override\npublic boolean equals(Object o) {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nProductCatalog that = (ProductCatalog) o;\nreturn id.equals(that.id) && title.equals(that.title) && Objects.equals(isbn,\nthat.isbn) && Objects.equals(authors, that.authors) && Objects.equals(price,\nthat.price);\n}\n@Override\npublic int hashCode() {\nreturn Objects.hash(id, title, isbn, authors, price);\n}\n@Override\n@DynamoDbIgnore\npublic int compareTo(ProductCatalog other) {\nif (this.id.compareTo(other.id) != 0){\nreturn this.id.compareTo(other.id);\n} else {\nreturn this.title.compareTo(other.title);\n}\n}\n}\nThe following two code examples of a batch write illustrate the verboseness and lack of type safety\nwhen using the standard client as opposed to the enhanced client.", "mimetype": "text/plain", "start_char_idx": 407998, "end_char_idx": 411584, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "beb37876-5399-4104-8c40-a30a8896b53b": {"__data__": {"id_": "beb37876-5399-4104-8c40-a30a8896b53b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0a0a8d26-a299-4b96-bbce-bac234211899", "node_type": "1", "metadata": {}, "hash": "0dd9263950a7f37fc8c61ff61cb9c9450af8be701fd5ad3f469835bb16176268", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e1c4434e-5aec-4cb4-b77d-4d282273a068", "node_type": "1", "metadata": {}, "hash": "f91e863bd22cd35bd01be0fbf343207f4dad50a62dbfa69d0fd9b61904533dd9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Map objects to DynamoDB items 228\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompare: Batch write using the standard DynamoDB client\npublic static void batchWriteStandard(DynamoDbClient dynamoDbClient, String\ntableName) {\nMap catalogItem = Map.of(\n\"authors\", AttributeValue.builder().ss(\"a\", \"b\").build(),\n\"id\", AttributeValue.builder().n(\"1\").build(),\n\"isbn\", AttributeValue.builder().s(\"1-565-85698\").build(),\n\"title\", AttributeValue.builder().s(\"Title 1\").build(),\n\"price\", AttributeValue.builder().n(\"52.13\").build());\nMap catalogItem2 = Map.of(\n\"authors\", AttributeValue.builder().ss(\"a\", \"b\", \"c\").build(),\n\"id\", AttributeValue.builder().n(\"2\").build(),\n\"isbn\", AttributeValue.builder().s(\"1-208-98073\").build(),\n\"title\", AttributeValue.builder().s(\"Title 2\").build(),\n\"price\", AttributeValue.builder().n(\"21.99\").build());\nMap catalogItem3 = Map.of(\n\"authors\", AttributeValue.builder().ss(\"g\", \"k\", \"c\").build(),\n\"id\", AttributeValue.builder().n(\"3\").build(),\n\"isbn\", AttributeValue.builder().s(\"7-236-98618\").build(),\n\"title\", AttributeValue.builder().s(\"Title 3\").build(),\n\"price\", AttributeValue.builder().n(\"42.00\").build());\nSet writeRequests = Set.of(\nWriteRequest.builder().putRequest(b -> b.item(catalogItem)).build(),\nWriteRequest.builder().putRequest(b -> b.item(catalogItem2)).build(),\nWriteRequest.builder().putRequest(b -> b.item(catalogItem3)).build());\nMap> productCatalogItems = Map.of(\n\"ProductCatalog\", writeRequests);\nBatchWriteItemResponse response = dynamoDbClient.batchWriteItem(b ->\nb.requestItems(productCatalogItems));\nlogger.info(\"Unprocessed items: \" + response.unprocessedItems().size());\n}\nMap objects to DynamoDB items 229\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompare: Batch write using the DynamoDB Enhanced Client\npublic static void batchWriteEnhanced(DynamoDbTable productCatalog)\n{\nProductCatalog prod = ProductCatalog.builder()\n.id(1)\n.isbn(\"1-565-85698\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\")))\n.price(BigDecimal.valueOf(52.13))\n.title(\"Title 1\")\n.build();\nProductCatalog prod2 = ProductCatalog.builder()\n.id(2)\n.isbn(\"1-208-98073\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\", \"c\")))\n.price(BigDecimal.valueOf(21.99))\n.title(\"Title 2\")\n.build();\nProductCatalog prod3 = ProductCatalog.builder()\n.id(3)\n.isbn(\"7-236-98618\")\n.authors(new HashSet<>(Arrays.asList(\"g\", \"k\", \"c\")))\n.price(BigDecimal.valueOf(42.00))\n.title(\"Title 3\")\n.build();\nBatchWriteResult batchWriteResult = DependencyFactory.enhancedClient()\n.batchWriteItem(b -> b.writeBatches(\nWriteBatch.builder(ProductCatalog.class)\n.mappedTableResource(productCatalog)\n.addPutItem(prod).addPutItem(prod2).addPutItem(prod3)\n.build()\n));\nlogger.info(\"Unprocessed items: \" +\nbatchWriteResult.unprocessedPutItemsForTable(productCatalog).size());\n}\nWork with immutable data classes\nThe mapping feature of the DynamoDB Enhanced Client API works with immutable data classes. An\nimmutable class has only getters and requires a builder class that the SDK uses to create instances\nof the class. Instead of using the @DynamoDbBean annotation as shown in the Customer class,\nMap objects to DynamoDB items 230\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimmutable classes use the @DynamoDbImmutable annotation, which takes a parameter that\nindicates the builder class to use.\nThe following class is an immutable version of Customer.", "mimetype": "text/plain", "start_char_idx": 411585, "end_char_idx": 415077, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e1c4434e-5aec-4cb4-b77d-4d282273a068": {"__data__": {"id_": "e1c4434e-5aec-4cb4-b77d-4d282273a068", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "beb37876-5399-4104-8c40-a30a8896b53b", "node_type": "1", "metadata": {}, "hash": "a4bd33257d683c0f97db6c0c4440cd5d62ebd96807d5836ea075694af045d186", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "21cd4fa4-b7ca-41be-9a4b-5705fcf571bd", "node_type": "1", "metadata": {}, "hash": "7036a7891d3d9077d977eccd49170f1139d219732b9804aee5da511966ad902a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "An\nimmutable class has only getters and requires a builder class that the SDK uses to create instances\nof the class. Instead of using the @DynamoDbBean annotation as shown in the Customer class,\nMap objects to DynamoDB items 230\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimmutable classes use the @DynamoDbImmutable annotation, which takes a parameter that\nindicates the builder class to use.\nThe following class is an immutable version of Customer.\npackage org.example.tests.model.immutable;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;\nimport java.time.Instant;\n@DynamoDbImmutable(builder = CustomerImmutable.Builder.class)\npublic class CustomerImmutable {\nprivate final String id;\nprivate final String name;\nprivate final String email;\nprivate final Instant regDate;\nprivate CustomerImmutable(Builder b) {\nthis.id = b.id;\nthis.email = b.email;\nthis.name = b.name;\nthis.regDate = b.regDate;\n}\n// This method will be automatically discovered and used by the TableSchema.\npublic static Builder builder() { return new Builder(); }\n@DynamoDbPartitionKey\npublic String id() { return this.id; }\n@DynamoDbSortKey\npublic String email() { return this.email; }\n@DynamoDbSecondaryPartitionKey(indexNames = \"customers_by_name\")\npublic String name() { return this.name; }\nMap objects to DynamoDB items 231\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@DynamoDbSecondarySortKey(indexNames = {\"customers_by_date\", \"customers_by_name\"})\npublic Instant regDate() { return this.regDate; }\npublic static final class Builder {\nprivate String id;\nprivate String email;\nprivate String name;\nprivate Instant regDate;\n// The private Builder constructor is visible to the enclosing\nCustomerImmutable class.\nprivate Builder() {}\npublic Builder id(String id) { this.id = id; return this; }\npublic Builder email(String email) { this.email = email; return this; }\npublic Builder name(String name) { this.name = name; return this; }\npublic Builder regDate(Instant regDate) { this.regDate = regDate; return\nthis; }\n// This method will be automatically discovered and used by the TableSchema.\npublic CustomerImmutable build() { return new CustomerImmutable(this); }\n}\n}\nYou must meet the following requirements when you annotate a data class with\n@DynamoDbImmutable.\n1. Every method that is both not an override of Object.class and has not been annotated with\n@DynamoDbIgnore must be a getter for an attribute of the DynamoDB table.\n2. Every getter must have a corresponding case-sensitive setter on the builder class.\n3. Only one of the following construction conditions must be met.\n\u2022 The builder class must have a public default constructor.\n\u2022 The data class must have a public static method named builder() that takes no parameters\nand returns an instance of the builder class. This option is shown in the immutable Customer\nclass.\n4. The builder class must have a public method named build() that takes no parameters and\nreturns an instance of the immutable class.\nMap objects to DynamoDB items 232\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo create a TableSchema for your immutable class, use the fromImmutableClass() method on\nTableSchema as shown in the following snippet.\nstatic final TableSchema customerImmutableTableSchema =\nTableSchema.fromImmutableClass(CustomerImmutable.class);\nJust as you can create a DynamoDB table from a mutable class, you can create one from an\nimmutable class with a one-time call to createTable() of DynamoDbTable as shown in the\nfollowing snippet example.\nstatic void createTableFromImmutable(DynamoDbEnhancedClient enhancedClient, String\ntableName, DynamoDbWaiter waiter){\n// First, create an in-memory representation of the table using the 'table()'\nmethod of the DynamoDb Enhanced Client.\n// 'table()' accepts a name for the table and a TableSchema instance that you\ncreated previously.\nDynamoDbTable customerDynamoDbTable = enhancedClient\n.table(tableName, TableSchema.fromImmutableClass(CustomerImmutable.class));\n// Second, call the 'createTable()' method on the DynamoDbTable instance.\ncustomerDynamoDbTable.createTable();\nwaiter.waitUntilTableExists(b -> b.tableName(tableName));\n}\nUse third-party libraries, such as Lombok\nThird-party libraries, such as Project Lombok, help generate boilerplate code associated with\nimmutable objects.", "mimetype": "text/plain", "start_char_idx": 414617, "end_char_idx": 419346, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "21cd4fa4-b7ca-41be-9a4b-5705fcf571bd": {"__data__": {"id_": "21cd4fa4-b7ca-41be-9a4b-5705fcf571bd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e1c4434e-5aec-4cb4-b77d-4d282273a068", "node_type": "1", "metadata": {}, "hash": "f91e863bd22cd35bd01be0fbf343207f4dad50a62dbfa69d0fd9b61904533dd9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7b6d158b-eeac-415d-b095-8a0d8176c873", "node_type": "1", "metadata": {}, "hash": "08ebbe0e632d203a3fa407e07dbf1c9998fb4465c817e85388c8c7102f56ebd0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "static void createTableFromImmutable(DynamoDbEnhancedClient enhancedClient, String\ntableName, DynamoDbWaiter waiter){\n// First, create an in-memory representation of the table using the 'table()'\nmethod of the DynamoDb Enhanced Client.\n// 'table()' accepts a name for the table and a TableSchema instance that you\ncreated previously.\nDynamoDbTable customerDynamoDbTable = enhancedClient\n.table(tableName, TableSchema.fromImmutableClass(CustomerImmutable.class));\n// Second, call the 'createTable()' method on the DynamoDbTable instance.\ncustomerDynamoDbTable.createTable();\nwaiter.waitUntilTableExists(b -> b.tableName(tableName));\n}\nUse third-party libraries, such as Lombok\nThird-party libraries, such as Project Lombok, help generate boilerplate code associated with\nimmutable objects. The DynamoDB Enhanced Client API works with these libraries as long as the\ndata classes follow the conventions detailed in this section.\nThe following example shows the immutable CustomerImmutable class with Lombok\nannotations. Note how Lombok's onMethod feature copies attribute-based DynamoDB\nannotations, such as @DynamoDbPartitionKey, onto the generated code.\n@Value\n@Builder\n@DynamoDbImmutable(builder = Customer.CustomerBuilder.class)\npublic class Customer {\n@Getter(onMethod_=@DynamoDbPartitionKey)\nprivate String id;\nMap objects to DynamoDB items 233\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Getter(onMethod_=@DynamoDbSortKey)\nprivate String email;\n@Getter(onMethod_=@DynamoDbSecondaryPartitionKey(indexNames = \"customers_by_name\"))\nprivate String name;\n@Getter(onMethod_=@DynamoDbSecondarySortKey(indexNames = {\"customers_by_date\",\n\"customers_by_name\"}))\nprivate Instant createdDate;\n}\nUse expressions and conditions\nExpressions in the DynamoDB Enhanced Client API are Java representations of DynamoDB\nexpressions.\nThe DynamoDB Enhanced Client API uses three types of expressions:\nExpression\nThe Expression class is used when you define conditions and filters.\nQueryConditional\nThis type of expression represents key conditions for query operations.\nUpdateExpression\nThis class helps you write DynamoDB update expressions and is currently used in the extension\nframework when you update an item.\nExpression anatomy\nAn expression is made up of the following:\n\u2022 A string expression (required). The string contains a DynamoDB logic expression with placeholder\nnames for attribute names and attribute values.\n\u2022 A map of expression values (usually required).\n\u2022 A map of expression names (optional).\nUse a builder to generate anExpression object that takes the following general form.\nMap objects to DynamoDB items 234\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExpression expression = Expression.builder()\n.expression()\n.expressionNames()\n.expressionValues()\n.build()\nExpressions usually require a map of expression values. The map provides the values for the\nplaceholders in the string expression. The map key consists of the placeholder name preceded\nwith a colon (:) and the map value is an instance of AttributeValue. The AttributeValues class has\nconvenience methods to generate an AttributeValue instance from a literal. Alternatively, you\ncan use the AttributeValue.Builder to generate an AttributeValue instance.\nThe following snippet shows a map with two entries after comment line 2. The string passed to the\nexpression() method, shown after comment line 1, contains the placeholders that DynamoDB\nresolves before performing the operation. This snippet doesn't contain a map of expression names,\nbecause price is a permissible attribute name.\npublic static void scanAsync(DynamoDbAsyncTable productCatalog) {\nScanEnhancedRequest request = ScanEnhancedRequest.builder()\n.consistentRead(true)\n.attributesToProject(\"id\", \"title\", \"authors\", \"price\")\n.filterExpression(Expression.builder()\n// 1. :min_value and :max_value are placeholders for the values\nprovided by the map\n.expression(\"price >= :min_value AND price <= :max_value\")\n// 2. Two values are needed for the expression and each is\nsupplied as a map entry.\n.expressionValues(\nMap.of( \":min_value\", numberValue(8.00),\n\":max_value\", numberValue(400_000.00)))\n.build())\n.build();\nIf an attribute name in the DynamoDB table is a reserved word, begins with a number, or contains a\nspace, a map of expression names is required for the Expression.\nFor example, if the attribute name was 1price instead of price in the previous code example, the\nexample would need to be modified as shown in the following example.", "mimetype": "text/plain", "start_char_idx": 418539, "end_char_idx": 423064, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7b6d158b-eeac-415d-b095-8a0d8176c873": {"__data__": {"id_": "7b6d158b-eeac-415d-b095-8a0d8176c873", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "21cd4fa4-b7ca-41be-9a4b-5705fcf571bd", "node_type": "1", "metadata": {}, "hash": "7036a7891d3d9077d977eccd49170f1139d219732b9804aee5da511966ad902a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cab522b8-15ae-4f34-98a1-a8d3cdd53d74", "node_type": "1", "metadata": {}, "hash": "f32bb66b9836da7d34915f98361baef8bfe4875ec7d23e06c083aa0ca37a4119", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Two values are needed for the expression and each is\nsupplied as a map entry.\n.expressionValues(\nMap.of( \":min_value\", numberValue(8.00),\n\":max_value\", numberValue(400_000.00)))\n.build())\n.build();\nIf an attribute name in the DynamoDB table is a reserved word, begins with a number, or contains a\nspace, a map of expression names is required for the Expression.\nFor example, if the attribute name was 1price instead of price in the previous code example, the\nexample would need to be modified as shown in the following example.\nScanEnhancedRequest request = ScanEnhancedRequest.builder()\nMap objects to DynamoDB items 235\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.filterExpression(Expression.builder()\n.expression(\"#price >= :min_value AND #price <= :max_value\")\n.expressionNames( Map.of(\"#price\", \"1price\") )\n.expressionValues(\nMap.of(\":min_value\", numberValue(8.00),\n\":max_value\", numberValue(400_000.00)))\n.build())\n.build();\nA placeholder for an expression name begins with the pound sign (#). An entry for the map of\nexpression names uses the placeholder as the key and the attribute name as the value. The map is\nadded to the expression builder with the expressionNames() method. DynamoDB resolves the\nattribute name before it performs the operation.\nExpression values are not required if a function is used in the string expression. An example of an\nexpression function is attribute_exists().\nThe following example builds an Expression that uses a DynamoDB function. The expression\nstring in this example uses no placeholders. This expression could be used on a putItem operation\nto check if an item already exists in the database with a movie attribute's value equal to the data\nobject's movie attribute.\nExpression exp = Expression.builder().expression(\"attribute_not_exists\n(movie)\").build();\nThe DynamoDB Developer Guide contains complete information on the low-level expressions that\nare used with DynamoDB.\nCondition expressions and conditionals\nWhen you use the putItem(), updateItem(), and deleteItem() methods, and also when\nyou use transaction and batch operations, you use Expression objects to specify conditions that\nDynamoDB must meet to proceed with the operation. These expressions are named condition\nexpressions. For an example, see the condition expression used in the addDeleteItem() method\n(after comment line 1) of transaction example shown in this guide.\nWhen you work with the query() methods, a condition is expressed as a QueryConditional.\nThe QueryConditional class has several static convenience methods that help you write the\ncriteria that determine which items to read from DynamoDB.\nMap objects to DynamoDB items 236\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFor examples of QueryConditionals, see the first code example of the the section called \u201cQuery\nmethod examples\u201d section of this guide.\nFilter expressions\nFilter expressions are used in scan and query operations to filter the items that are returned.\nA filter expression is applied after all the data is read from the database, so the read cost is the\nsame as if there were no filter. The Amazon DynamoDB Developer Guide has more information\nabout using filter expressions for both query and scan operations.\nThe following example shows a filter expression added to a scan request. The criteria restricts the\nitems returned to items with a price between 8.00 and 80.00 inclusive.\nMap expressionValues = Map.of(\n\":min_value\", numberValue(8.00),\n\":max_value\", numberValue(80.00));\nScanEnhancedRequest request = ScanEnhancedRequest.builder()\n.consistentRead(true)\n// 1. the 'attributesToProject()' method allows you to specify which\nvalues you want returned.\n.attributesToProject(\"id\", \"title\", \"authors\", \"price\")\n// 2. Filter expression limits the items returned that match the\nprovided criteria.\n.filterExpression(Expression.builder()\n.expression(\"price >= :min_value AND price <= :max_value\")\n.expressionValues(expressionValues)\n.build())\n.build();\nUpdate expressions\nThe DynamoDB Enhanced Client's updateItem() method provides a standard way to update\nitems in DynamoDB. However, when you require more functionality, UpdateExpressions provide\na type-safe representation of DynamoDB update expression syntax. For example, you can use\nUpdateExpressions to increase values without first reading items from DynamoDB, or add\nindividual members to a list. Update expressions are currently available in custom extensions for\nthe updateItem() method.\nFor an example that uses update expressions, see the custom extension example in this guide.\nMap objects to DynamoDB items 237\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMore information about update expressions is available in the Amazon DynamoDB Developer\nGuide.", "mimetype": "text/plain", "start_char_idx": 422537, "end_char_idx": 427316, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cab522b8-15ae-4f34-98a1-a8d3cdd53d74": {"__data__": {"id_": "cab522b8-15ae-4f34-98a1-a8d3cdd53d74", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7b6d158b-eeac-415d-b095-8a0d8176c873", "node_type": "1", "metadata": {}, "hash": "08ebbe0e632d203a3fa407e07dbf1c9998fb4465c817e85388c8c7102f56ebd0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f246314e-97f0-4edb-b921-229d9a97d2ff", "node_type": "1", "metadata": {}, "hash": "24c6904f856605fa761b27b8f4d9b5bff43496ada6f3b839f00289ed0528a1d8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Filter expression limits the items returned that match the\nprovided criteria.\n.filterExpression(Expression.builder()\n.expression(\"price >= :min_value AND price <= :max_value\")\n.expressionValues(expressionValues)\n.build())\n.build();\nUpdate expressions\nThe DynamoDB Enhanced Client's updateItem() method provides a standard way to update\nitems in DynamoDB. However, when you require more functionality, UpdateExpressions provide\na type-safe representation of DynamoDB update expression syntax. For example, you can use\nUpdateExpressions to increase values without first reading items from DynamoDB, or add\nindividual members to a list. Update expressions are currently available in custom extensions for\nthe updateItem() method.\nFor an example that uses update expressions, see the custom extension example in this guide.\nMap objects to DynamoDB items 237\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMore information about update expressions is available in the Amazon DynamoDB Developer\nGuide.\nWork with paginated results: scans and queries\nThe scan, query and batch methods of the DynamoDB Enhanced Client API return responses\nwith one or more pages. A page contains one or more items. Your code can process the response on\nper-page basis or it can process individual items.\nA paginated response returned by the synchronous DynamoDbEnhancedClient\nclient returns a PageIterable object, whereas a response returned by the asynchronous\nDynamoDbEnhancedAsyncClient returns a PagePublisher object.\nThis section looks at processing paginated results and provides examples that use the scan and\nquery APIs.\nScan a table\nThe SDK's scan method corresponds to the DynamoDB operation of the same name. The\nDynamoDB Enhanced Client API offers the same options but it uses a familiar object model and\nhandles the pagination for you.\nFirst, we explore the PageIterable interface by looking at the scan method of the synchronous\nmapping class, DynamoDbTable.\nUse the synchronous API\nThe following example shows the scan method that uses an expression to filter the items that are\nreturned. The ProductCatalog is the model object that was shown earlier.\nThe filtering expression shown after comment line 2 limits the ProductCatalog items that are\nreturned to those with a price value between 8.00 and 80.00 inclusively.\nThis example also excludes the isbn values by using the attributesToProject method shown\nafter comment line 1.\nAfter comment line 3, the PageIterable object, pagedResults, is returned by the scan\nmethod. The stream method of PageIterable returns a java.util.Stream object, which you\ncan use to process the pages. In this example, the number of pages is counted and logged.\nStarting with comment line 4, the example shows two variations of accessing the\nProductCatalog items. The version after comment line 4a streams through each page and sorts\nMap objects to DynamoDB items 238\nAWS SDK for Java 2.x Developer Guide for version 2.x\nand logs the items on each page. The version after comment line 4b skips the page iteration and\naccesses the items directly.\nThe PageIterable interface offers multiple ways to process results because of its two parent\ninterfaces\u2014java.lang.Iterable and SdkIterable. Iterable brings the forEach,\niterator and spliterator methods, and SdkIterable brings the stream method.\npublic static void scanSync(DynamoDbTable productCatalog) {\nMap expressionValues = Map.of(\n\":min_value\", numberValue(8.00),\n\":max_value\", numberValue(80.00));\nScanEnhancedRequest request = ScanEnhancedRequest.builder()\n.consistentRead(true)\n// 1. the 'attributesToProject()' method allows you to specify which\nvalues you want returned.\n.attributesToProject(\"id\", \"title\", \"authors\", \"price\")\n// 2. Filter expression limits the items returned that match the\nprovided criteria.\n.filterExpression(Expression.builder()\n.expression(\"price >= :min_value AND price <= :max_value\")\n.expressionValues(expressionValues)\n.build())\n.build();\n// 3. A PageIterable object is returned by the scan method.\nPageIterable pagedResults = productCatalog.scan(request);\nlogger.info(\"page count: {}\", pagedResults.stream().count());\n// 4. Log the returned ProductCatalog items using two variations.\n// 4a. This version sorts and logs the items of each page.\npagedResults.stream().forEach(p -> p.items().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(\nitem -> logger.info(item.toString())\n));\n// 4b. This version sorts and logs all items for all pages.", "mimetype": "text/plain", "start_char_idx": 426315, "end_char_idx": 430838, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f246314e-97f0-4edb-b921-229d9a97d2ff": {"__data__": {"id_": "f246314e-97f0-4edb-b921-229d9a97d2ff", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cab522b8-15ae-4f34-98a1-a8d3cdd53d74", "node_type": "1", "metadata": {}, "hash": "f32bb66b9836da7d34915f98361baef8bfe4875ec7d23e06c083aa0ca37a4119", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e55b346d-7477-45bd-9d40-05b1bc4d4775", "node_type": "1", "metadata": {}, "hash": "04c5ac62feb999fd73d10a92103d90760de370ad144952f539952136d9b89918", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".attributesToProject(\"id\", \"title\", \"authors\", \"price\")\n// 2. Filter expression limits the items returned that match the\nprovided criteria.\n.filterExpression(Expression.builder()\n.expression(\"price >= :min_value AND price <= :max_value\")\n.expressionValues(expressionValues)\n.build())\n.build();\n// 3. A PageIterable object is returned by the scan method.\nPageIterable pagedResults = productCatalog.scan(request);\nlogger.info(\"page count: {}\", pagedResults.stream().count());\n// 4. Log the returned ProductCatalog items using two variations.\n// 4a. This version sorts and logs the items of each page.\npagedResults.stream().forEach(p -> p.items().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(\nitem -> logger.info(item.toString())\n));\n// 4b. This version sorts and logs all items for all pages.\npagedResults.items().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(\nitem -> logger.info(item.toString())\n);\nMap objects to DynamoDB items 239\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nUse the asynchronous API\nThe asynchronous scan method returns results as a PagePublisher object. The PagePublisher\ninterface has two subscribe methods that you can use to process response pages. One\nsubscribe method comes from the org.reactivestreams.Publisher parent interface. To\nprocess pages using this first option, pass a Subscriber instance to the subscribe method. The\nfirst example that follows shows the use of subscribe method.\nThe second subscribe method comes from the SdkPublisher interface. This version of\nsubscribe accepts a Consumer rather than a Subscriber. This subscribe method variation is\nshown in the second example that follows.\nThe following example shows the asynchronous version of the scan method that uses the same\nfilter expression shown in the previous example.\nAfter comment line 3, DynamoDbAsyncTable.scan returns a PagePublisher object. On the\nnext line, the code creates an instance of the org.reactivestreams.Subscriber interface,\nProductCatalogSubscriber, which subscribes to the PagePublisher after comment line 4.\nThe Subscriber object collects the ProductCatalog items from each page in the onNext\nmethod after comment line 8 in the ProductCatalogSubscriber class example. The\nitems are stored in the private List variable and are accessed in the calling code with the\nProductCatalogSubscriber.getSubscribedItems() method. This is called after comment\nline 5.\nAfter the list is retrieved, the code sorts all ProductCatalog items by price and logs each item.\nThe CountDownLatch in the ProductCatalogSubscriber class blocks the calling thread until all\nitems have been added to the list before continuing after comment line 5.\npublic static void scanAsync(DynamoDbAsyncTable productCatalog) {\nScanEnhancedRequest request = ScanEnhancedRequest.builder()\n.consistentRead(true)\n.attributesToProject(\"id\", \"title\", \"authors\", \"price\")\n.filterExpression(Expression.builder()\n// 1. :min_value and :max_value are placeholders for the values\nprovided by the map\n.expression(\"price >= :min_value AND price <= :max_value\")\nMap objects to DynamoDB items 240\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// 2. Two values are needed for the expression and each is\nsupplied as a map entry.\n.expressionValues(\nMap.of( \":min_value\", numberValue(8.00),\n\":max_value\", numberValue(400_000.00)))\n.build())\n.build();\n// 3. A PagePublisher object is returned by the scan method.\nPagePublisher pagePublisher = productCatalog.scan(request);\nProductCatalogSubscriber subscriber = new ProductCatalogSubscriber();\n// 4. Subscribe the ProductCatalogSubscriber to the PagePublisher.\npagePublisher.subscribe(subscriber);\n// 5. Retrieve all collected ProductCatalog items accumulated by the\nsubscriber.\nsubscriber.getSubscribedItems().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(item ->\nlogger.info(item.toString()));\n// 6. Use a Consumer to work through each page.\npagePublisher.subscribe(page -> page\n.items().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(item ->\nlogger.info(item.toString())))\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\n// 7. Use a Consumer to work through each ProductCatalog item.\npagePublisher.items()\n.subscribe(product -> logger.info(product.toString()))\n.exceptionally(failure -> {\nlogger.error(\"ERROR - \", failure);\nreturn null;\n})\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\n}", "mimetype": "text/plain", "start_char_idx": 430006, "end_char_idx": 434548, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e55b346d-7477-45bd-9d40-05b1bc4d4775": {"__data__": {"id_": "e55b346d-7477-45bd-9d40-05b1bc4d4775", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f246314e-97f0-4edb-b921-229d9a97d2ff", "node_type": "1", "metadata": {}, "hash": "24c6904f856605fa761b27b8f4d9b5bff43496ada6f3b839f00289ed0528a1d8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "032bb48a-52d5-49e0-9bf8-522d906b3a19", "node_type": "1", "metadata": {}, "hash": "e1439b0bc34e69fc5444bffd55319b16303e95ab4185056404c88b1189cb77bf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Subscribe the ProductCatalogSubscriber to the PagePublisher.\npagePublisher.subscribe(subscriber);\n// 5. Retrieve all collected ProductCatalog items accumulated by the\nsubscriber.\nsubscriber.getSubscribedItems().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(item ->\nlogger.info(item.toString()));\n// 6. Use a Consumer to work through each page.\npagePublisher.subscribe(page -> page\n.items().stream()\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(item ->\nlogger.info(item.toString())))\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\n// 7. Use a Consumer to work through each ProductCatalog item.\npagePublisher.items()\n.subscribe(product -> logger.info(product.toString()))\n.exceptionally(failure -> {\nlogger.error(\"ERROR - \", failure);\nreturn null;\n})\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\n}\nprivate static class ProductCatalogSubscriber implements\nSubscriber> {\nprivate CountDownLatch latch = new CountDownLatch(1);\nprivate Subscription subscription;\nprivate List itemsFromAllPages = new ArrayList<>();\nMap objects to DynamoDB items 241\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic void onSubscribe(Subscription sub) {\nsubscription = sub;\nsubscription.request(1L);\ntry {\nlatch.await(); // Called by main thread blocking it until latch is\nreleased.\n} catch (InterruptedException e) {\nthrow new RuntimeException(e);\n}\n}\n@Override\npublic void onNext(Page productCatalogPage) {\n// 8. Collect all the ProductCatalog instances in the page, then ask the\npublisher for one more page.\nitemsFromAllPages.addAll(productCatalogPage.items());\nsubscription.request(1L);\n}\n@Override\npublic void onError(Throwable throwable) {\n}\n@Override\npublic void onComplete() {\nlatch.countDown(); // Call by subscription thread; latch releases.\n}\nList getSubscribedItems() {\nreturn this.itemsFromAllPages;\n}\n}\nThe following snippet example uses the version of the PagePublisher.subscribe method that\naccepts a Consumer after comment line 6. The Java lambda parameter consumes pages, which\nfurther process each item. In this example, each page is processed and the items on each page are\nsorted and then logged.\n// 6. Use a Consumer to work through each page.\npagePublisher.subscribe(page -> page\n.items().stream()\nMap objects to DynamoDB items 242\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.sorted(Comparator.comparing(ProductCatalog::price))\n.forEach(item ->\nlogger.info(item.toString())))\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\nThe items method of PagePublisher unwraps the model instances so that your code can\nprocess the items directly. This approach is shown in the following snippet.\n// 7. Use a Consumer to work through each ProductCatalog item.\npagePublisher.items()\n.subscribe(product -> logger.info(product.toString()))\n.exceptionally(failure -> {\nlogger.error(\"ERROR - \", failure);\nreturn null;\n})\n.join(); // If needed, blocks the subscribe() method thread until it is\nfinished processing.\nQuery a table\nThe query() method of the DynamoDbTable class finds items based on primary key values. The\n@DynamoDbPartitionKey annotation and the optional @DynamoDbSortKey annotation are used\nto define the primary key on your data class.\nThe query() method requires a partition key value that finds items that match the supplied\nvalue. If your table also defines a sort key, you can add a value for it to your query as an additional\ncomparison condition to fine tune the results.\nExcept for processing the results, the synchronous and asynchronous versions of query() work\nthe same. As with the scan API, the query API returns a PageIterable for a synchronous\ncall and a PagePublisher for asynchronous call. We discussed the use of PageIterable and\nPagePublisher previously in the scan section.\nQuery method examples\nThe query() method code example that follows uses the MovieActor class. The data class\ndefines a composite primary key that is made up of the movie attribute for the partition key and\nthe actor attribute for the sort key.\nThe class also signals that it uses a global secondary index named acting_award_year. The\nindex's composite primary key is composed of the actingaward attribute for the partition key and\nMap objects to DynamoDB items 243\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthe actingyear for the sort key. Later in this topic, when we show how to create and use indexes,\nwe'll refer to the acting_award_year index.", "mimetype": "text/plain", "start_char_idx": 433617, "end_char_idx": 438246, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "032bb48a-52d5-49e0-9bf8-522d906b3a19": {"__data__": {"id_": "032bb48a-52d5-49e0-9bf8-522d906b3a19", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e55b346d-7477-45bd-9d40-05b1bc4d4775", "node_type": "1", "metadata": {}, "hash": "04c5ac62feb999fd73d10a92103d90760de370ad144952f539952136d9b89918", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "99ed2e3d-71da-42c8-b53c-cf413c576497", "node_type": "1", "metadata": {}, "hash": "b090d9c0690d3ba4fddbd852cfb335fc114675b61d7ac500ba5e9d2dcaf616ef", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "As with the scan API, the query API returns a PageIterable for a synchronous\ncall and a PagePublisher for asynchronous call. We discussed the use of PageIterable and\nPagePublisher previously in the scan section.\nQuery method examples\nThe query() method code example that follows uses the MovieActor class. The data class\ndefines a composite primary key that is made up of the movie attribute for the partition key and\nthe actor attribute for the sort key.\nThe class also signals that it uses a global secondary index named acting_award_year. The\nindex's composite primary key is composed of the actingaward attribute for the partition key and\nMap objects to DynamoDB items 243\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthe actingyear for the sort key. Later in this topic, when we show how to create and use indexes,\nwe'll refer to the acting_award_year index.\nMovieActor class\npackage org.example.tests.model;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;\nimport java.util.Objects;\n@DynamoDbBean\npublic class MovieActor implements Comparable {\nprivate String movieName;\nprivate String actorName;\nprivate String actingAward;\nprivate Integer actingYear;\nprivate String actingSchoolName;\n@DynamoDbPartitionKey\n@DynamoDbAttribute(\"movie\")\npublic String getMovieName() {\nreturn movieName;\n}\npublic void setMovieName(String movieName) {\nthis.movieName = movieName;\n}\n@DynamoDbSortKey\n@DynamoDbAttribute(\"actor\")\npublic String getActorName() {\nreturn actorName;\n}\nMap objects to DynamoDB items 244\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void setActorName(String actorName) {\nthis.actorName = actorName;\n}\n@DynamoDbSecondaryPartitionKey(indexNames = \"acting_award_year\")\n@DynamoDbAttribute(\"actingaward\")\npublic String getActingAward() {\nreturn actingAward;\n}\npublic void setActingAward(String actingAward) {\nthis.actingAward = actingAward;\n}\n@DynamoDbSecondarySortKey(indexNames = {\"acting_award_year\", \"movie_year\"})\n@DynamoDbAttribute(\"actingyear\")\npublic Integer getActingYear() {\nreturn actingYear;\n}\npublic void setActingYear(Integer actingYear) {\nthis.actingYear = actingYear;\n}\n@DynamoDbAttribute(\"actingschoolname\")\npublic String getActingSchoolName() {\nreturn actingSchoolName;\n}\npublic void setActingSchoolName(String actingSchoolName) {\nthis.actingSchoolName = actingSchoolName;\n}\n@Override\npublic String toString() {\nfinal StringBuffer sb = new StringBuffer(\"MovieActor{\");\nsb.append(\"movieName='\").append(movieName).append('\\'');\nsb.append(\", actorName='\").append(actorName).append('\\'');\nsb.append(\", actingAward='\").append(actingAward).append('\\'');\nsb.append(\", actingYear=\").append(actingYear);\nsb.append(\", actingSchoolName='\").append(actingSchoolName).append('\\'');\nsb.append('}');\nreturn sb.toString();\nMap objects to DynamoDB items 245\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n@Override\npublic boolean equals(Object o) {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nMovieActor that = (MovieActor) o;\nreturn Objects.equals(movieName, that.movieName) && Objects.equals(actorName,\nthat.actorName) && Objects.equals(actingAward, that.actingAward) &&\nObjects.equals(actingYear, that.actingYear) && Objects.equals(actingSchoolName,\nthat.actingSchoolName);\n}\n@Override\npublic int hashCode() {\nreturn Objects.hash(movieName, actorName, actingAward, actingYear,\nactingSchoolName);\n}\n@Override\npublic int compareTo(MovieActor o) {\nif (this.movieName.compareTo(o.movieName) != 0){\nreturn this.movieName.compareTo(o.movieName);\n} else {\nreturn this.actorName.compareTo(o.actorName);\n}\n}\n}\nThe code examples that follow query against the following items.", "mimetype": "text/plain", "start_char_idx": 437375, "end_char_idx": 441516, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "99ed2e3d-71da-42c8-b53c-cf413c576497": {"__data__": {"id_": "99ed2e3d-71da-42c8-b53c-cf413c576497", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "032bb48a-52d5-49e0-9bf8-522d906b3a19", "node_type": "1", "metadata": {}, "hash": "e1439b0bc34e69fc5444bffd55319b16303e95ab4185056404c88b1189cb77bf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "eb0823e4-f72c-4659-a5f8-5fa9e467417e", "node_type": "1", "metadata": {}, "hash": "9518679d8b88d3d449544c871a4381723565ac0b3cc3a4cdbc13410225f8159e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Items in the MovieActor table\nMovieActor{movieName='movie01', actorName='actor0', actingAward='actingaward0',\nactingYear=2001, actingSchoolName='null'}\nMovieActor{movieName='movie01', actorName='actor1', actingAward='actingaward1',\nactingYear=2001, actingSchoolName='actingschool1'}\nMovieActor{movieName='movie01', actorName='actor2', actingAward='actingaward2',\nactingYear=2001, actingSchoolName='actingschool2'}\nMovieActor{movieName='movie01', actorName='actor3', actingAward='actingaward3',\nactingYear=2001, actingSchoolName='null'}\nMovieActor{movieName='movie01', actorName='actor4', actingAward='actingaward4',\nactingYear=2001, actingSchoolName='actingschool4'}\nMap objects to DynamoDB items 246\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMovieActor{movieName='movie02', actorName='actor0', actingAward='actingaward0',\nactingYear=2002, actingSchoolName='null'}\nMovieActor{movieName='movie02', actorName='actor1', actingAward='actingaward1',\nactingYear=2002, actingSchoolName='actingschool1'}\nMovieActor{movieName='movie02', actorName='actor2', actingAward='actingaward2',\nactingYear=2002, actingSchoolName='actingschool2'}\nMovieActor{movieName='movie02', actorName='actor3', actingAward='actingaward3',\nactingYear=2002, actingSchoolName='null'}\nMovieActor{movieName='movie02', actorName='actor4', actingAward='actingaward4',\nactingYear=2002, actingSchoolName='actingschool4'}\nMovieActor{movieName='movie03', actorName='actor0', actingAward='actingaward0',\nactingYear=2003, actingSchoolName='null'}\nMovieActor{movieName='movie03', actorName='actor1', actingAward='actingaward1',\nactingYear=2003, actingSchoolName='actingschool1'}\nMovieActor{movieName='movie03', actorName='actor2', actingAward='actingaward2',\nactingYear=2003, actingSchoolName='actingschool2'}\nMovieActor{movieName='movie03', actorName='actor3', actingAward='actingaward3',\nactingYear=2003, actingSchoolName='null'}\nMovieActor{movieName='movie03', actorName='actor4', actingAward='actingaward4',\nactingYear=2003, actingSchoolName='actingschool4'}\nThe following code defines two QueryConditional instances. QueryConditionals work with key\nvalues\u2014either the partition key alone or in combination with the sort key\u2014and correspond to\nthe key conditional expressions of the DynamoDB service API. After comment line 1, the example\ndefines the keyEqual instance that matches items with a partition value of movie01.\nThis example also defines a filter expression that filters off any item that has no\nactingschoolname on after comment line 2.\nAfter comment line 3, the example shows the QueryEnhancedRequest instance that the code\npasses to the DynamoDbTable.query() method. This object combines the key condition and\nfilter that the SDK uses to generate the request to the DynamoDB service.\npublic static void query(DynamoDbTable movieActorTable) {\n// 1. Define a QueryConditional instance to return items matching a partition\nvalue.\nQueryConditional keyEqual = QueryConditional.keyEqualTo(b ->\nb.partitionValue(\"movie01\"));\n// 1a. Define a QueryConditional that adds a sort key criteria to the partition\nvalue criteria.\nMap objects to DynamoDB items 247\nAWS SDK for Java 2.x Developer Guide for version 2.x\nQueryConditional sortGreaterThanOrEqualTo =\nQueryConditional.sortGreaterThanOrEqualTo(b ->\nb.partitionValue(\"movie01\").sortValue(\"actor2\"));\n// 2. Define a filter expression that filters out items whose attribute value\nis null.\nfinal Expression filterOutNoActingschoolname =\nExpression.builder().expression(\"attribute_exists(actingschoolname)\").build();\n// 3. Build the query request.\nQueryEnhancedRequest tableQuery = QueryEnhancedRequest.builder()\n.queryConditional(keyEqual)\n.filterExpression(filterOutNoActingschoolname)\n.build();\n// 4. Perform the query.\nPageIterable pagedResults = movieActorTable.query(tableQuery);\nlogger.info(\"page count: {}\", pagedResults.stream().count()); // Log number of\npages.\npagedResults.items().stream()\n.sorted()\n.forEach(\nitem -> logger.info(item.toString()) // Log the sorted list of\nitems.\n);\nThe following is the output from running the method.", "mimetype": "text/plain", "start_char_idx": 441517, "end_char_idx": 445595, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "eb0823e4-f72c-4659-a5f8-5fa9e467417e": {"__data__": {"id_": "eb0823e4-f72c-4659-a5f8-5fa9e467417e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "99ed2e3d-71da-42c8-b53c-cf413c576497", "node_type": "1", "metadata": {}, "hash": "b090d9c0690d3ba4fddbd852cfb335fc114675b61d7ac500ba5e9d2dcaf616ef", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7d177cac-1368-465d-9b79-de44e1ab20fb", "node_type": "1", "metadata": {}, "hash": "4eb9307279d1a70a636ee2228801bed20d522192ffc8ba81ad854fc20b0ebb95", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Define a filter expression that filters out items whose attribute value\nis null.\nfinal Expression filterOutNoActingschoolname =\nExpression.builder().expression(\"attribute_exists(actingschoolname)\").build();\n// 3. Build the query request.\nQueryEnhancedRequest tableQuery = QueryEnhancedRequest.builder()\n.queryConditional(keyEqual)\n.filterExpression(filterOutNoActingschoolname)\n.build();\n// 4. Perform the query.\nPageIterable pagedResults = movieActorTable.query(tableQuery);\nlogger.info(\"page count: {}\", pagedResults.stream().count()); // Log number of\npages.\npagedResults.items().stream()\n.sorted()\n.forEach(\nitem -> logger.info(item.toString()) // Log the sorted list of\nitems.\n);\nThe following is the output from running the method. The output displays items with a\nmovieName value of movie01 and displays no items with actingSchoolName equal to null.\n2023-03-05 13:11:05 [main] INFO org.example.tests.QueryDemo:46 - page count: 1\n2023-03-05 13:11:05 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor1', actingAward='actingaward1',\nactingYear=2001, actingSchoolName='actingschool1'}\n2023-03-05 13:11:05 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor2', actingAward='actingaward2',\nactingYear=2001, actingSchoolName='actingschool2'}\n2023-03-05 13:11:05 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor4', actingAward='actingaward4',\nactingYear=2001, actingSchoolName='actingschool4'}\nIn the following query request variation shown previously after comment line 3, the code replaces\nthe keyEqual QueryConditional with the sortGreaterThanOrEqualTo QueryConditional\nthat was defined after comment line 1a. The following code also removes the filter expression.\nMap objects to DynamoDB items 248\nAWS SDK for Java 2.x Developer Guide for version 2.x\nQueryEnhancedRequest tableQuery = QueryEnhancedRequest.builder()\n.queryConditional(sortGreaterThanOrEqualTo)\nBecause this table has a composite primary key, all QueryConditional instances require a\npartition key value. QueryConditional methods that begin with sort... indicate that a sort\nkey is required. The results are not sorted.\nThe following output displays the results from the query. The query returns items that have a\nmovieName value equal to movie01 and only items that have an actorName value that is greater\nthan or equal to actor2. Because the filter was removed, the query returns items that have no value\nfor the actingSchoolName attribute.\n2023-03-05 13:15:00 [main] INFO org.example.tests.QueryDemo:46 - page count: 1\n2023-03-05 13:15:00 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor2', actingAward='actingaward2',\nactingYear=2001, actingSchoolName='actingschool2'}\n2023-03-05 13:15:00 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor3', actingAward='actingaward3',\nactingYear=2001, actingSchoolName='null'}\n2023-03-05 13:15:00 [main] INFO org.example.tests.QueryDemo:51 -\nMovieActor{movieName='movie01', actorName='actor4', actingAward='actingaward4',\nactingYear=2001, actingSchoolName='actingschool4'}\nPerform batch operations\nThe DynamoDB Enhanced Client API offers two batch methods, batchGetItem() and\nbatchWriteItem().\nbatchGetItem() example\nWith the DynamoDbEnhancedClient.batchGetItem() method, you can retrieve up to 100\nindividual items across multiple tables in one overall request. The following example uses the\nCustomer and MovieActor data classes shown previously.\nIn the example after lines 1 and 2, you build ReadBatch objects that you later add as parameters\nto the batchGetItem() method after comment line 3.\nThe code after comment line 1 builds the batch to read from the Customer table. The code after\ncomment line 1a shows the use of a GetItemEnhancedRequest builder that takes a primary key\nvalue and a sort key value to specify the item to read. If the data class has composite key, you must\nprovide both the partition key value and the sort key value.", "mimetype": "text/plain", "start_char_idx": 444846, "end_char_idx": 448930, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7d177cac-1368-465d-9b79-de44e1ab20fb": {"__data__": {"id_": "7d177cac-1368-465d-9b79-de44e1ab20fb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "eb0823e4-f72c-4659-a5f8-5fa9e467417e", "node_type": "1", "metadata": {}, "hash": "9518679d8b88d3d449544c871a4381723565ac0b3cc3a4cdbc13410225f8159e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6f2607b4-5562-4b7d-abbe-c01f8b9a458a", "node_type": "1", "metadata": {}, "hash": "a9160eefc1ff6f3cc735af2f91c194777df25f6e847fff712b7ee2da9b6591c9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "batchGetItem() example\nWith the DynamoDbEnhancedClient.batchGetItem() method, you can retrieve up to 100\nindividual items across multiple tables in one overall request. The following example uses the\nCustomer and MovieActor data classes shown previously.\nIn the example after lines 1 and 2, you build ReadBatch objects that you later add as parameters\nto the batchGetItem() method after comment line 3.\nThe code after comment line 1 builds the batch to read from the Customer table. The code after\ncomment line 1a shows the use of a GetItemEnhancedRequest builder that takes a primary key\nvalue and a sort key value to specify the item to read. If the data class has composite key, you must\nprovide both the partition key value and the sort key value.\nMap objects to DynamoDB items 249\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn contrast to specifying key values to request an item, you can use a data class to request an\nitem as shown after comment line 1b. The SDK extracts the key values behind the scenes before\nsubmitting the request.\nWhen you specify the item using the key-based approach as shown in the two statements after\n2a, you can also specify that DynamoDB should perform a strongly consistent read. When the\nconsistentRead() method is used, it must be used on all requested items for the same table.\nTo retrieve the items that DynamoDB found, use the resultsForTable() method\nthat is shown after comment line 4. Call the method for each table that was read in the\nrequest. resultsForTable() returns a list of found items that you can process using any\njava.util.List method. This example logs each item.\nTo discover items that DynamoDB did not process, use the approach after comment line 5. The\nBatchGetResultPage class has the unprocessedKeysForTable() method that gives you\naccess to each key that was unprocessed. The BatchGetItem API reference has more information\nabout situations that result in unprocessed items.\npublic static void batchGetItemExample(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable customerTable,\nDynamoDbTable movieActorTable) {\nCustomer customer2 = new Customer();\ncustomer2.setId(\"2\");\ncustomer2.setEmail(\"cust2@example.org\");\n// 1. Build a batch to read from the Customer table.\nReadBatch customerBatch = ReadBatch.builder(Customer.class)\n.mappedTableResource(customerTable)\n// 1a. Specify the primary key value and sort key value for the item.\n.addGetItem(b -> b.key(k ->\nk.partitionValue(\"1\").sortValue(\"cust1@orgname.org\")))\n// 1b. Alternatively, supply a data class instances to provide the\nprimary key values.\n.addGetItem(customer2)\n.build();\n// 2. Build a batch to read from the MovieActor table.\nReadBatch moveActorBatch = ReadBatch.builder(MovieActor.class)\n.mappedTableResource(movieActorTable)\n// 2a. Call consistentRead(Boolean.TRUE) for each item for the same\ntable.\nMap objects to DynamoDB items 250\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.addGetItem(b -> b.key(k ->\nk.partitionValue(\"movie01\").sortValue(\"actor1\")).consistentRead(Boolean.TRUE))\n.addGetItem(b -> b.key(k ->\nk.partitionValue(\"movie01\").sortValue(\"actor4\")).consistentRead(Boolean.TRUE))\n.build();\n// 3. Add ReadBatch objects to the request.\nBatchGetResultPageIterable resultPages = enhancedClient.batchGetItem(b ->\nb.readBatches(customerBatch, moveActorBatch));\n// 4. Retrieve the successfully requested items from each table.\nresultPages.resultsForTable(customerTable).forEach(item ->\nlogger.info(item.toString()));\nresultPages.resultsForTable(movieActorTable).forEach(item ->\nlogger.info(item.toString()));\n// 5. Retrieve the keys of the items requested but not processed by the\nservice.\nresultPages.forEach((BatchGetResultPage pageResult) -> {\npageResult.unprocessedKeysForTable(customerTable).forEach(key ->\nlogger.info(\"Unprocessed item key: \" + key.toString()));\npageResult.unprocessedKeysForTable(customerTable).forEach(key ->\nlogger.info(\"Unprocessed item key: \" + key.toString()));\n});\n}\nAssume that the following items are in the two tables before running the example code.", "mimetype": "text/plain", "start_char_idx": 448179, "end_char_idx": 452240, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6f2607b4-5562-4b7d-abbe-c01f8b9a458a": {"__data__": {"id_": "6f2607b4-5562-4b7d-abbe-c01f8b9a458a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7d177cac-1368-465d-9b79-de44e1ab20fb", "node_type": "1", "metadata": {}, "hash": "4eb9307279d1a70a636ee2228801bed20d522192ffc8ba81ad854fc20b0ebb95", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9af6753c-5364-47c1-b643-4f223a0588fa", "node_type": "1", "metadata": {}, "hash": "545bb5c97b886070957238033a768e342c40d49cf8b1d96e2cf540f6c397cd36", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Add ReadBatch objects to the request.\nBatchGetResultPageIterable resultPages = enhancedClient.batchGetItem(b ->\nb.readBatches(customerBatch, moveActorBatch));\n// 4. Retrieve the successfully requested items from each table.\nresultPages.resultsForTable(customerTable).forEach(item ->\nlogger.info(item.toString()));\nresultPages.resultsForTable(movieActorTable).forEach(item ->\nlogger.info(item.toString()));\n// 5. Retrieve the keys of the items requested but not processed by the\nservice.\nresultPages.forEach((BatchGetResultPage pageResult) -> {\npageResult.unprocessedKeysForTable(customerTable).forEach(key ->\nlogger.info(\"Unprocessed item key: \" + key.toString()));\npageResult.unprocessedKeysForTable(customerTable).forEach(key ->\nlogger.info(\"Unprocessed item key: \" + key.toString()));\n});\n}\nAssume that the following items are in the two tables before running the example code.\nItems in tables\nCustomer [id=1, name=CustName1, email=cust1@example.org,\nregDate=2023-03-31T15:46:27.688Z]\nCustomer [id=2, name=CustName2, email=cust2@example.org,\nregDate=2023-03-31T15:46:28.688Z]\nCustomer [id=3, name=CustName3, email=cust3@example.org,\nregDate=2023-03-31T15:46:29.688Z]\nCustomer [id=4, name=CustName4, email=cust4@example.org,\nregDate=2023-03-31T15:46:30.688Z]\nCustomer [id=5, name=CustName5, email=cust5@example.org,\nregDate=2023-03-31T15:46:31.689Z]\nMovieActor{movieName='movie01', actorName='actor0', actingAward='actingaward0',\nactingYear=2001, actingSchoolName='null'}\nMovieActor{movieName='movie01', actorName='actor1', actingAward='actingaward1',\nactingYear=2001, actingSchoolName='actingschool1'}\nMap objects to DynamoDB items 251\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMovieActor{movieName='movie01', actorName='actor2', actingAward='actingaward2',\nactingYear=2001, actingSchoolName='actingschool2'}\nMovieActor{movieName='movie01', actorName='actor3', actingAward='actingaward3',\nactingYear=2001, actingSchoolName='null'}\nMovieActor{movieName='movie01', actorName='actor4', actingAward='actingaward4',\nactingYear=2001, actingSchoolName='actingschool4'}\nThe following output shows the items returned and logged after comment line 4.\nCustomer [id=1, name=CustName1, email=cust1@example.org,\nregDate=2023-03-31T15:46:27.688Z]\nCustomer [id=2, name=CustName2, email=cust2@example.org,\nregDate=2023-03-31T15:46:28.688Z]\nMovieActor{movieName='movie01', actorName='actor4', actingAward='actingaward4',\nactingYear=2001, actingSchoolName='actingschool4'}\nMovieActor{movieName='movie01', actorName='actor1', actingAward='actingaward1',\nactingYear=2001, actingSchoolName='actingschool1'}\nbatchWriteItem() example\nThe batchWriteItem() method puts or deletes multiple items in one or more tables. You can\nspecify up to 25 individual put or delete operations in the request. The following example uses the\nProductCatalog and MovieActor model classes shown previously.\nWriteBatch objects are built after comment lines 1 and 2. For the ProductCatalog table, the\ncode puts one item and deletes one item. For the MovieActor table after comment line 2, the\ncode puts two items and deletes one.\nThe batchWriteItem method is called after comment line 3. The builder parameter provides\nthe batch requests for each table.\nThe returned BatchWriteResult object provides separate methods for each operation to view\nunprocessed requests. The code after comment line 4a provides the keys for unprocessed delete\nrequests and the code after comment line 4b provides the unprocessed put items.\npublic static void batchWriteItemExample(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable\ncatalogTable,\nDynamoDbTable movieActorTable)\n{\n// 1. Build a batch to write to the ProductCatalog table.", "mimetype": "text/plain", "start_char_idx": 451360, "end_char_idx": 455071, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9af6753c-5364-47c1-b643-4f223a0588fa": {"__data__": {"id_": "9af6753c-5364-47c1-b643-4f223a0588fa", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6f2607b4-5562-4b7d-abbe-c01f8b9a458a", "node_type": "1", "metadata": {}, "hash": "a9160eefc1ff6f3cc735af2f91c194777df25f6e847fff712b7ee2da9b6591c9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "af712d37-c85a-4524-ae64-dea69f79c629", "node_type": "1", "metadata": {}, "hash": "f80ca0c0cc295146c37cead562597d20a842a8f8d0c72f18aa7c874f1c5ca6a2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "WriteBatch objects are built after comment lines 1 and 2. For the ProductCatalog table, the\ncode puts one item and deletes one item. For the MovieActor table after comment line 2, the\ncode puts two items and deletes one.\nThe batchWriteItem method is called after comment line 3. The builder parameter provides\nthe batch requests for each table.\nThe returned BatchWriteResult object provides separate methods for each operation to view\nunprocessed requests. The code after comment line 4a provides the keys for unprocessed delete\nrequests and the code after comment line 4b provides the unprocessed put items.\npublic static void batchWriteItemExample(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable\ncatalogTable,\nDynamoDbTable movieActorTable)\n{\n// 1. Build a batch to write to the ProductCatalog table.\nMap objects to DynamoDB items 252\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWriteBatch products = WriteBatch.builder(ProductCatalog.class)\n.mappedTableResource(catalogTable)\n.addPutItem(b -> b.item(getProductCatItem1()))\n.addDeleteItem(b -> b.key(k -> k\n.partitionValue(getProductCatItem2().id())\n.sortValue(getProductCatItem2().title())))\n.build();\n// 2. Build a batch to write to the MovieActor table.\nWriteBatch movies = WriteBatch.builder(MovieActor.class)\n.mappedTableResource(movieActorTable)\n.addPutItem(getMovieActorYeoh())\n.addPutItem(getMovieActorBlanchettPartial())\n.addDeleteItem(b -> b.key(k -> k\n.partitionValue(getMovieActorStreep().getMovieName())\n.sortValue(getMovieActorStreep().getActorName())))\n.build();\n// 3. Add WriteBatch objects to the request.\nBatchWriteResult batchWriteResult = enhancedClient.batchWriteItem(b ->\nb.writeBatches(products, movies));\n// 4. Retrieve keys for items the service did not process.\n// 4a. 'unprocessedDeleteItemsForTable()' returns keys for delete requests that\ndid not process.\nif (batchWriteResult.unprocessedDeleteItemsForTable(movieActorTable).size() >\n0) {\nbatchWriteResult.unprocessedDeleteItemsForTable(movieActorTable).forEach(key ->\nlogger.info(key.toString()));\n}\n// 4b. 'unprocessedPutItemsForTable()' returns keys for put requests that did\nnot process.\nif (batchWriteResult.unprocessedPutItemsForTable(catalogTable).size() > 0) {\nbatchWriteResult.unprocessedPutItemsForTable(catalogTable).forEach(key ->\nlogger.info(key.toString()));\n}\n}\nThe following helper methods provide the model objects for the put and delete operations.\nHelper methods\npublic static ProductCatalog getProductCatItem1() {\nreturn ProductCatalog.builder()\nMap objects to DynamoDB items 253\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.id(2)\n.isbn(\"1-565-85698\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\")))\n.price(BigDecimal.valueOf(30.22))\n.title(\"Title 55\")\n.build();\n}\npublic static ProductCatalog getProductCatItem2() {\nreturn ProductCatalog.builder()\n.id(4)\n.price(BigDecimal.valueOf(40.00))\n.title(\"Title 1\")\n.build();\n}\npublic static MovieActor getMovieActorBlanchettPartial() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Cate Blanchett\");\nmovieActor.setMovieName(\"Blue Jasmine\");\nmovieActor.setActingYear(2023);\nmovieActor.setActingAward(\"Best Actress\");\nreturn movieActor;\n}\npublic static MovieActor getMovieActorStreep() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Meryl Streep\");\nmovieActor.setMovieName(\"Sophie's Choice\");\nmovieActor.setActingYear(1982);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"Yale School of Drama\");\nreturn movieActor;\n}\npublic static MovieActor getMovieActorYeoh(){\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Michelle Yeoh\");\nmovieActor.setMovieName(\"Everything Everywhere All at Once\");\nmovieActor.setActingYear(2023);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"Royal Academy of Dance\");\nreturn movieActor;\nMap objects to DynamoDB items 254\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nAssume that the tables contain the following items before you run the example code.", "mimetype": "text/plain", "start_char_idx": 454236, "end_char_idx": 458284, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "af712d37-c85a-4524-ae64-dea69f79c629": {"__data__": {"id_": "af712d37-c85a-4524-ae64-dea69f79c629", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9af6753c-5364-47c1-b643-4f223a0588fa", "node_type": "1", "metadata": {}, "hash": "545bb5c97b886070957238033a768e342c40d49cf8b1d96e2cf540f6c397cd36", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "88ecf9dd-4580-4dbe-834f-012908511ff1", "node_type": "1", "metadata": {}, "hash": "b4ae35cf143ffe8d9ee289b411f41d20ab702a687805f340a890cbce4710d61e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "MovieActor{movieName='Blue Jasmine', actorName='Cate Blanchett', actingAward='Best\nActress', actingYear=2013, actingSchoolName='National Institute of Dramatic Art'}\nMovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\nProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\nAfter the example code finishes, the tables contain the following items.\nMovieActor{movieName='Blue Jasmine', actorName='Cate Blanchett', actingAward='Best\nActress', actingYear=2013, actingSchoolName='null'}\nMovieActor{movieName='Everything Everywhere All at Once', actorName='Michelle Yeoh',\nactingAward='Best Actress', actingYear=2023, actingSchoolName='Royal Academy of\nDance'}\nProductCatalog{id=2, title='Title 55', isbn='1-565-85698', authors=[a, b], price=30.22}\nNotice in the MovieActor table that the Blue Jasmine movie item has been replaced with the\nitem used in the put request acquired through the getMovieActorBlanchettPartial() helper\nmethod. If a data bean attribute value was not provided, the value in the database is removed. This\nis why the resulting actingSchoolName is null for the Blue Jasmine movie item.\nNote\nAlthough the API documentation suggests that condition expressions can be used and that\nconsumed capacity and collection metrics can be returned with individual put and delete\nrequests, this is not the case in a batch write scenario. To improve performance for batch\noperations, these individual options are ignored.\nPerform transaction operations\nThe DynamoDB Enhanced Client API provides the transactGetItems() and the\ntransactWriteItems() methods. The transaction methods of the SDK for Java provide\natomicity, consistency, isolation, and durability (ACID) in DynamoDB tables, helping you to maintain\ndata correctness in your applications.\nMap objects to DynamoDB items 255\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntransactGetItems() example\nThe transactGetItems() method accepts up to 100 individual requests for items. All items are\nread in a single atomic transaction. The Amazon DynamoDB Developer Guide has information about\nthe conditions that cause a transactGetItems() method to fail, and also about the isolation\nlevel used when you call transactGetItem().\nAfter comment line 1 in the following example, the code calls the transactGetItems() method\nwith a builder parameter. The builder's addGetItem() is invoked three times with a data object\nthat contains the key values that the SDK will use to generate the final request.\nThe request returns a list of Document objects after comment line 2. The list of documents that is\nreturned contains non-null Document instances of item data in the same order as requested. The\nDocument.getItem(MappedTableResource mappedTableResource) method converts\nan untyped Document object into a typed Java object if item data was returned, otherwise the\nmethod returns null.\npublic static void transactGetItemsExample(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable\ncatalogTable,\nDynamoDbTable\nmovieActorTable) {\n// 1. Request three items from two tables using a builder.\nfinal List documents = enhancedClient.transactGetItems(b -> b\n.addGetItem(catalogTable,\nKey.builder().partitionValue(2).sortValue(\"Title 55\").build())\n.addGetItem(movieActorTable, Key.builder().partitionValue(\"Sophie's\nChoice\").sortValue(\"Meryl Streep\").build())\n.addGetItem(movieActorTable, Key.builder().partitionValue(\"Blue\nJasmine\").sortValue(\"Cate Blanchett\").build())\n.build());\n// 2. A list of Document objects is returned in the same order as requested.\nProductCatalog title55 = documents.get(0).getItem(catalogTable);\nif (title55 != null) {\nlogger.info(title55.toString());\n}\nMovieActor sophiesChoice = documents.get(1).getItem(movieActorTable);\nif (sophiesChoice != null) {\nlogger.info(sophiesChoice.toString());\nMap objects to DynamoDB items 256\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n// 3. The getItem() method returns null if the Document object contains no item\nfrom DynamoDB.\nMovieActor blueJasmine = documents.get(2).getItem(movieActorTable);\nif (blueJasmine != null) {\nlogger.info(blueJasmine.toString());\n}\n}\nThe DynamoDB tables contain the following items before the code example runs.", "mimetype": "text/plain", "start_char_idx": 458285, "end_char_idx": 462612, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "88ecf9dd-4580-4dbe-834f-012908511ff1": {"__data__": {"id_": "88ecf9dd-4580-4dbe-834f-012908511ff1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "af712d37-c85a-4524-ae64-dea69f79c629", "node_type": "1", "metadata": {}, "hash": "f80ca0c0cc295146c37cead562597d20a842a8f8d0c72f18aa7c874f1c5ca6a2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5b5d5ba8-7870-4f93-b89c-bb205fc1e1b8", "node_type": "1", "metadata": {}, "hash": "5d6f434eea189609a07065b2cf9995ad9c6c3f8fd60103b19692fa5efd39944b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "A list of Document objects is returned in the same order as requested.\nProductCatalog title55 = documents.get(0).getItem(catalogTable);\nif (title55 != null) {\nlogger.info(title55.toString());\n}\nMovieActor sophiesChoice = documents.get(1).getItem(movieActorTable);\nif (sophiesChoice != null) {\nlogger.info(sophiesChoice.toString());\nMap objects to DynamoDB items 256\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n// 3. The getItem() method returns null if the Document object contains no item\nfrom DynamoDB.\nMovieActor blueJasmine = documents.get(2).getItem(movieActorTable);\nif (blueJasmine != null) {\nlogger.info(blueJasmine.toString());\n}\n}\nThe DynamoDB tables contain the following items before the code example runs.\nProductCatalog{id=2, title='Title 55', isbn='orig_isbn', authors=[b, g], price=10}\nMovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\nThe following output is logged. If an item is requested but not found, it not returned as is the case\nfor the request for the movie named Blue Jasmine.\nProductCatalog{id=2, title='Title 55', isbn='orig_isbn', authors=[b, g], price=10}\nMovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\ntransactWriteItems() examples\nThe transactWriteItems() accepts up to 100 put, update, or delete actions in a single atomic\ntransaction across multiple tables. The Amazon DynamoDB Developer Guide contains details about\nrestrictions and failure conditions of the underlying DynamoDB service operation.\nBasic example\nIn the following example, four operations are requested for two tables. The corresponding model\nclasses ProductCatalog and MovieActor were shown previously.\nEach of the three possible operations\u2014put, update, and delete\u2014uses a dedicated request\nparameter to specify the details.\nThe code after comment line 1 shows the simple variation of the addPutItem()\nmethod. The method accepts a MappedTableResource object and the data object\ninstance to put. The statement after comment line 2 shows the variation that accepts a\nMap objects to DynamoDB items 257\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTransactPutItemEnhancedRequest instance. This variation lets you add more options in the\nrequest, such as a condition expression. A subsequent example shows a condition expression for an\nindividual operation.\nAn update operation is requested after comment line 3.\nTransactUpdateItemEnhancedRequest has an ignoreNulls() method that lets you\nconfigure what the SDK does with null values on the model object. If the ignoreNulls()\nmethod returns true, the SDK does not remove the table's attribute values for data object\nattributes that are null. If the ignoreNulls() method returns false, the SDK requests the\nDynamoDB service to remove the attributes from the item in the table. The default value for\nignoreNulls is false.\nThe statement after comment line 4 shows the variation of a delete request that takes a data\nobject. The enhanced client extracts the key values before dispatching the final request.\npublic static void transactWriteItems(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable catalogTable,\nDynamoDbTable movieActorTable) {\nenhancedClient.transactWriteItems(b -> b\n// 1. Simplest variation of put item request.\n.addPutItem(catalogTable, getProductCatId2())\n// 2. Put item request variation that accommodates condition\nexpressions.\n.addPutItem(movieActorTable,\nTransactPutItemEnhancedRequest.builder(MovieActor.class)\n.item(getMovieActorStreep())\n.conditionExpression(Expression.builder().expression(\"attribute_not_exists\n(movie)\").build())\n.build())\n// 3. Update request that does not remove attribute values on the table\nif the data object's value is null.\n.addUpdateItem(catalogTable,\nTransactUpdateItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId4ForUpdate())\n.ignoreNulls(Boolean.TRUE)\n.build())\n// 4. Variation of delete request that accepts a data object. The key\nvalues are extracted for the request.\n.addDeleteItem(movieActorTable, getMovieActorBlanchett())\n);\nMap objects to DynamoDB items 258\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nThe following helper methods provide the data objects for the add*Item parameters.", "mimetype": "text/plain", "start_char_idx": 461883, "end_char_idx": 466263, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5b5d5ba8-7870-4f93-b89c-bb205fc1e1b8": {"__data__": {"id_": "5b5d5ba8-7870-4f93-b89c-bb205fc1e1b8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "88ecf9dd-4580-4dbe-834f-012908511ff1", "node_type": "1", "metadata": {}, "hash": "b4ae35cf143ffe8d9ee289b411f41d20ab702a687805f340a890cbce4710d61e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "688d6c99-8576-4db4-b131-ff16b3434507", "node_type": "1", "metadata": {}, "hash": "c228a157d25e3d4c40e25017de379e55352d8ceb43bff9a1fe59eecb678b2237", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".addPutItem(movieActorTable,\nTransactPutItemEnhancedRequest.builder(MovieActor.class)\n.item(getMovieActorStreep())\n.conditionExpression(Expression.builder().expression(\"attribute_not_exists\n(movie)\").build())\n.build())\n// 3. Update request that does not remove attribute values on the table\nif the data object's value is null.\n.addUpdateItem(catalogTable,\nTransactUpdateItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId4ForUpdate())\n.ignoreNulls(Boolean.TRUE)\n.build())\n// 4. Variation of delete request that accepts a data object. The key\nvalues are extracted for the request.\n.addDeleteItem(movieActorTable, getMovieActorBlanchett())\n);\nMap objects to DynamoDB items 258\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nThe following helper methods provide the data objects for the add*Item parameters.\nHelper methods\npublic static ProductCatalog getProductCatId2() {\nreturn ProductCatalog.builder()\n.id(2)\n.isbn(\"1-565-85698\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\")))\n.price(BigDecimal.valueOf(30.22))\n.title(\"Title 55\")\n.build();\n}\npublic static ProductCatalog getProductCatId4ForUpdate() {\nreturn ProductCatalog.builder()\n.id(4)\n.price(BigDecimal.valueOf(40.00))\n.title(\"Title 1\")\n.build();\n}\npublic static MovieActor getMovieActorBlanchett() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Cate Blanchett\");\nmovieActor.setMovieName(\"Tar\");\nmovieActor.setActingYear(2022);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"National Institute of Dramatic Art\");\nreturn movieActor;\n}\npublic static MovieActor getMovieActorStreep() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Meryl Streep\");\nmovieActor.setMovieName(\"Sophie's Choice\");\nmovieActor.setActingYear(1982);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"Yale School of Drama\");\nreturn movieActor;\n}\nMap objects to DynamoDB items 259\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe DynamoDB tables contain the following items before the code example runs.\n1 | ProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\n2 | MovieActor{movieName='Tar', actorName='Cate Blanchett', actingAward='Best Actress',\nactingYear=2022, actingSchoolName='National Institute of Dramatic Art'}\nThe following items are in the tables after the code finishes running.\n3 | ProductCatalog{id=2, title='Title 55', isbn='1-565-85698', authors=[a, b],\nprice=30.22}\n4 | ProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=40.0}\n5 | MovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\nThe item on line 2 has been deleted and lines 3 and 5 show the items that were put. Line 4\nshows the update of line 1. The price value is the only value that changed on the item. If\nignoreNulls() had returned false, line 4 would look like the following line.\nProductCatalog{id=4, title='Title 1', isbn='null', authors=null, price=40.0}\nCondition check example\nThe following example shows the use of a condition check. A condition check is used to check that\nan item exists or to check the condition of specific attributes of an item in the database. The item\nchecked in the condition check cannot be used in another operation in the transaction.\nNote\nYou can't target the same item with multiple operations within the same transaction. For\nexample, you can't perform a condition check and also attempt to update the same item in\nthe same transaction.\nThe example shows one of each type of operation in a transactional write items request. After\ncomment line 2, the addConditionCheck() method supplies the condition that fails the\ntransaction if the conditionExpression parameter evaluates to false. The condition\nexpression that is returned from the method shown in the Helper methods block checks if the\naward year for the movie Sophie's Choice is not equal to 1982. If it is, the expression evaluates\nto false and the transaction fails.\nMap objects to DynamoDB items 260\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThis guide discusses expressions in depth in another topic.", "mimetype": "text/plain", "start_char_idx": 465431, "end_char_idx": 469631, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "688d6c99-8576-4db4-b131-ff16b3434507": {"__data__": {"id_": "688d6c99-8576-4db4-b131-ff16b3434507", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5b5d5ba8-7870-4f93-b89c-bb205fc1e1b8", "node_type": "1", "metadata": {}, "hash": "5d6f434eea189609a07065b2cf9995ad9c6c3f8fd60103b19692fa5efd39944b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b3101e47-d789-49f1-abab-14a2db0eacb1", "node_type": "1", "metadata": {}, "hash": "d9e160b568babcafb9d49afc65a3360788e9bbf6eda53ec7832b8bfe9535ce96", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The item\nchecked in the condition check cannot be used in another operation in the transaction.\nNote\nYou can't target the same item with multiple operations within the same transaction. For\nexample, you can't perform a condition check and also attempt to update the same item in\nthe same transaction.\nThe example shows one of each type of operation in a transactional write items request. After\ncomment line 2, the addConditionCheck() method supplies the condition that fails the\ntransaction if the conditionExpression parameter evaluates to false. The condition\nexpression that is returned from the method shown in the Helper methods block checks if the\naward year for the movie Sophie's Choice is not equal to 1982. If it is, the expression evaluates\nto false and the transaction fails.\nMap objects to DynamoDB items 260\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThis guide discusses expressions in depth in another topic.\npublic static void conditionCheckFailExample(DynamoDbEnhancedClient enhancedClient,\nDynamoDbTable\ncatalogTable,\nDynamoDbTable\nmovieActorTable) {\ntry {\nenhancedClient.transactWriteItems(b -> b\n// 1. Perform one of each type of operation with the next three\nmethods.\n.addPutItem(catalogTable,\nTransactPutItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId2()).build())\n.addUpdateItem(catalogTable,\nTransactUpdateItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId4ForUpdate())\n.ignoreNulls(Boolean.TRUE).build())\n.addDeleteItem(movieActorTable,\nTransactDeleteItemEnhancedRequest.builder()\n.key(b1 -> b1\n.partitionValue(getMovieActorBlanchett().getMovieName())\n.sortValue(getMovieActorBlanchett().getActorName())).build())\n// 2. Add a condition check on a table item that is not involved in\nanother operation in this request.\n.addConditionCheck(movieActorTable, ConditionCheck.builder()\n.conditionExpression(buildConditionCheckExpression())\n.key(k -> k\n.partitionValue(\"Sophie's Choice\")\n.sortValue(\"Meryl Streep\"))\n// 3. Specify the request to return existing values from\nthe item if the condition evaluates to true.\n.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)\n.build())\n.build());\n// 4. Catch the exception if the transaction fails and log the information.\n} catch (TransactionCanceledException ex) {\nex.cancellationReasons().stream().forEach(cancellationReason -> {\nlogger.info(cancellationReason.toString());\n});\nMap objects to DynamoDB items 261\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\nThe following helper methods are used in the previous code example.\nHelper methods\nprivate static Expression buildConditionCheckExpression() {\nMap expressionValue = Map.of(\n\":year\", numberValue(1982));\nreturn Expression.builder()\n.expression(\"actingyear <> :year\")\n.expressionValues(expressionValue)\n.build();\n}\npublic static ProductCatalog getProductCatId2() {\nreturn ProductCatalog.builder()\n.id(2)\n.isbn(\"1-565-85698\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\")))\n.price(BigDecimal.valueOf(30.22))\n.title(\"Title 55\")\n.build();\n}\npublic static ProductCatalog getProductCatId4ForUpdate() {\nreturn ProductCatalog.builder()\n.id(4)\n.price(BigDecimal.valueOf(40.00))\n.title(\"Title 1\")\n.build();\n}\npublic static MovieActor getMovieActorBlanchett() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Cate Blanchett\");\nmovieActor.setMovieName(\"Blue Jasmine\");\nmovieActor.setActingYear(2013);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"National Institute of Dramatic Art\");\nreturn movieActor;\nMap objects to DynamoDB items 262\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nThe DynamoDB tables contain the following items before the code example runs.\n1 | ProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\n2 | MovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\n3 | MovieActor{movieName='Tar', actorName='Cate Blanchett', actingAward='Best Actress',\nactingYear=2022, actingSchoolName='National Institute of Dramatic Art'}\nThe following items are in the tables after the code finishes running.", "mimetype": "text/plain", "start_char_idx": 468696, "end_char_idx": 472946, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b3101e47-d789-49f1-abab-14a2db0eacb1": {"__data__": {"id_": "b3101e47-d789-49f1-abab-14a2db0eacb1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "688d6c99-8576-4db4-b131-ff16b3434507", "node_type": "1", "metadata": {}, "hash": "c228a157d25e3d4c40e25017de379e55352d8ceb43bff9a1fe59eecb678b2237", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e90571c1-b7b9-4838-9c19-f3d8ededa619", "node_type": "1", "metadata": {}, "hash": "7568358baec1ca21324b59b12b3f43d2c28e6166435d9dcc1875c821f9103e6b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "1 | ProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\n2 | MovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\n3 | MovieActor{movieName='Tar', actorName='Cate Blanchett', actingAward='Best Actress',\nactingYear=2022, actingSchoolName='National Institute of Dramatic Art'}\nThe following items are in the tables after the code finishes running.\nProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\nMovieActor{movieName='Sophie's Choice', actorName='Meryl Streep', actingAward='Best\nActress', actingYear=1982, actingSchoolName='Yale School of Drama'}\nMovieActor{movieName='Tar', actorName='Cate Blanchett', actingAward='Best Actress',\nactingYear=2022, actingSchoolName='National Institute of Dramatic Art'}\nItems remain unchanged in the tables because the transaction failed. The actingYear value for\nthe movie Sophie's Choice is 1982, as shown on line 2 of the items in the table before the\ntransactWriteItem() method is called.\nTo capture the cancellation information for the transaction, enclose the transactWriteItems()\nmethod call in a try block and catch the TransactionCanceledException. After comment\nline 4 of the example, the code logs each CancellationReason object. Because the code\nfollowing comment line 3 of the example specifies that values should be returned for the item that\ncaused the transaction to fail, the log displays the raw database values for the Sophie's Choice\nmovie item.\nCancellationReason(Code=None)\nCancellationReason(Code=None)\nCancellationReason(Code=None)\nCancellationReason(Item={actor=AttributeValue(S=Meryl Streep),\nmovie=AttributeValue(S=Sophie's Choice), actingaward=AttributeValue(S=Best Actress),\nactingyear=AttributeValue(N=1982), actingschoolname=AttributeValue(S=Yale School of\nDrama)}, \u00ac\nCode=ConditionalCheckFailed, Message=The conditional request failed.)\nMap objects to DynamoDB items 263\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSingle operation condition example\nThe following example shows the use of a condition on a single operation in a transaction request.\nThe delete operation after comment line 1 contains a condition that checks the value of the target\nitem of the operation against the database. In this example, the condition expression created\nwith the helper method after comment line 2 specifies that the item should be deleted from the\ndatabase if the acting year of the movie is not equal to 2013.\nExpressions are discussed later in this guide.\npublic static void singleOperationConditionFailExample(DynamoDbEnhancedClient\nenhancedClient,\nDynamoDbTable catalogTable,\nDynamoDbTable\nmovieActorTable) {\ntry {\nenhancedClient.transactWriteItems(b -> b\n.addPutItem(catalogTable,\nTransactPutItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId2())\n.build())\n.addUpdateItem(catalogTable,\nTransactUpdateItemEnhancedRequest.builder(ProductCatalog.class)\n.item(getProductCatId4ForUpdate())\n.ignoreNulls(Boolean.TRUE).build())\n// 1. Delete operation that contains a condition expression\n.addDeleteItem(movieActorTable,\nTransactDeleteItemEnhancedRequest.builder()\n.key((Key.Builder k) -> {\nMovieActor blanchett = getMovieActorBlanchett();\nk.partitionValue(blanchett.getMovieName())\n.sortValue(blanchett.getActorName());\n})\n.conditionExpression(buildDeleteItemExpression())\n.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)\n.build())\n.build());\n} catch (TransactionCanceledException ex) {\nex.cancellationReasons().forEach(cancellationReason ->\nlogger.info(cancellationReason.toString()));\n}\nMap objects to DynamoDB items 264\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n// 2. Provide condition expression to check if 'actingyear' is not equal to 2013.\nprivate static Expression buildDeleteItemExpression() {\nMap expressionValue = Map.of(\n\":year\", numberValue(2013));\nreturn Expression.builder()\n.expression(\"actingyear <> :year\")\n.expressionValues(expressionValue)\n.build();\n}\nThe following helper methods are used in the previous code example.", "mimetype": "text/plain", "start_char_idx": 472474, "end_char_idx": 476653, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e90571c1-b7b9-4838-9c19-f3d8ededa619": {"__data__": {"id_": "e90571c1-b7b9-4838-9c19-f3d8ededa619", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b3101e47-d789-49f1-abab-14a2db0eacb1", "node_type": "1", "metadata": {}, "hash": "d9e160b568babcafb9d49afc65a3360788e9bbf6eda53ec7832b8bfe9535ce96", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f06f0b44-f1f5-45b2-9201-83d128513b9a", "node_type": "1", "metadata": {}, "hash": "27fb2a6091f001204dbb9f728490b32e47432656667569d404be8647ae4e5976", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Provide condition expression to check if 'actingyear' is not equal to 2013.\nprivate static Expression buildDeleteItemExpression() {\nMap expressionValue = Map.of(\n\":year\", numberValue(2013));\nreturn Expression.builder()\n.expression(\"actingyear <> :year\")\n.expressionValues(expressionValue)\n.build();\n}\nThe following helper methods are used in the previous code example.\nHelper methods\npublic static ProductCatalog getProductCatId2() {\nreturn ProductCatalog.builder()\n.id(2)\n.isbn(\"1-565-85698\")\n.authors(new HashSet<>(Arrays.asList(\"a\", \"b\")))\n.price(BigDecimal.valueOf(30.22))\n.title(\"Title 55\")\n.build();\n}\npublic static ProductCatalog getProductCatId4ForUpdate() {\nreturn ProductCatalog.builder()\n.id(4)\n.price(BigDecimal.valueOf(40.00))\n.title(\"Title 1\")\n.build();\n}\npublic static MovieActor getMovieActorBlanchett() {\nMovieActor movieActor = new MovieActor();\nmovieActor.setActorName(\"Cate Blanchett\");\nmovieActor.setMovieName(\"Blue Jasmine\");\nmovieActor.setActingYear(2013);\nmovieActor.setActingAward(\"Best Actress\");\nmovieActor.setActingSchoolName(\"National Institute of Dramatic Art\");\nreturn movieActor;\n}\nMap objects to DynamoDB items 265\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe DynamoDB tables contain the following items before the code example runs.\n1 | ProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\n2 | MovieActor{movieName='Blue Jasmine', actorName='Cate Blanchett', actingAward='Best\nActress', actingYear=2013, actingSchoolName='National Institute of Dramatic Art'}\nThe following items are in the tables after the code finishes running.\nProductCatalog{id=4, title='Title 1', isbn='orig_isbn', authors=[b, g], price=10}\n2023-03-15 11:29:07 [main] INFO org.example.tests.TransactDemoTest:168 -\nMovieActor{movieName='Blue Jasmine', actorName='Cate Blanchett', actingAward='Best\nActress', actingYear=2013, actingSchoolName='National Institute of Dramatic Art'}\nItems remain unchanged in the tables because the transaction failed. The actingYear value for\nthe movie Blue Jasmine is 2013 as shown on line 2 in the list of items before the code example\nruns.\nThe following lines are logged to the console.\nCancellationReason(Code=None)\nCancellationReason(Code=None)\nCancellationReason(Item={actor=AttributeValue(S=Cate Blanchett),\nmovie=AttributeValue(S=Blue Jasmine), actingaward=AttributeValue(S=Best Actress),\nactingyear=AttributeValue(N=2013), actingschoolname=AttributeValue(S=National\nInstitute of Dramatic Art)},\nCode=ConditionalCheckFailed, Message=The conditional request failed)\nUse secondary indices\nSecondary indices improve data access by defining alternative keys that you use in query and scan\noperations. Global secondary indices (GSI) have a partition key and a sort key that can be different\nfrom those on the base table. In contrast, local secondary indices (LSI) use the partition key of the\nprimary index.\nAnnotate data class with secondary index annotations\nAttributes that participate in secondary indices require either the\n@DynamoDbSecondaryPartitionKey or @DynamoDbSecondarySortKey annotation.\nThe following class shows annotations for two indices. The GSI named SubjectLastPostedDateIndex\nuses the Subject attribute for the partition key and the LastPostedDateTime for the sort\nMap objects to DynamoDB items 266\nAWS SDK for Java 2.x Developer Guide for version 2.x\nkey. The LSI named ForumLastPostedDateIndex uses the ForumName as its partition key and\nLastPostedDateTime as its sort key.\nNote that the Subject attribute serves a dual role. It is the primary key's sort key and the partition\nkey of the GSI named SubjectLastPostedDateIndex.\nMessageThread class\nThe MessageThread class is suitable to use as a data class for the example Thread table in the\nAmazon DynamoDB Developer Guide.", "mimetype": "text/plain", "start_char_idx": 476261, "end_char_idx": 480061, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f06f0b44-f1f5-45b2-9201-83d128513b9a": {"__data__": {"id_": "f06f0b44-f1f5-45b2-9201-83d128513b9a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e90571c1-b7b9-4838-9c19-f3d8ededa619", "node_type": "1", "metadata": {}, "hash": "7568358baec1ca21324b59b12b3f43d2c28e6166435d9dcc1875c821f9103e6b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "00ad3afc-b3dd-4fbc-97a0-cde939f32086", "node_type": "1", "metadata": {}, "hash": "037e9bc24e4c8b6905b14488ec65ab67c14320f3c5a600d52186a2f493958e4a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Annotate data class with secondary index annotations\nAttributes that participate in secondary indices require either the\n@DynamoDbSecondaryPartitionKey or @DynamoDbSecondarySortKey annotation.\nThe following class shows annotations for two indices. The GSI named SubjectLastPostedDateIndex\nuses the Subject attribute for the partition key and the LastPostedDateTime for the sort\nMap objects to DynamoDB items 266\nAWS SDK for Java 2.x Developer Guide for version 2.x\nkey. The LSI named ForumLastPostedDateIndex uses the ForumName as its partition key and\nLastPostedDateTime as its sort key.\nNote that the Subject attribute serves a dual role. It is the primary key's sort key and the partition\nkey of the GSI named SubjectLastPostedDateIndex.\nMessageThread class\nThe MessageThread class is suitable to use as a data class for the example Thread table in the\nAmazon DynamoDB Developer Guide.\nImports\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;\nimport\nsoftware.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey;\nimport software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;\nimport java.util.List;\n@DynamoDbBean\npublic class MessageThread {\nprivate String ForumName;\nprivate String Subject;\nprivate String Message;\nprivate String LastPostedBy;\nprivate String LastPostedDateTime;\nprivate Integer Views;\nprivate Integer Replies;\nprivate Integer Answered;\nprivate List Tags;\n@DynamoDbPartitionKey\npublic String getForumName() {\nreturn ForumName;\n}\npublic void setForumName(String forumName) {\nForumName = forumName;\nMap objects to DynamoDB items 267\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n// Sort key for primary index and partition key for GSI\n\"SubjectLastPostedDateIndex\".\n@DynamoDbSortKey\n@DynamoDbSecondaryPartitionKey(indexNames = \"SubjectLastPostedDateIndex\")\npublic String getSubject() {\nreturn Subject;\n}\npublic void setSubject(String subject) {\nSubject = subject;\n}\n// Sort key for GSI \"SubjectLastPostedDateIndex\" and sort key for LSI\n\"ForumLastPostedDateIndex\".\n@DynamoDbSecondarySortKey(indexNames = {\"SubjectLastPostedDateIndex\",\n\"ForumLastPostedDateIndex\"})\npublic String getLastPostedDateTime() {\nreturn LastPostedDateTime;\n}\npublic void setLastPostedDateTime(String lastPostedDateTime) {\nLastPostedDateTime = lastPostedDateTime;\n}\npublic String getMessage() {\nreturn Message;\n}\npublic void setMessage(String message) {\nMessage = message;\n}\npublic String getLastPostedBy() {\nreturn LastPostedBy;\n}\npublic void setLastPostedBy(String lastPostedBy) {\nLastPostedBy = lastPostedBy;\n}\npublic Integer getViews() {\nreturn Views;\n}\nMap objects to DynamoDB items 268\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void setViews(Integer views) {\nViews = views;\n}\n@DynamoDbSecondaryPartitionKey(indexNames = \"ForumRepliesIndex\")\npublic Integer getReplies() {\nreturn Replies;\n}\npublic void setReplies(Integer replies) {\nReplies = replies;\n}\npublic Integer getAnswered() {\nreturn Answered;\n}\npublic void setAnswered(Integer answered) {\nAnswered = answered;\n}\npublic List getTags() {\nreturn Tags;\n}\npublic void setTags(List tags) {\nTags = tags;\n}\npublic MessageThread() {\nthis.Answered = 0;\nthis.LastPostedBy = \"\";\nthis.ForumName = \"\";\nthis.Message = \"\";\nthis.LastPostedDateTime = \"\";\nthis.Replies = 0;\nthis.Views = 0;\nthis.Subject = \"\";\n}\n@Override\npublic String toString() {\nreturn \"MessageThread{\" +\nMap objects to DynamoDB items 269\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"ForumName='\" + ForumName + '\\'' +\n\", Subject='\" + Subject + '\\'' +\n\", Message='\" + Message + '\\'' +\n\", LastPostedBy='\" + LastPostedBy + '\\'' +\n\", LastPostedDateTime='\" + LastPostedDateTime + '\\'' +\n\", Views=\" + Views +\n\", Replies=\" + Replies +\n\", Answered=\" + Answered +\n\", Tags=\" + Tags +\n'}';\n}\n}\nCreate the index\nBeginning with version 2.20.86 of the SDK for Java, the createTable() method automatically\ngenerates secondary indexes from data class annotations. By default, all attributes from the base\ntable are copied to an index and the provisioned throughput values are 20 read capacity units and\n20 write capacity units.", "mimetype": "text/plain", "start_char_idx": 479173, "end_char_idx": 483509, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "00ad3afc-b3dd-4fbc-97a0-cde939f32086": {"__data__": {"id_": "00ad3afc-b3dd-4fbc-97a0-cde939f32086", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f06f0b44-f1f5-45b2-9201-83d128513b9a", "node_type": "1", "metadata": {}, "hash": "27fb2a6091f001204dbb9f728490b32e47432656667569d404be8647ae4e5976", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9d734949-8064-44c6-8832-1debb7b49355", "node_type": "1", "metadata": {}, "hash": "7059885696ffa1ba2585891103c005644134b1dfd3d969bb58450150d9f4eeb7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "By default, all attributes from the base\ntable are copied to an index and the provisioned throughput values are 20 read capacity units and\n20 write capacity units.\nHowever, if you use an SDK version prior to 2.20.86, you need to build the index along with the\ntable as shown in the following example. This example builds the two indexes for the Thread\ntable. The builder parameter has methods to configure both types of indexes as shown after\ncomment lines 1 and 2. You use the index builder's indexName() method to associate the index\nnames specified in the data class annotations with the intended type of index.\nThis code configures all of the table attributes to end up in both indexes after comment lines 3 and\n4. More information about attribute projections is available in the Amazon DynamoDB Developer\nGuide.\npublic static void createMessageThreadTable(DynamoDbTable\nmessageThreadDynamoDbTable, DynamoDbClient dynamoDbClient) {\nmessageThreadDynamoDbTable.createTable(b -> b\n// 1. Generate the GSI.\n.globalSecondaryIndices(gsi ->\ngsi.indexName(\"SubjectLastPostedDateIndex\")\n// 3. Populate the GSI with all attributes.\n.projection(p -> p\n.projectionType(ProjectionType.ALL))\n)\n// 2. Generate the LSI.\n.localSecondaryIndices(lsi -> lsi.indexName(\"ForumLastPostedDateIndex\")\nMap objects to DynamoDB items 270\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// 4. Populate the LSI with all attributes.\n.projection(p -> p\n.projectionType(ProjectionType.ALL))\n)\n);\nQuery by using an index\nThe following example queries the local secondary index ForumLastPostedDateIndex.\nFollowing comment line 2, you create a QueryConditional object that is required when calling the\nDynamoDbIndex.query() method.\nYou get a reference to the index you want to query after comment line 3 by passing in the name\nof the index. Following comment line 4, you call the query() method on the index passing in the\nQueryConditional object.\nYou also configure the query to return three attribute values as shown after comment line 5. If\nattributesToProject() is not called, the query returns all attribute values. Notice that the\nspecified attribute names begin with lowercase letters. These attribute names match those used in\nthe table, not necessarily the attribute names of the data class.\nFollowing comment line 6, iterate through the results and log each item returned by the query and\nalso store it in the list to return to the caller.\npublic static List queryUsingSecondaryIndices(DynamoDbEnhancedClient\nenhancedClient,\nString lastPostedDate,\nDynamoDbTable threadTable) {\n// 1. Log the parameter value.\nlogger.info(\"lastPostedDate value: {}\", lastPostedDate);\n// 2. Create a QueryConditional whose sort key value must be greater than or\nequal to the parameter value.\nQueryConditional queryConditional =\nQueryConditional.sortGreaterThanOrEqualTo(qc ->\nqc.partitionValue(\"Forum02\").sortValue(lastPostedDate));\n// 3. Specify the index name to query the DynamoDbIndex instance.\nfinal DynamoDbIndex forumLastPostedDateIndex =\nthreadTable.index(\"ForumLastPostedDateIndex\");\nMap objects to DynamoDB items 271\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// 4. Perform the query by using the QueryConditional object.\nfinal SdkIterable> pagedResult =\nforumLastPostedDateIndex.query(q -> q\n.queryConditional(queryConditional)\n// 5. Request three attribute in the results.\n.attributesToProject(\"forumName\", \"subject\", \"lastPostedDateTime\"));\nList collectedItems = new ArrayList<>();\n// 6. Iterate through the pages response and sort the items.\npagedResult.stream().forEach(page -> page.items().stream()\n.sorted(Comparator.comparing(MessageThread::getLastPostedDateTime))\n.forEach(mt -> {\n// 7. Log the returned items and add the collection to\nreturn to the caller.\nlogger.info(mt.toString());\ncollectedItems.add(mt);\n}));\nreturn collectedItems;\n}\nThe following items exist in the database before the query is run.", "mimetype": "text/plain", "start_char_idx": 483346, "end_char_idx": 487338, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9d734949-8064-44c6-8832-1debb7b49355": {"__data__": {"id_": "9d734949-8064-44c6-8832-1debb7b49355", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "00ad3afc-b3dd-4fbc-97a0-cde939f32086", "node_type": "1", "metadata": {}, "hash": "037e9bc24e4c8b6905b14488ec65ab67c14320f3c5a600d52186a2f493958e4a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "69236577-29b9-4dbd-98d7-f550c8d08e0a", "node_type": "1", "metadata": {}, "hash": "cae147e66095fff811b3cd55533b7c9d6a483c08e968b0525924fee27ed0da90", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Perform the query by using the QueryConditional object.\nfinal SdkIterable> pagedResult =\nforumLastPostedDateIndex.query(q -> q\n.queryConditional(queryConditional)\n// 5. Request three attribute in the results.\n.attributesToProject(\"forumName\", \"subject\", \"lastPostedDateTime\"));\nList collectedItems = new ArrayList<>();\n// 6. Iterate through the pages response and sort the items.\npagedResult.stream().forEach(page -> page.items().stream()\n.sorted(Comparator.comparing(MessageThread::getLastPostedDateTime))\n.forEach(mt -> {\n// 7. Log the returned items and add the collection to\nreturn to the caller.\nlogger.info(mt.toString());\ncollectedItems.add(mt);\n}));\nreturn collectedItems;\n}\nThe following items exist in the database before the query is run.\nMessageThread{ForumName='Forum01', Subject='Subject01', Message='Message01',\nLastPostedBy='', LastPostedDateTime='2023.03.28', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum02', Subject='Subject02', Message='Message02',\nLastPostedBy='', LastPostedDateTime='2023.03.29', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum02', Subject='Subject04', Message='Message04',\nLastPostedBy='', LastPostedDateTime='2023.03.31', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum02', Subject='Subject08', Message='Message08',\nLastPostedBy='', LastPostedDateTime='2023.04.04', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum02', Subject='Subject10', Message='Message10',\nLastPostedBy='', LastPostedDateTime='2023.04.06', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum03', Subject='Subject03', Message='Message03',\nLastPostedBy='', LastPostedDateTime='2023.03.30', Views=0, Replies=0, Answered=0,\nTags=null}\nMap objects to DynamoDB items 272\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMessageThread{ForumName='Forum03', Subject='Subject06', Message='Message06',\nLastPostedBy='', LastPostedDateTime='2023.04.02', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum03', Subject='Subject09', Message='Message09',\nLastPostedBy='', LastPostedDateTime='2023.04.05', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum05', Subject='Subject05', Message='Message05',\nLastPostedBy='', LastPostedDateTime='2023.04.01', Views=0, Replies=0, Answered=0,\nTags=null}\nMessageThread{ForumName='Forum07', Subject='Subject07', Message='Message07',\nLastPostedBy='', LastPostedDateTime='2023.04.03', Views=0, Replies=0, Answered=0,\nTags=null}\nThe logging statements at lines 1 and 6 result in the following console output.\nlastPostedDate value: 2023.03.31\nMessageThread{ForumName='Forum02', Subject='Subject04', Message='', LastPostedBy='',\nLastPostedDateTime='2023.03.31', Views=0, Replies=0, Answered=0, Tags=null}\nMessageThread{ForumName='Forum02', Subject='Subject08', Message='', LastPostedBy='',\nLastPostedDateTime='2023.04.04', Views=0, Replies=0, Answered=0, Tags=null}\nMessageThread{ForumName='Forum02', Subject='Subject10', Message='', LastPostedBy='',\nLastPostedDateTime='2023.04.06', Views=0, Replies=0, Answered=0, Tags=null}\nThe query returned items with a forumName value of Forum02 and a lastPostedDateTime\nvalue greater than or equal to 2023.03.31. The results show message values with an empty string\nalthough the message attributes have values in the index. This is because the message attribute\nwas not projected after comment line 5.\nUse advanced mapping features\nLearn about advanced table schema features in the DynamoDB Enhanced Client API.\nUnderstand table schema types\nTableSchema is the interface to the mapping functionality of the DynamoDB Enhanced Client\nAPI. It can map a data object to and from a map of AttributeValues. A TableSchema object needs\nto know about the structure of the table it is mapping.", "mimetype": "text/plain", "start_char_idx": 486554, "end_char_idx": 490418, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "69236577-29b9-4dbd-98d7-f550c8d08e0a": {"__data__": {"id_": "69236577-29b9-4dbd-98d7-f550c8d08e0a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9d734949-8064-44c6-8832-1debb7b49355", "node_type": "1", "metadata": {}, "hash": "7059885696ffa1ba2585891103c005644134b1dfd3d969bb58450150d9f4eeb7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4e5ceaf7-d972-43d5-a79e-c5cf703f4023", "node_type": "1", "metadata": {}, "hash": "ded3a4ab86b857bf0aab8a0e6ce8f309f47f581457b4c8972d5db74a40a6185c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The results show message values with an empty string\nalthough the message attributes have values in the index. This is because the message attribute\nwas not projected after comment line 5.\nUse advanced mapping features\nLearn about advanced table schema features in the DynamoDB Enhanced Client API.\nUnderstand table schema types\nTableSchema is the interface to the mapping functionality of the DynamoDB Enhanced Client\nAPI. It can map a data object to and from a map of AttributeValues. A TableSchema object needs\nto know about the structure of the table it is mapping. This structure information is stored in a\nTableMetadata object.\nThe enhanced client API has several implementations of TableSchema, which follow.\nMap objects to DynamoDB items 273\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTable schema generated from annotated classes\nIt is a moderately expensive operation to build a TableSchema from annotated classes, so we\nrecommend doing this once, at application startup.\nBeanTableSchema\nThis implementation is built based on attributes and annotations of a bean class. An example of\nthis approach is demonstrated in the Get started section.\nNote\nIf a BeanTableSchema is not behaving as you expect, enable debug logging for\nsoftware.amazon.awssdk.enhanced.dynamodb.beans.\nImmutableTableSchema\nThis implementation is built from an immutable data class. This approach is described in the ???\nsection.\nTable schema generated with a builder\nThe following TableSchemas are built from code by using a builder. This approach is less costly\nthan the approach that uses annotated data classes. The builder approach avoids the use of\nannotations and doesn't require JavaBean naming standards.\nStaticTableSchema\nThis implementation is built for mutable data classes. The getting started section of this guide\ndemonstrated how to generate a StaticTableSchema using a builder.\nStaticImmutableTableSchema\nSimilarly to how you build a StaticTableSchema, you generate an implementation of this\ntype of TableSchema using a builder for use with immutable data classes.\nMap objects to DynamoDB items 274\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTable schema for data without a fixed schema\nDocumentTableSchema\nUnlike other implementations of TableSchema, you don't define attributes for a\nDocumentTableSchema instance. Usually, you specify only primary keys and attribute\nconverter providers. An EnhancedDocument instance provides the attributes that you build\nfrom individual elements or from a JSON string.\nExplicitly include or exclude attributes\nThe DynamoDB Enhanced Client API offers annotations to exclude data class attributes from\nbecoming attributes on a table. With the API, you can also use an attribute name that's different\nfrom the data class attribute name.\nExclude attributes\nTo ignore attributes that should not be mapped to a DynamoDB table, mark the attribute with the\n@DynamoDbIgnore annotation.\nprivate String internalKey;\n@DynamoDbIgnore\npublic String getInternalKey() { return this.internalKey; }\npublic void setInternalKey(String internalKey) { this.internalKey = internalKey;}\nInclude attributes\nTo change the name of an attribute used in the DynamoDB table, mark it with the\n@DynamoDbAttribute annotation and supply a different name.\nprivate String internalKey;\n@DynamoDbAttribute(\"renamedInternalKey\")\npublic String getInternalKey() { return this.internalKey; }\npublic void setInternalKey(String internalKey) { this.internalKey = internalKey;}\nControl attribute conversion\nBy default, a table schema provides converters for many common Java types through a default\nimplementation of the AttributeConverterProvider interface. You can change the overall\nMap objects to DynamoDB items 275\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndefault behavior with a custom AttributeConverterProvider implementation. You can also\nchange the converter for a single attribute.\nFor a list of available converters, see the AttributeConverter interface Java doc.\nProvide custom attribute converter providers\nYou can provide a single AttributeConverterProvider or a chain of ordered\nAttributeConverterProviders through the @DynamoDbBean (converterProviders\n= {\u2026}) annotation. Any custom AttributeConverterProvider must extend the\nAttributeConverterProvider interface.\nNote that if you supply your own chain of attribute converter providers, you will override the\ndefault converter provider, DefaultAttributeConverterProvider. If you want to use the\nfunctionality of the DefaultAttributeConverterProvider, you must include it in the chain.\nIt's also possible to annotate the bean with an empty array {}. This disables the use of any\nattribute converter providers, including the default. In this case all attributes that are to be\nmapped must have their own attribute converter.\nThe following snippet shows a single converter provider.\n@DynamoDbBean(converterProviders = ConverterProvider1.class)\npublic class Customer {\n}\nThe following snippet shows the use of a chain of converter providers. Since the SDK default is\nprovided last, it has the lowest priority.", "mimetype": "text/plain", "start_char_idx": 489849, "end_char_idx": 494939, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4e5ceaf7-d972-43d5-a79e-c5cf703f4023": {"__data__": {"id_": "4e5ceaf7-d972-43d5-a79e-c5cf703f4023", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "69236577-29b9-4dbd-98d7-f550c8d08e0a", "node_type": "1", "metadata": {}, "hash": "cae147e66095fff811b3cd55533b7c9d6a483c08e968b0525924fee27ed0da90", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fb4a951e-7347-486c-9a6f-a074adfbedef", "node_type": "1", "metadata": {}, "hash": "a559a6b5298d3ce7ba4bbfd6398d2f7fddae0467a99bbb62fb74157a905d6cc3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Any custom AttributeConverterProvider must extend the\nAttributeConverterProvider interface.\nNote that if you supply your own chain of attribute converter providers, you will override the\ndefault converter provider, DefaultAttributeConverterProvider. If you want to use the\nfunctionality of the DefaultAttributeConverterProvider, you must include it in the chain.\nIt's also possible to annotate the bean with an empty array {}. This disables the use of any\nattribute converter providers, including the default. In this case all attributes that are to be\nmapped must have their own attribute converter.\nThe following snippet shows a single converter provider.\n@DynamoDbBean(converterProviders = ConverterProvider1.class)\npublic class Customer {\n}\nThe following snippet shows the use of a chain of converter providers. Since the SDK default is\nprovided last, it has the lowest priority.\n@DynamoDbBean(converterProviders = {\nConverterProvider1.class,\nConverterProvider2.class,\nDefaultAttributeConverterProvider.class})\npublic class Customer {\n}\nThe static table schema builders have an attributeConverterProviders() method that works\nthe same way. This is shown in the following snippet.\nMap objects to DynamoDB items 276\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static final StaticTableSchema CUSTOMER_TABLE_SCHEMA =\nStaticTableSchema.builder(Customer.class)\n.newItemSupplier(Customer::new)\n.addAttribute(String.class, a -> a.name(\"name\")\na.getter(Customer::getName)\na.setter(Customer::setName))\n.attributeConverterProviders(converterProvider1, converterProvider2)\n.build();\nOverride the mapping of a single attribute\nTo override the way a single attribute is mapped, supply an AttributeConverter for the\nattribute. This addition overrides any converters provided by AttributeConverterProviders\nin the table schema. This adds a custom converter for only that attribute. Other attributes, even\nthose of the same type, won't use that converter unless it is explicitly specified for those other\nattributes.\nThe @DynamoDbConvertedBy annotation is used to specify the custom AttributeConverter\nclass as shown in the following snippet.\n@DynamoDbBean\npublic class Customer {\nprivate String name;\n@DynamoDbConvertedBy(CustomAttributeConverter.class)\npublic String getName() { return this.name; }\npublic void setName(String name) { this.name = name;}\n}\nThe builders for static schemas have an equivalent attribute builder attributeConverter()\nmethod. This method takes an instance of an AttributeConverter as the following shows.\nprivate static final StaticTableSchema CUSTOMER_TABLE_SCHEMA =\nStaticTableSchema.builder(Customer.class)\n.newItemSupplier(Customer::new)\n.addAttribute(String.class, a -> a.name(\"name\")\na.getter(Customer::getName)\na.setter(Customer::setName)\na.attributeConverter(customAttributeConverter))\n.build();\nMap objects to DynamoDB items 277\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExample\nThis example shows an AttributeConverterProvider implementation that provides an\nattribute converter for java.net.HttpCookie objects.\nThe following SimpleUser class contains an attribute named lastUsedCookie that is an\ninstance of HttpCookie.\nThe parameter to the @DynamoDbBean annotations lists the two\nAttributeConverterProvider classes that provide converters.\nClass with annotations\n@DynamoDbBean(converterProviders = {CookieConverterProvider.class,\nDefaultAttributeConverterProvider.class})\npublic static final class SimpleUser {\nprivate String name;\nprivate HttpCookie lastUsedCookie;\n@DynamoDbPartitionKey\npublic String getName() {\nreturn name;\n}\npublic void setName(String name) {\nthis.name = name;\n}\npublic HttpCookie getLastUsedCookie() {\nreturn lastUsedCookie;\n}\npublic void setLastUsedCookie(HttpCookie lastUsedCookie) {\nthis.lastUsedCookie = lastUsedCookie;\n}\nStatic table schema\nprivate static final TableSchema SIMPLE_USER_TABLE_SCHEMA =\nTableSchema.builder(SimpleUser.class)\n.newItemSupplier(SimpleUser::new)\n.attributeConverterProviders(CookieConverterProvider.create(),\nAttributeConverterProvider.defaultProvider())\nMap objects to DynamoDB items 278\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.addAttribute(String.class, a -> a.name(\"name\")\n.setter(SimpleUser::setName)\n.getter(SimpleUser::getName)\n.tags(StaticAttributeTags.primaryPartitionKey()))\n.addAttribute(HttpCookie.class, a -> a.name(\"lastUsedCookie\")\n.setter(SimpleUser::setLastUsedCookie)\n.getter(SimpleUser::getLastUsedCookie))\n.build();\nThe CookieConverterProvider in the following example provides an instance of an\nHttpCookeConverter.\npublic static final class CookieConverterProvider implements\nAttributeConverterProvider {\nprivate final Map, AttributeConverter> converterCache =\nImmutableMap.of(\n// 1. Add HttpCookieConverter to the internal cache.", "mimetype": "text/plain", "start_char_idx": 494056, "end_char_idx": 498882, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fb4a951e-7347-486c-9a6f-a074adfbedef": {"__data__": {"id_": "fb4a951e-7347-486c-9a6f-a074adfbedef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4e5ceaf7-d972-43d5-a79e-c5cf703f4023", "node_type": "1", "metadata": {}, "hash": "ded3a4ab86b857bf0aab8a0e6ce8f309f47f581457b4c8972d5db74a40a6185c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d7d515bc-fc64-4d34-80ae-5d4830795c08", "node_type": "1", "metadata": {}, "hash": "8898e035990c7eff9d3e58e3c4c8e59cc06d871b70759052c2fdfd7b73a656ef", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static final class CookieConverterProvider implements\nAttributeConverterProvider {\nprivate final Map, AttributeConverter> converterCache =\nImmutableMap.of(\n// 1. Add HttpCookieConverter to the internal cache.\nEnhancedType.of(HttpCookie.class), new HttpCookieConverter());\npublic static CookieConverterProvider create() {\nreturn new CookieConverterProvider();\n}\n// The SDK calls this method to find out if the provider contains a\nAttributeConverter instance\n// for the EnhancedType argument.\n@SuppressWarnings(\"unchecked\")\n@Override\npublic AttributeConverter converterFor(EnhancedType enhancedType) {\nreturn (AttributeConverter) converterCache.get(enhancedType);\n}\n}\nConversion code\nIn the transformFrom() method of the following HttpCookieConverter class, the code\nreceives an HttpCookie instance and transforms it into a DynamoDB map that is stored as an\nattribute.\nThe transformTo() method receives a DynamoDB map parameter, then invokes the\nHttpCookie constructor that requires a name and a value.\nMap objects to DynamoDB items 279\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static final class HttpCookieConverter implements\nAttributeConverter {\n@Override\npublic AttributeValue transformFrom(HttpCookie httpCookie) {\nreturn AttributeValue.fromM(\nMap.of (\"cookieName\", AttributeValue.fromS(httpCookie.getName()),\n\"cookieValue\", AttributeValue.fromS(httpCookie.getValue()))\n);\n}\n@Override\npublic HttpCookie transformTo(AttributeValue attributeValue) {\nMap map = attributeValue.m();\nreturn new HttpCookie(\nmap.get(\"cookieName\").s(),\nmap.get(\"cookieValue\").s());\n}\n@Override\npublic EnhancedType type() {\nreturn EnhancedType.of(HttpCookie.class);\n}\n@Override\npublic AttributeValueType attributeValueType() {\nreturn AttributeValueType.M;\n}\n}\nChange update behavior of attributes\nYou can customize the update behavior of individual attributes when you perform an update\noperation. Some examples of update operations in the DynamoDB Enhanced Client API are\nupdateItem() and transactWriteItems().\nFor example, imagine that you want to store a created on timestamp on your record. However,\nyou want its value to be written only if there's no existing value for the attribute already in the\ndatabase. In this case, you use the WRITE_IF_NOT_EXISTS update behavior.\nThe following example shows the annotation that adds the behavior to the createdOn attribute.\nMap objects to DynamoDB items 280\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@DynamoDbBean\npublic class Customer extends GenericRecord {\nprivate String id;\nprivate Instant createdOn;\n@DynamoDbPartitionKey\npublic String getId() { return this.id; }\npublic void setId(String id) { this.name = id; }\n@DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)\npublic Instant getCreatedOn() { return this.createdOn; }\npublic void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; }\n}\nYou can declare the same update behavior when you build a static table schema as shown in the\nfollowing example after comment line 1.\nstatic final TableSchema CUSTOMER_TABLE_SCHEMA =\nTableSchema.builder(Customer.class)\n.newItemSupplier(Customer::new)\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(Customer::getId)\n.setter(Customer::setId)\n.tags(StaticAttributeTags.primaryPartitionKey()))\n.addAttribute(Instant.class, a -> a.name(\"createdOn\")\n.getter(Customer::getCreatedOn)\n.setter(Customer::setCreatedOn)\n// 1. Add an UpdateBehavior.\n.tags(StaticAttributeTags.updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)))\n.build();\nFlatten attributes from other classes\nIf the attributes for your table are spread across several different Java classes, either through\ninheritance or composition, the DynamoDB Enhanced Client API provides support to flatten the\nattributes into one class.\nUse inheritance\nIf your classes use inheritance, use the following approaches to flatten the hierarchy.\nMap objects to DynamoDB items 281\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse annotated beans\nFor the annotation approach, both classes must carry the @DynamoDbBean annotation and a class\nmust carry one or more primary key annotations.\nThe following shows examples of data classes that have an inheritance relationship.", "mimetype": "text/plain", "start_char_idx": 498648, "end_char_idx": 502941, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d7d515bc-fc64-4d34-80ae-5d4830795c08": {"__data__": {"id_": "d7d515bc-fc64-4d34-80ae-5d4830795c08", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fb4a951e-7347-486c-9a6f-a074adfbedef", "node_type": "1", "metadata": {}, "hash": "a559a6b5298d3ce7ba4bbfd6398d2f7fddae0467a99bbb62fb74157a905d6cc3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1539c246-2a12-4348-a793-9c0090deaee1", "node_type": "1", "metadata": {}, "hash": "8f42e47c9635bc2e6f92db86e2cd3e92fbecbe5a52e33c9375ca67540e9ada91", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Add an UpdateBehavior.\n.tags(StaticAttributeTags.updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)))\n.build();\nFlatten attributes from other classes\nIf the attributes for your table are spread across several different Java classes, either through\ninheritance or composition, the DynamoDB Enhanced Client API provides support to flatten the\nattributes into one class.\nUse inheritance\nIf your classes use inheritance, use the following approaches to flatten the hierarchy.\nMap objects to DynamoDB items 281\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse annotated beans\nFor the annotation approach, both classes must carry the @DynamoDbBean annotation and a class\nmust carry one or more primary key annotations.\nThe following shows examples of data classes that have an inheritance relationship.\nStandard data class\n@DynamoDbBean\npublic class Customer extends GenericRecord {\nprivate String name;\npublic String getName() { return name; }\npublic void setName(String name) { this.name = name; }\n}\n@DynamoDbBean\npublic abstract class GenericRecord {\nprivate String id;\nprivate String createdDate;\n@DynamoDbPartitionKey\npublic String getId() { return id; }\npublic void setId(String id) { this.id = id; }\npublic String getCreatedDate() { return createdDate; }\npublic void setCreatedDate(String createdDate) { this.createdDate =\ncreatedDate; }\n}\nLombok\nLombok's onMethod option copies attribute-based DynamoDB annotations, such as\n@DynamoDbPartitionKey, onto the generated code.\n@DynamoDbBean\n@Data\n@ToString(callSuper = true)\npublic class Customer extends GenericRecord {\nprivate String name;\n}\nMap objects to DynamoDB items 282\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Data\n@DynamoDbBean\npublic abstract class GenericRecord {\n@Getter(onMethod_=@DynamoDbPartitionKey)\nprivate String id;\nprivate String createdDate;\n}\nUse static schemas\nFor the static schema approach, use the extend() method of the builder to collapse the attributes\nof the parent class onto the child class. This is shown after comment line 1 in the following\nexample.\nStaticTableSchema\nGENERIC_RECORD_SCHEMA =\nStaticTableSchema.builder(org.example.tests.model.inheritance.stat.GenericRecord.class)\n// The partition key will be inherited by the top level mapper.\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(org.example.tests.model.inheritance.stat.GenericRecord::getId)\n.setter(org.example.tests.model.inheritance.stat.GenericRecord::setId)\n.tags(primaryPartitionKey()))\n.addAttribute(String.class, a -> a.name(\"created_date\")\n.getter(org.example.tests.model.inheritance.stat.GenericRecord::getCreatedDate)\n.setter(org.example.tests.model.inheritance.stat.GenericRecord::setCreatedDate))\n.build();\nStaticTableSchema\nCUSTOMER_SCHEMA =\nStaticTableSchema.builder(org.example.tests.model.inheritance.stat.Customer.class)\n.newItemSupplier(org.example.tests.model.inheritance.stat.Customer::new)\n.addAttribute(String.class, a -> a.name(\"name\")\n.getter(org.example.tests.model.inheritance.stat.Customer::getName)\nMap objects to DynamoDB items 283\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.setter(org.example.tests.model.inheritance.stat.Customer::setName))\n// 1. Use the extend() method to collapse the parent attributes\nonto the child class.\n.extend(GENERIC_RECORD_SCHEMA) // All the attributes of the\nGenericRecord schema are added to Customer.\n.build();\nThe previous static schema example uses the following data classes. Because the mapping is\ndefined when you build the static table schema, the data classes don't require annotations.\nData classes\nStandard data class\npublic class Customer extends GenericRecord {\nprivate String name;\npublic String getName() { return name; }\npublic void setName(String name) { this.name = name; }\n}\npublic abstract class GenericRecord {\nprivate String id;\nprivate String createdDate;\npublic String getId() { return id; }\npublic void setId(String id) { this.id = id; }\npublic String getCreatedDate() { return createdDate; }\npublic void setCreatedDate(String createdDate) { this.createdDate =\ncreatedDate; }\nLombok\n@Data\n@ToString(callSuper = true)\npublic class Customer extends GenericRecord{\nprivate String name;\n}\n@Data\nMap objects to DynamoDB items 284\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic abstract class GenericRecord {\nprivate String id;\nprivate String createdDate;\n}\nUse composition\nIf your classes use composition, use the following approaches to flatten the hierarchy.\nUse annotated beans\nThe @DynamoDbFlatten annotation flattens the contained class.\nThe following data class examples use the @DynamoDbFlatten annotation to effectively add all\nattributes of the contained GenericRecord class to the Customer class.", "mimetype": "text/plain", "start_char_idx": 502137, "end_char_idx": 506927, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1539c246-2a12-4348-a793-9c0090deaee1": {"__data__": {"id_": "1539c246-2a12-4348-a793-9c0090deaee1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d7d515bc-fc64-4d34-80ae-5d4830795c08", "node_type": "1", "metadata": {}, "hash": "8898e035990c7eff9d3e58e3c4c8e59cc06d871b70759052c2fdfd7b73a656ef", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "900ecc94-c531-4e54-a93b-e3171190522f", "node_type": "1", "metadata": {}, "hash": "a0e8e3af2bdc6c16e3291ab385fc4f9a54ef0860f9982dc6f4de6dc0d25a8590", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use annotated beans\nThe @DynamoDbFlatten annotation flattens the contained class.\nThe following data class examples use the @DynamoDbFlatten annotation to effectively add all\nattributes of the contained GenericRecord class to the Customer class.\nStandard data class\n@DynamoDbBean\npublic class Customer {\nprivate String name;\nprivate GenericRecord record;\npublic String getName() { return this.name; }\npublic void setName(String name) { this.name = name; }\n@DynamoDbFlatten\npublic GenericRecord getRecord() { return this.record; }\npublic void setRecord(GenericRecord record) { this.record = record; }\n@DynamoDbBean\npublic class GenericRecord {\nprivate String id;\nprivate String createdDate;\n@DynamoDbPartitionKey\npublic String getId() { return this.id; }\npublic void setId(String id) { this.id = id; }\npublic String getCreatedDate() { return this.createdDate; }\npublic void setCreatedDate(String createdDate) { this.createdDate =\ncreatedDate; }\nMap objects to DynamoDB items 285\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nLombok\n@Data\n@DynamoDbBean\npublic class Customer {\nprivate String name;\n@Getter(onMethod_=@DynamoDbFlatten)\nprivate GenericRecord record;\n}\n@Data\n@DynamoDbBean\npublic class GenericRecord {\n@Getter(onMethod_=@DynamoDbPartitionKey)\nprivate String id;\nprivate String createdDate;\n}\nYou can use the flatten annotation to flatten as many different eligible classes as you need to. The\nfollowing constraints apply:\n\u2022 All attribute names must be unique after they are flattened.\n\u2022 There must never be more than one partition key, sort key, or table name.\nUse static schemas\nWhen you build a static table schema, use the flatten() method of the builder. You also supply\nthe getter and setter methods that identify the contained class.\nStaticTableSchema GENERIC_RECORD_SCHEMA =\nStaticTableSchema.builder(GenericRecord.class)\n.newItemSupplier(GenericRecord::new)\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(GenericRecord::getId)\n.setter(GenericRecord::setId)\n.tags(primaryPartitionKey()))\n.addAttribute(String.class, a -> a.name(\"created_date\")\n.getter(GenericRecord::getCreatedDate)\nMap objects to DynamoDB items 286\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.setter(GenericRecord::setCreatedDate))\n.build();\nStaticTableSchema CUSTOMER_SCHEMA =\nStaticTableSchema.builder(Customer.class)\n.newItemSupplier(Customer::new)\n.addAttribute(String.class, a -> a.name(\"name\")\n.getter(Customer::getName)\n.setter(Customer::setName))\n// Because we are flattening a component object, we supply a\ngetter and setter so the\n// mapper knows how to access it.\n.flatten(GENERIC_RECORD_SCHEMA, Customer::getRecord,\nCustomer::setRecord)\n.build();\nThe previous static schema example uses the following data classes.\nData classes\nStandard data class\npublic class Customer {\nprivate String name;\nprivate GenericRecord record;\npublic String getName() { return this.name; }\npublic void setName(String name) { this.name = name; }\npublic GenericRecord getRecord() { return this.record; }\npublic void setRecord(GenericRecord record) { this.record = record; }\npublic class GenericRecord {\nprivate String id;\nprivate String createdDate;\npublic String getId() { return this.id; }\npublic void setId(String id) { this.id = id; }\npublic String getCreatedDate() { return this.createdDate; }\npublic void setCreatedDate(String createdDate) { this.createdDate =\ncreatedDate; }\n}\nMap objects to DynamoDB items 287\nAWS SDK for Java 2.x Developer Guide for version 2.x\nLombok\n@Data\npublic class Customer {\nprivate String name;\nprivate GenericRecord record;\n}\n@Data\npublic class GenericRecord {\nprivate String id;\nprivate String createdDate;\n}\nYou can use the builder pattern to flatten as many different eligible classes as you need to.\nImplications for other code\nWhen you use the @DynamoDbFlatten attribute (or flatten() builder method), the item in\nDynamoDB contains an attribute for each attribute of the composed object. It also includes the\nattributes of the composing object.\nIn contrast, if you annotate a data class with a composed class and don't use @DynamoDbFlatten,\nthe item is saved with the composed object as a single attribute.\nFor example, compare the Customer class shown in the flattening with composition example with\nand without flattening of the record attribute. You can visualize the difference with JSON as\nshown in the following table.", "mimetype": "text/plain", "start_char_idx": 506682, "end_char_idx": 511072, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "900ecc94-c531-4e54-a93b-e3171190522f": {"__data__": {"id_": "900ecc94-c531-4e54-a93b-e3171190522f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1539c246-2a12-4348-a793-9c0090deaee1", "node_type": "1", "metadata": {}, "hash": "8f42e47c9635bc2e6f92db86e2cd3e92fbecbe5a52e33c9375ca67540e9ada91", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f42a1946-5f68-4c67-84c2-fb408a7ee80d", "node_type": "1", "metadata": {}, "hash": "b1994095255c1e7492e952f6708ea787be557a949ad42ded3e24b505754b00e4", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Implications for other code\nWhen you use the @DynamoDbFlatten attribute (or flatten() builder method), the item in\nDynamoDB contains an attribute for each attribute of the composed object. It also includes the\nattributes of the composing object.\nIn contrast, if you annotate a data class with a composed class and don't use @DynamoDbFlatten,\nthe item is saved with the composed object as a single attribute.\nFor example, compare the Customer class shown in the flattening with composition example with\nand without flattening of the record attribute. You can visualize the difference with JSON as\nshown in the following table.\nWith flattening Without flattening\n3 attributes 2 attributes\n{ {\n\"id\": \"1\", \"id\": \"1\",\n\"createdDate\": \"today\", \"record\": {\n\"name\": \"my name\" \"createdDate\": \"today\",\n} \"name\": \"my name\"\n}\n}\nMap objects to DynamoDB items 288\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe difference becomes important if you have other code accessing the DynamoDB table that\nexpects to find certain attributes.\nWork with attributes that are beans, maps, lists and sets\nA bean definition, such as the Person class shown below, might define properties (or attributes)\nthat refer to types with additional attributes. For instance, in the Person class, mainAddress is\na property that refers to an Address bean that defines additional value attributes. addresses\nrefers to a Java Map, whose elements refer to Address beans. These complex types can be\nthought of a containers of simple attributes that you use for their data value in the context of\nDynamoDB.\nDynamoDB refers to the value properties of nested elements, such as maps, lists, or beans, as\nnested attributes. The Amazon DynamoDB Developer Guide refers to the saved form of a Java\nmap, list or bean as a document type. Simple attributes that you use for their data value in Java are\nreferred to as scalar types in DynamoDB. Sets, which contains multiple scalar elements of the same\ntype, and referred to as set types.\nIt is important to know that the DynamoDB Enhanced Client API converts a property that is bean to\na DynamoDB map document type when it is save.", "mimetype": "text/plain", "start_char_idx": 510447, "end_char_idx": 512581, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f42a1946-5f68-4c67-84c2-fb408a7ee80d": {"__data__": {"id_": "f42a1946-5f68-4c67-84c2-fb408a7ee80d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "900ecc94-c531-4e54-a93b-e3171190522f", "node_type": "1", "metadata": {}, "hash": "a0e8e3af2bdc6c16e3291ab385fc4f9a54ef0860f9982dc6f4de6dc0d25a8590", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e781d225-83de-48ff-9b4b-6ae0aa980f58", "node_type": "1", "metadata": {}, "hash": "a91fd70383b7d993ade6b4d158d3bae670849014008ca2be66c4520b32ea2020", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "addresses\nrefers to a Java Map, whose elements refer to Address beans. These complex types can be\nthought of a containers of simple attributes that you use for their data value in the context of\nDynamoDB.\nDynamoDB refers to the value properties of nested elements, such as maps, lists, or beans, as\nnested attributes. The Amazon DynamoDB Developer Guide refers to the saved form of a Java\nmap, list or bean as a document type. Simple attributes that you use for their data value in Java are\nreferred to as scalar types in DynamoDB. Sets, which contains multiple scalar elements of the same\ntype, and referred to as set types.\nIt is important to know that the DynamoDB Enhanced Client API converts a property that is bean to\na DynamoDB map document type when it is save.\nPerson class\n@DynamoDbBean\npublic class Person {\nprivate Integer id;\nprivate String firstName;\nprivate String lastName;\nprivate Integer age;\nprivate Address mainAddress;\nprivate Map addresses;\nprivate List phoneNumbers;\nprivate Set hobbies;\n@DynamoDbPartitionKey\npublic Integer getId() {\nreturn id;\n}\npublic void setId(Integer id) {\nthis.id = id;\n}\nMap objects to DynamoDB items 289\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String getFirstName() {\nreturn firstName;\n}\npublic void setFirstName(String firstName) {\nthis.firstName = firstName;\n}\npublic String getLastName() {\nreturn lastName;\n}\npublic void setLastName(String lastName) {\nthis.lastName = lastName;\n}\npublic Integer getAge() {\nreturn age;\n}\npublic void setAge(Integer age) {\nthis.age = age;\n}\npublic Address getMainAddress() {\nreturn mainAddress;\n}\npublic void setMainAddress(Address mainAddress) {\nthis.mainAddress = mainAddress;\n}\npublic Map getAddresses() {\nreturn addresses;\n}\npublic void setAddresses(Map addresses) {\nthis.addresses = addresses;\n}\npublic List getPhoneNumbers() {\nreturn phoneNumbers;\n}\nMap objects to DynamoDB items 290\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void setPhoneNumbers(List phoneNumbers) {\nthis.phoneNumbers = phoneNumbers;\n}\npublic Set getHobbies() {\nreturn hobbies;\n}\npublic void setHobbies(Set hobbies) {\nthis.hobbies = hobbies;\n}\n@Override\npublic String toString() {\nreturn \"Person{\" +\n\"addresses=\" + addresses +\n\", id=\" + id +\n\", firstName='\" + firstName + '\\'' +\n\", lastName='\" + lastName + '\\'' +\n\", age=\" + age +\n\", mainAddress=\" + mainAddress +\n\", phoneNumbers=\" + phoneNumbers +\n\", hobbies=\" + hobbies +\n'}';\n}\n}\nAddress class\n@DynamoDbBean\npublic class Address {\nprivate String street;\nprivate String city;\nprivate String state;\nprivate String zipCode;\npublic Address() {\n}\npublic String getStreet() {\nreturn this.street;\n}\nMap objects to DynamoDB items 291\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String getCity() {\nreturn this.city;\n}\npublic String getState() {\nreturn this.state;\n}\npublic String getZipCode() {\nreturn this.zipCode;\n}\npublic void setStreet(String street) {\nthis.street = street;\n}\npublic void setCity(String city) {\nthis.city = city;\n}\npublic void setState(String state) {\nthis.state = state;\n}\npublic void setZipCode(String zipCode) {\nthis.zipCode = zipCode;\n}\n@Override\npublic boolean equals(Object o) {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nAddress address = (Address) o;\nreturn Objects.equals(street, address.street) && Objects.equals(city,\naddress.city) && Objects.equals(state, address.state) && Objects.equals(zipCode,\naddress.zipCode);\n}\n@Override\npublic int hashCode() {\nreturn Objects.hash(street, city, state, zipCode);\n}\nMap objects to DynamoDB items 292\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic String toString() {\nreturn \"Address{\" +\n\"street='\" + street + '\\'' +\n\", city='\" + city + '\\'' +\n\", state='\" + state + '\\'' +\n\", zipCode='\" + zipCode + '\\'' +\n'}';\n}\n}\nPhoneNumber class\n@DynamoDbBean\npublic class PhoneNumber {\nString type;\nString number;\npublic String getType() {\nreturn type;\n}\npublic void setType(String type) {\nthis.type = type;\n}\npublic String getNumber() {\nreturn number;\n}\npublic void setNumber(String number) {\nthis.number = number;\n}\n@Override\npublic String toString() {\nreturn \"PhoneNumber{\" +\n\"type='\" + type + '\\'' +\n\", number='\" + number + '\\'' +\n'}';\n}\n}\nMap objects to DynamoDB items 293\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSave complex types\nUse annotated data classes\nYou save nested attributes for custom classes by simply annotating them.", "mimetype": "text/plain", "start_char_idx": 511812, "end_char_idx": 516356, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e781d225-83de-48ff-9b4b-6ae0aa980f58": {"__data__": {"id_": "e781d225-83de-48ff-9b4b-6ae0aa980f58", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f42a1946-5f68-4c67-84c2-fb408a7ee80d", "node_type": "1", "metadata": {}, "hash": "b1994095255c1e7492e952f6708ea787be557a949ad42ded3e24b505754b00e4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "03b85c8c-0e21-43f6-96d8-fdd60c8821f1", "node_type": "1", "metadata": {}, "hash": "1ee25ba2455aea16945b330e2471f2f3d6484a85b2ed2093820a18343d2b0df9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The Address class and\nPhoneNumber class shown previously are annotated with only the @DynamoDbBean annotation.\nWhen the DynamoDB Enhanced Client API builds the table schema for the Person class with the\nfollowing snippet, the API discovers the use of the Address and PhoneNumber classes and builds\nthe corresponding mappings to work with DynamoDB.\nTableSchema personTableSchema = TableSchema.fromBean(Person.class);\nUse abstract schemas with builders\nThe alternative approach is to use static table schema builders for each nested bean class as shown\nin the following code.\nThe table schemas for the Address and PhoneNumber classes are abstract in the sense that they\ncannot be used with a DynamoDB table. This is because they lack definitions for the primary key.\nThey are used, however, as nested schemas in the table schema for the Person class.\nAfter comment lines 1 and 2 in the definition of PERSON_TABLE_SCHEMA, you\nsee the code that uses the abstract table schemas. The use of documentOf in the\nEnhanceType.documentOf(...) method does not indicate that the method returns an\nEnhancedDocument type of the Enhanced Document API. The documentOf(...) method in this\ncontext returns an object that knows how to map its class argument to and from DynamoDB table\nattributes by using the table schema argument.\nStatic schema code\n// Abstract table schema that cannot be used to work with a DynamoDB table,\n// but can be used as a nested schema.\npublic static final TableSchema
TABLE_SCHEMA_ADDRESS =\nTableSchema.builder(Address.class)\n.newItemSupplier(Address::new)\n.addAttribute(String.class, a -> a.name(\"street\")\n.getter(Address::getStreet)\n.setter(Address::setStreet))\n.addAttribute(String.class, a -> a.name(\"city\")\n.getter(Address::getCity)\n.setter(Address::setCity))\n.addAttribute(String.class, a -> a.name(\"zipcode\")\nMap objects to DynamoDB items 294\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.getter(Address::getZipCode)\n.setter(Address::setZipCode))\n.addAttribute(String.class, a -> a.name(\"state\")\n.getter(Address::getState)\n.setter(Address::setState))\n.build();\n// Abstract table schema that cannot be used to work with a DynamoDB table,\n// but can be used as a nested schema.\npublic static final TableSchema TABLE_SCHEMA_PHONENUMBER =\nTableSchema.builder(PhoneNumber.class)\n.newItemSupplier(PhoneNumber::new)\n.addAttribute(String.class, a -> a.name(\"type\")\n.getter(PhoneNumber::getType)\n.setter(PhoneNumber::setType))\n.addAttribute(String.class, a -> a.name(\"number\")\n.getter(PhoneNumber::getNumber)\n.setter(PhoneNumber::setNumber))\n.build();\n// A static table schema that can be used with a DynamoDB table.\n// The table schema contains two nested schemas that are used to perform mapping\nto/from DynamoDB.\npublic static final TableSchema PERSON_TABLE_SCHEMA =\nTableSchema.builder(Person.class)\n.newItemSupplier(Person::new)\n.addAttribute(Integer.class, a -> a.name(\"id\")\n.getter(Person::getId)\n.setter(Person::setId)\n.addTag(StaticAttributeTags.primaryPartitionKey()))\n.addAttribute(String.class, a -> a.name(\"firstName\")\n.getter(Person::getFirstName)\n.setter(Person::setFirstName))\n.addAttribute(String.class, a -> a.name(\"lastName\")\n.getter(Person::getLastName)\n.setter(Person::setLastName))\n.addAttribute(Integer.class, a -> a.name(\"age\")\n.getter(Person::getAge)\n.setter(Person::setAge))\n.addAttribute(EnhancedType.documentOf(Address.class, TABLE_SCHEMA_ADDRESS),\na -> a.name(\"mainAddress\")\n.getter(Person::getMainAddress)\n.setter(Person::setMainAddress))\n.addAttribute(EnhancedType.listOf(String.class), a -> a.name(\"hobbies\")\nMap objects to DynamoDB items 295\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.getter(Person::getHobbies)\n.setter(Person::setHobbies))\n.addAttribute(EnhancedType.mapOf(\nEnhancedType.of(String.class),\n// 1. Use mapping functionality of the Address table schema.\nEnhancedType.documentOf(Address.class, TABLE_SCHEMA_ADDRESS)), a ->\na.name(\"addresses\")\n.getter(Person::getAddresses)\n.setter(Person::setAddresses))\n.addAttribute(EnhancedType.listOf(\n// 2. Use mapping functionality of the PhoneNumber table schema.\nEnhancedType.documentOf(PhoneNumber.class, TABLE_SCHEMA_PHONENUMBER)),\na -> a.name(\"phoneNumbers\")\n.getter(Person::getPhoneNumbers)\n.setter(Person::setPhoneNumbers))\n.build();\nProject attributes of complex types\nFor query() and scan() methods, you can specify which attributes you want to be returned\nin the results by using method calls such as addNestedAttributeToProject() and\nattributesToProject(). The DynamoDB Enhanced Client API converts the Java method call\nparameters into projection expressions before the request is sent.\nThe following example populates the Person table with two items, then performs three scan\noperations.", "mimetype": "text/plain", "start_char_idx": 516357, "end_char_idx": 521104, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "03b85c8c-0e21-43f6-96d8-fdd60c8821f1": {"__data__": {"id_": "03b85c8c-0e21-43f6-96d8-fdd60c8821f1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e781d225-83de-48ff-9b4b-6ae0aa980f58", "node_type": "1", "metadata": {}, "hash": "a91fd70383b7d993ade6b4d158d3bae670849014008ca2be66c4520b32ea2020", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ecc5cf1d-f62a-4b53-9112-8055efffa577", "node_type": "1", "metadata": {}, "hash": "12b7d4a33e923ce4f7d68d7776ed954594eadee90a7d6aaee899adec4ea66cd5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use mapping functionality of the Address table schema.\nEnhancedType.documentOf(Address.class, TABLE_SCHEMA_ADDRESS)), a ->\na.name(\"addresses\")\n.getter(Person::getAddresses)\n.setter(Person::setAddresses))\n.addAttribute(EnhancedType.listOf(\n// 2. Use mapping functionality of the PhoneNumber table schema.\nEnhancedType.documentOf(PhoneNumber.class, TABLE_SCHEMA_PHONENUMBER)),\na -> a.name(\"phoneNumbers\")\n.getter(Person::getPhoneNumbers)\n.setter(Person::setPhoneNumbers))\n.build();\nProject attributes of complex types\nFor query() and scan() methods, you can specify which attributes you want to be returned\nin the results by using method calls such as addNestedAttributeToProject() and\nattributesToProject(). The DynamoDB Enhanced Client API converts the Java method call\nparameters into projection expressions before the request is sent.\nThe following example populates the Person table with two items, then performs three scan\noperations.\nThe first scan accesses all items in the table in order to compare the results to the other scan\noperations.\nThe second scan uses the addNestedAttributeToProject() builder method to return only the\nstreet attribute value.\nThe third scan operation uses the attributesToProject() builder method to return the data\nfor the first-level attribute, hobbies. The attribute type of hobbies is a list. To access individual\nlist items, perform a get() operation on the list.\npersonDynamoDbTable = getDynamoDbEnhancedClient().table(\"Person\",\nPERSON_TABLE_SCHEMA);\nPersonUtils.createPersonTable(personDynamoDbTable, getDynamoDbClient());\n// Use a utility class to add items to the Person table.\nList personList = PersonUtils.getItemsForCount(2);\nMap objects to DynamoDB items 296\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// This utility method performs a put against DynamoDB to save the instances in\nthe list argument.\nPersonUtils.putCollection(getDynamoDbEnhancedClient(), personList,\npersonDynamoDbTable);\n// The first scan logs all items in the table to compare to the results of the\nsubsequent scans.\nfinal PageIterable allItems = personDynamoDbTable.scan();\nallItems.items().forEach(p ->\n// 1. Log what is in the table.\nlogger.info(p.toString()));\n// Scan for nested attributes.\nPageIterable streetScanResult = personDynamoDbTable.scan(b -> b\n// Use the 'addNestedAttributeToProject()' or\n'addNestedAttributesToProject()' to access data nested in maps in DynamoDB.\n.addNestedAttributeToProject(\nNestedAttributeName.create(\"addresses\", \"work\", \"street\")\n));\nstreetScanResult.items().forEach(p ->\n//2. Log the results of requesting nested attributes.\nlogger.info(p.toString()));\n// Scan for a top-level list attribute.\nPageIterable hobbiesScanResult = personDynamoDbTable.scan(b -> b\n// Use the 'attributesToProject()' method to access first-level\nattributes.\n.attributesToProject(\"hobbies\"));\nhobbiesScanResult.items().forEach((p) -> {\n// 3. Log the results of the request for the 'hobbies' attribute.\nlogger.info(p.toString());\n// To access an item in a list, first get the parent attribute, 'hobbies',\nthen access items in the list.\nString hobby = p.getHobbies().get(1);\n// 4. Log an item in the list.\nlogger.info(hobby);\n});\n// Logged results from comment line 1.\nPerson{id=2, firstName='first name 2', lastName='last name 2', age=11,\naddresses={work=Address{street='street 21', city='city 21', state='state 21',\nMap objects to DynamoDB items 297\nAWS SDK for Java 2.x Developer Guide for version 2.x\nzipCode='33333'}, home=Address{street='street 2', city='city 2', state='state 2',\nzipCode='22222'}}, phoneNumbers=[PhoneNumber{type='home', number='222-222-2222'},\nPhoneNumber{type='work', number='333-333-3333'}], hobbies=[hobby 2, hobby 21]}\nPerson{id=1, firstName='first name 1', lastName='last name 1', age=11,\naddresses={work=Address{street='street 11', city='city 11', state='state 11',\nzipCode='22222'}, home=Address{street='street 1', city='city 1', state='state 1',\nzipCode='11111'}}, phoneNumbers=[PhoneNumber{type='home', number='111-111-1111'},\nPhoneNumber{type='work', number='222-222-2222'}], hobbies=[hobby 1, hobby 11]}\n// Logged results from comment line 2.", "mimetype": "text/plain", "start_char_idx": 520166, "end_char_idx": 524318, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ecc5cf1d-f62a-4b53-9112-8055efffa577": {"__data__": {"id_": "ecc5cf1d-f62a-4b53-9112-8055efffa577", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "03b85c8c-0e21-43f6-96d8-fdd60c8821f1", "node_type": "1", "metadata": {}, "hash": "1ee25ba2455aea16945b330e2471f2f3d6484a85b2ed2093820a18343d2b0df9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8df00194-ce5f-4507-9635-b2add11a49bb", "node_type": "1", "metadata": {}, "hash": "00304a54b5fa239164b039904e998b054eac0430c45d0dc7a5cf9c9dfd11ef87", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Person{id=null, firstName='null', lastName='null', age=null,\naddresses={work=Address{street='street 21', city='null', state='null',\nzipCode='null'}}, phoneNumbers=null, hobbies=null}\nPerson{id=null, firstName='null', lastName='null', age=null,\naddresses={work=Address{street='street 11', city='null', state='null',\nzipCode='null'}}, phoneNumbers=null, hobbies=null}\n// Logged results from comment lines 3 and 4.\nPerson{id=null, firstName='null', lastName='null', age=null, addresses=null,\nphoneNumbers=null, hobbies=[hobby 2, hobby 21]}\nhobby 21\nPerson{id=null, firstName='null', lastName='null', age=null, addresses=null,\nphoneNumbers=null, hobbies=[hobby 1, hobby 11]}\nhobby 11\nNote\nIf the attributesToProject() method follows any other builder method that\nadds attributes that you want to project, the list of attribute names supplied to the\nattributesToProject() replaces all other attribute names.\nA scan performed with the ScanEnhancedRequest instance in the following snippet\nreturns only hobby data.\nScanEnhancedRequest lastOverwrites = ScanEnhancedRequest.builder()\n.addNestedAttributeToProject(\nNestedAttributeName.create(\"addresses\", \"work\", \"street\"))\n.addAttributeToProject(\"firstName\")\n// If the 'attributesToProject()' method follows other builder methods\nthat add attributes for projection,\n// its list of attributes replace all previous attributes.\n.attributesToProject(\"hobbies\")\n.build();\nMap objects to DynamoDB items 298\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPageIterable hobbiesOnlyResult =\npersonDynamoDbTable.scan(lastOverwrites);\nhobbiesOnlyResult.items().forEach(p ->\nlogger.info(p.toString()));\n// Logged results.\nPerson{id=null, firstName='null', lastName='null', age=null, addresses=null,\nphoneNumbers=null, hobbies=[hobby 2, hobby 21]}\nPerson{id=null, firstName='null', lastName='null', age=null, addresses=null,\nphoneNumbers=null, hobbies=[hobby 1, hobby 11]}\nThe following code snippet uses the attributesToProject() method first. This\nordering preserves all other requested attributes.\nScanEnhancedRequest attributesPreserved = ScanEnhancedRequest.builder()\n// Use 'attributesToProject()' first so that the method call does not\nreplace all other attributes\n// that you want to project.\n.attributesToProject(\"firstName\")\n.addNestedAttributeToProject(\nNestedAttributeName.create(\"addresses\", \"work\", \"street\"))\n.addAttributeToProject(\"hobbies\")\n.build();\nPageIterable allAttributesResult =\npersonDynamoDbTable.scan(attributesPreserved);\nallAttributesResult.items().forEach(p ->\nlogger.info(p.toString()));\n// Logged results.\nPerson{id=null, firstName='first name 2', lastName='null', age=null,\naddresses={work=Address{street='street 21', city='null', state='null',\nzipCode='null'}}, phoneNumbers=null, hobbies=[hobby 2, hobby 21]}\nPerson{id=null, firstName='first name 1', lastName='null', age=null,\naddresses={work=Address{street='street 11', city='null', state='null',\nzipCode='null'}}, phoneNumbers=null, hobbies=[hobby 1, hobby 11]}\nUse complex types in expressions\nYou can use complex types in expressions, such as filter expressions and condition expressions, by\nusing dereferencing operators to navigate the structure of the complex type. For objects and maps,\nuse the . (dot) and for list elements use [n] (square brackets around the sequence number\nMap objects to DynamoDB items 299\nAWS SDK for Java 2.x Developer Guide for version 2.x\nof the element). You can't refer to individual elements of a set, but you can use the contains\nfunction.\nThe following example show two filter expressions that are used in scan operations. The filter\nexpressions specify the match conditions for items you want in the results. The example uses\nPerson, Address, and PhoneNumber classes shown previously.\npublic void scanUsingFilterOfNestedAttr() {\n// The following is a filter expression for an attribute that is a map of\nAddress objects.\n// By using this filter expression, the SDK returns Person objects that have an\naddress\n// with 'mailing' as a key and 'MS2' for a state value.\nExpression addressFilter = Expression.builder()\n.expression(\"addresses.#type.#field = :value\")\n.putExpressionName(\"#type\", \"mailing\")\n.putExpressionName(\"#field\", \"state\")\n.putExpressionValue(\":value\",\nAttributeValue.builder().s(\"MS2\").build())\n.build();\nPageIterable addressFilterResults = personDynamoDbTable.scan(rb -> rb.", "mimetype": "text/plain", "start_char_idx": 524319, "end_char_idx": 528690, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8df00194-ce5f-4507-9635-b2add11a49bb": {"__data__": {"id_": "8df00194-ce5f-4507-9635-b2add11a49bb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ecc5cf1d-f62a-4b53-9112-8055efffa577", "node_type": "1", "metadata": {}, "hash": "12b7d4a33e923ce4f7d68d7776ed954594eadee90a7d6aaee899adec4ea66cd5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "952b94d2-13a2-494e-a932-4bcd93424c3e", "node_type": "1", "metadata": {}, "hash": "4e52425895d2d01573ee33f48fc521a9662764c8c098eaad167bc3dee047cfca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following example show two filter expressions that are used in scan operations. The filter\nexpressions specify the match conditions for items you want in the results. The example uses\nPerson, Address, and PhoneNumber classes shown previously.\npublic void scanUsingFilterOfNestedAttr() {\n// The following is a filter expression for an attribute that is a map of\nAddress objects.\n// By using this filter expression, the SDK returns Person objects that have an\naddress\n// with 'mailing' as a key and 'MS2' for a state value.\nExpression addressFilter = Expression.builder()\n.expression(\"addresses.#type.#field = :value\")\n.putExpressionName(\"#type\", \"mailing\")\n.putExpressionName(\"#field\", \"state\")\n.putExpressionValue(\":value\",\nAttributeValue.builder().s(\"MS2\").build())\n.build();\nPageIterable addressFilterResults = personDynamoDbTable.scan(rb -> rb.\nfilterExpression(addressFilter));\naddressFilterResults.items().stream().forEach(p -> logger.info(\"Person: {}\",\np));\nassert addressFilterResults.items().stream().count() == 1;\n// The following is a filter expression for an attribute that is a list of\nphone numbers.\n// By using this filter expression, the SDK returns Person objects whose second\nphone number\n// in the list has a type equal to 'cell'.", "mimetype": "text/plain", "start_char_idx": 527831, "end_char_idx": 529091, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "952b94d2-13a2-494e-a932-4bcd93424c3e": {"__data__": {"id_": "952b94d2-13a2-494e-a932-4bcd93424c3e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8df00194-ce5f-4507-9635-b2add11a49bb", "node_type": "1", "metadata": {}, "hash": "00304a54b5fa239164b039904e998b054eac0430c45d0dc7a5cf9c9dfd11ef87", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "79cc8653-d0cd-41c9-a2c8-fe6ea7b69b7e", "node_type": "1", "metadata": {}, "hash": "d472c47eccc43fd5c54927b4e3d88dd67378ac404b7ca823f6d26c21c3d7a152", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// By using this filter expression, the SDK returns Person objects that have an\naddress\n// with 'mailing' as a key and 'MS2' for a state value.\nExpression addressFilter = Expression.builder()\n.expression(\"addresses.#type.#field = :value\")\n.putExpressionName(\"#type\", \"mailing\")\n.putExpressionName(\"#field\", \"state\")\n.putExpressionValue(\":value\",\nAttributeValue.builder().s(\"MS2\").build())\n.build();\nPageIterable addressFilterResults = personDynamoDbTable.scan(rb -> rb.\nfilterExpression(addressFilter));\naddressFilterResults.items().stream().forEach(p -> logger.info(\"Person: {}\",\np));\nassert addressFilterResults.items().stream().count() == 1;\n// The following is a filter expression for an attribute that is a list of\nphone numbers.\n// By using this filter expression, the SDK returns Person objects whose second\nphone number\n// in the list has a type equal to 'cell'.\nExpression phoneFilter = Expression.builder()\n.expression(\"phoneNumbers[1].#type = :type\")\n.putExpressionName(\"#type\", \"type\")\n.putExpressionValue(\":type\",\nAttributeValue.builder().s(\"cell\").build())\n.build();\nPageIterable phoneFilterResults = personDynamoDbTable.scan(rb -> rb\n.filterExpression(phoneFilter)\nMap objects to DynamoDB items 300\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.attributesToProject(\"id\", \"firstName\", \"lastName\", \"phoneNumbers\")\n);\nphoneFilterResults.items().stream().forEach(p -> logger.info(\"Person: {}\", p));\nassert phoneFilterResults.items().stream().count() == 1;\nassert\nphoneFilterResults.items().stream().findFirst().get().getPhoneNumbers().get(1).getType().equals(\"cell\");\n}\nHelper method that populates the table\npublic static void populateDatabase() {\nPerson person1 = new Person();\nperson1.setId(1);\nperson1.setFirstName(\"FirstName1\");\nperson1.setLastName(\"LastName1\");\nAddress billingAddr1 = new Address();\nbillingAddr1.setState(\"BS1\");\nbillingAddr1.setCity(\"BillingTown1\");\nAddress mailing1 = new Address();\nmailing1.setState(\"MS1\");\nmailing1.setCity(\"MailingTown1\");\nperson1.setAddresses(Map.of(\"billing\", billingAddr1, \"mailing\", mailing1));\nPhoneNumber pn1_1 = new PhoneNumber();\npn1_1.setType(\"work\");\npn1_1.setNumber(\"111-111-1111\");\nPhoneNumber pn1_2 = new PhoneNumber();\npn1_2.setType(\"home\");\npn1_2.setNumber(\"222-222-2222\");\nList phoneNumbers1 = List.of(pn1_1, pn1_2);\nperson1.setPhoneNumbers(phoneNumbers1);\npersonDynamoDbTable.putItem(person1);\nPerson person2 = person1;\nperson2.setId(2);\nMap objects to DynamoDB items 301\nAWS SDK for Java 2.x Developer Guide for version 2.x\nperson2.setFirstName(\"FirstName2\");\nperson2.setLastName(\"LastName2\");\nAddress billingAddress2 = billingAddr1;\nbillingAddress2.setCity(\"BillingTown2\");\nbillingAddress2.setState(\"BS2\");\nAddress mailing2 = mailing1;\nmailing2.setCity(\"MailingTown2\");\nmailing2.setState(\"MS2\");\nperson2.setAddresses(Map.of(\"billing\", billingAddress2, \"mailing\", mailing2));\nPhoneNumber pn2_1 = new PhoneNumber();\npn2_1.setType(\"work\");\npn2_1.setNumber(\"333-333-3333\");\nPhoneNumber pn2_2 = new PhoneNumber();\npn2_2.setType(\"cell\");\npn2_2.setNumber(\"444-444-4444\");\nList phoneNumbers2 = List.of(pn2_1, pn2_2);\nperson2.setPhoneNumbers(phoneNumbers2);\npersonDynamoDbTable.putItem(person2);\n}\nJSON representation of items in the database\n{\n\"id\": 1,\n\"addresses\": {\n\"billing\": {\n\"city\": \"BillingTown1\",\n\"state\": \"BS1\",\n\"street\": null,\n\"zipCode\": null\n},\n\"mailing\": {\n\"city\": \"MailingTown1\",\n\"state\": \"MS1\",\n\"street\": null,\n\"zipCode\": null\nMap objects to DynamoDB items 302\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n},\n\"firstName\": \"FirstName1\",\n\"lastName\": \"LastName1\",\n\"phoneNumbers\": [\n{\n\"number\": \"111-111-1111\",\n\"type\": \"work\"\n},\n{\n\"number\": \"222-222-2222\",\n\"type\": \"home\"\n}\n]\n}\n{\n\"id\": 2,\n\"addresses\": {\n\"billing\": {\n\"city\": \"BillingTown2\",\n\"state\": \"BS2\",\n\"street\": null,\n\"zipCode\": null\n},\n\"mailing\": {\n\"city\": \"MailingTown2\",\n\"state\": \"MS2\",\n\"street\": null,\n\"zipCode\": null\n}\n},\n\"firstName\": \"FirstName2\",\n\"lastName\": \"LastName2\",\n\"phoneNumbers\": [\n{\n\"number\": \"333-333-3333\",\n\"type\": \"work\"\n},\n{\n\"number\": \"444-444-4444\",\n\"type\": \"cell\"\n}\n]\nMap objects to DynamoDB items 303\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nUpdate items that contain complex types\nTo update an item that contains complex types, you have two basic approaches:\n\u2022 Approach 1: First retrieve the item (by using getItem), update the object, then call\nDynamoDbTable#updateItem.", "mimetype": "text/plain", "start_char_idx": 528213, "end_char_idx": 532614, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "79cc8653-d0cd-41c9-a2c8-fe6ea7b69b7e": {"__data__": {"id_": "79cc8653-d0cd-41c9-a2c8-fe6ea7b69b7e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "952b94d2-13a2-494e-a932-4bcd93424c3e", "node_type": "1", "metadata": {}, "hash": "4e52425895d2d01573ee33f48fc521a9662764c8c098eaad167bc3dee047cfca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7f800fec-ac96-400e-8a98-91215f39011b", "node_type": "1", "metadata": {}, "hash": "95dade1fe249d4e76bc477e07117b5d37edf9f782742b6304175b477a69023de", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 Approach 2: Don't retrieve the item, but construct a new instance, set the properties you want to\nupdate, and submit the instance to DynamoDbTable#updateItem by setting the appropriate\nvalue of IgnoreNullsMode . This approach does not require that you fetch the item before\nupdating it.\nThe examples shown in this section use the Person, Address, and PhoneNumber classes shown\npreviously.\nUpdate approach 1: retrieve, then update\nBy using this approach, you ensure that no data is lost on update. The DynamoDB Enhanced Client\nAPI recreates the bean with the attributes from the item saved in DynamoDB including values of\ncomplex types. You then need to use the getters and setters to update the bean. The downside of\nthis approach is the cost you incur retrieving the item first.\nThe following example demonstrates that no data is lost if you first retrieve the item before\nupdating it.\npublic void retrieveThenUpdateExample() {\n// Assume that we ran this code yesterday.\nPerson person = new Person();\nperson.setId(1);\nperson.setFirstName(\"FirstName\");\nperson.setLastName(\"LastName\");\nAddress mainAddress = new Address();\nmainAddress.setStreet(\"123 MyStreet\");\nmainAddress.setCity(\"MyCity\");\nmainAddress.setState(\"MyState\");\nmainAddress.setZipCode(\"MyZipCode\");\nperson.setMainAddress(mainAddress);\nPhoneNumber homePhone = new PhoneNumber();\nMap objects to DynamoDB items 304\nAWS SDK for Java 2.x Developer Guide for version 2.x\nhomePhone.setNumber(\"1111111\");\nhomePhone.setType(\"HOME\");\nperson.setPhoneNumbers(List.of(homePhone));\npersonDynamoDbTable.putItem(person);\n// Assume that we are running this code now.\n// First, retrieve the item\nPerson retrievedPerson =\npersonDynamoDbTable.getItem(Key.builder().partitionValue(1).build());\n// Make any updates.\nretrievedPerson.getMainAddress().setCity(\"YourCity\");\n// Save the updated bean. 'updateItem' returns the bean as it appears after the\nupdate.\nPerson updatedPerson = personDynamoDbTable.updateItem(retrievedPerson);\n// Verify for this example.\nAddress updatedMainAddress = updatedPerson.getMainAddress();\nassert updatedMainAddress.getCity().equals(\"YourCity\");\nassert updatedMainAddress.getState().equals(\"MyState\"); // Unchanged.\n// The list of phone numbers remains; it was not set to null;\nassert updatedPerson.getPhoneNumbers().size() == 1;\n}\nUpdate approach 2: Use an IgnoreNullsMode enum without retrieving the item first\nTo update an item in DynamoDB, you can provide a new object that has only the properties that\nyou want updated and leave the other values as null. With this approach, you need to be aware of\nhow null values in the object are treated by the SDK and how you can control the behavior.\nTo specify which null-valued properties you want the SDK to ignore, provide an\nIgnoreNullsMode enum when you build the UpdateItemEnhancedRequest. As\nan example of using one of the enumerated values, the following snippet uses the\nIgnoreNullsMode.SCALAR_ONLY mode.\n// Create a new Person object to update the existing item in DynamoDB.\nPerson personForUpdate = new Person();\npersonForUpdate.setId(1);\npersonForUpdate.setFirstName(\"updatedFirstName\"); // 'firstName' is a top scalar\nproperty.\nMap objects to DynamoDB items 305\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAddress addressForUpdate = new Address();\naddressForUpdate.setCity(\"updatedCity\");\npersonForUpdate.setMainAddress(addressForUpdate);\npersonDynamoDbTable.updateItem(r -> r\n.item(personForUpdate)\n.ignoreNullsMode(IgnoreNullsMode.SCALAR_ONLY)\n.build());\n/* With IgnoreNullsMode.SCALAR_ONLY provided, The SDK ignores all null properties. The\nSDK adds or replaces\nthe 'firstName' property with the provided value, \"updatedFirstName\". The SDK updates\nthe 'city' value of\n'mainAddress', as long as the 'mainAddress' attribute already exists in DynamoDB.\nIn the background, the SDK generates an update expression that it sends in the request\nto DynamoDB.\nThe following JSON object is a simplified version of what it sends. Notice that the SDK\nincludes the paths\nto 'mainAddress.city' and 'firstName' in the SET clause of the update expression. No\nnull values in\n'personForUpdate' are included.", "mimetype": "text/plain", "start_char_idx": 532615, "end_char_idx": 536745, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7f800fec-ac96-400e-8a98-91215f39011b": {"__data__": {"id_": "7f800fec-ac96-400e-8a98-91215f39011b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "79cc8653-d0cd-41c9-a2c8-fe6ea7b69b7e", "node_type": "1", "metadata": {}, "hash": "d472c47eccc43fd5c54927b4e3d88dd67378ac404b7ca823f6d26c21c3d7a152", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "580275da-3407-4437-bc74-3a33f40047ca", "node_type": "1", "metadata": {}, "hash": "677fe1d95170b6eb17becf63240da765bc4b9d95d1ad8ea3dd70041459e1fc31", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The\nSDK adds or replaces\nthe 'firstName' property with the provided value, \"updatedFirstName\". The SDK updates\nthe 'city' value of\n'mainAddress', as long as the 'mainAddress' attribute already exists in DynamoDB.\nIn the background, the SDK generates an update expression that it sends in the request\nto DynamoDB.\nThe following JSON object is a simplified version of what it sends. Notice that the SDK\nincludes the paths\nto 'mainAddress.city' and 'firstName' in the SET clause of the update expression. No\nnull values in\n'personForUpdate' are included.\n{\n\"TableName\": \"PersonTable\",\n\"Key\": {\n\"id\": {\n\"N\": \"1\"\n}\n},\n\"ReturnValues\": \"ALL_NEW\",\n\"UpdateExpression\": \"SET #mainAddress.#city = :mainAddress_city, #firstName\n= :firstName\",\n\"ExpressionAttributeNames\": {\n\"#city\": \"city\",\n\"#firstName\": \"firstName\",\n\"#mainAddress\": \"mainAddress\"\n},\n\"ExpressionAttributeValues\": {\n\":firstName\": {\n\"S\": \"updatedFirstName\"\n},\n\":mainAddress_city\": {\n\"S\": \"updatedCity\"\nMap objects to DynamoDB items 306\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n}\nHad we chosen 'IgnoreNullsMode.DEFAULT' instead of 'IgnoreNullsMode.SCALAR_ONLY', the\nSDK would have included\nnull values in the \"ExpressionAttributeValues\" section of the request as shown in the\nfollowing snippet.\n\"ExpressionAttributeValues\": {\n\":mainAddress\": {\n\"M\": {\n\"zipCode\": {\n\"NULL\": true\n},\n\"city\": {\n\"S\": \"updatedCity\"\n},\n\"street\": {\n\"NULL\": true\n},\n\"state\": {\n\"NULL\": true\n}\n}\n},\n\":firstName\": {\n\"S\": \"updatedFirstName\"\n}\n}\n*/\nThe Amazon DynamoDB Developer Guide contains more information about update expressions.\nDescriptions of the IgnoreNullsMode options\n\u2022 IgnoreNullsMode.SCALAR_ONLY - Use this setting to update scalar attributes at any\nlevel. The SDK constructs an update statement that sends only non-null, scalar attributes to\nDynamoDB. The SDK ignores null-valued, scalar attributes of a bean or map, retaining the saved\nvalue in DynamoDB.\nWhen you update a scalar attribute of map or bean, the map must already exists in DynamoDB.\nIf you add a map or a bean to the object that does not already exist for the object in DynamoDB,\nMap objects to DynamoDB items 307\nAWS SDK for Java 2.x Developer Guide for version 2.x\nyou get a DynamoDbException with the message The document path provided in the update\nexpression is invalid for update. You must use MAPS_ONLY mode to add a bean or map to\nDynamoDB before you update any of its attributes.\n\u2022 IgnoreNullsMode.MAPS_ONLY - Use this setting to add or replace properties that are a bean\nor a map. The SDK replaces or adds any map or bean provided in the object. Any beans or maps\nthat are null in the object are ignored, retaining the map that exists in DynamoDB.\n\u2022 IgnoreNullsMode.DEFAULT - With this setting, the SDK never ignores null values. Scalar\nattributes at any level that are null are updated to null. The SDK updates any null-valued bean,\nmap, list, or set property in the object to null in DynamoDB. When you use this mode\u2014or don't\nprovide a mode since it's the default mode\u2014you should retrieve the item first so that values in\nDynamoDB are not set to null that are provided in the object for updating, unless your intention\nis to set the values to null.\nIn all modes, if you provide an object to updateItem that has a non-null list or set, the list or set is\nsaved to DynamoDB.\nWhy the modes?\nWhen you provide an object with a bean or map to the updateItem method, the SDK can't tell if it\nshould use the property values in the bean (or entry values in the map) to update the item, or if the\nentire bean/map should replace what's been saved to DynamoDB.\nWorking from our previous example that shows the retrieval of the item first, let's attempt to\nupdate the city attribute of mainAddress without the retrieval.\n/* The retrieval example saved the Person object with a 'mainAddress' property whose\n'city' property value is \"MyCity\".\n/* Note that we create a new Person with only the necessary information to update the\ncity value\nof the mainAddress. */\nPerson personForUpdate = new Person();\npersonForUpdate.setId(1);\n// The update we want to make changes the city.", "mimetype": "text/plain", "start_char_idx": 536194, "end_char_idx": 540283, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "580275da-3407-4437-bc74-3a33f40047ca": {"__data__": {"id_": "580275da-3407-4437-bc74-3a33f40047ca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7f800fec-ac96-400e-8a98-91215f39011b", "node_type": "1", "metadata": {}, "hash": "95dade1fe249d4e76bc477e07117b5d37edf9f782742b6304175b477a69023de", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f59d0f78-fd43-4f37-9205-dc0f9c28bdf8", "node_type": "1", "metadata": {}, "hash": "8cd56db0386b0e0fca9fccd70eb05e3236262faf4a97bc4dc12d950be1931188", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Why the modes?\nWhen you provide an object with a bean or map to the updateItem method, the SDK can't tell if it\nshould use the property values in the bean (or entry values in the map) to update the item, or if the\nentire bean/map should replace what's been saved to DynamoDB.\nWorking from our previous example that shows the retrieval of the item first, let's attempt to\nupdate the city attribute of mainAddress without the retrieval.\n/* The retrieval example saved the Person object with a 'mainAddress' property whose\n'city' property value is \"MyCity\".\n/* Note that we create a new Person with only the necessary information to update the\ncity value\nof the mainAddress. */\nPerson personForUpdate = new Person();\npersonForUpdate.setId(1);\n// The update we want to make changes the city.\nAddress mainAddressForUpdate = new Address();\nmainAddressForUpdate.setCity(\"YourCity\");\npersonForUpdate.setMainAddress(mainAddressForUpdate);\n// Lets' try the following:\nPerson updatedPerson = personDynamoDbTable.updateItem(personForUpdate);\n/*\nMap objects to DynamoDB items 308\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSince we haven't retrieved the item, we don't know if the 'mainAddress' property\nalready exists, so what update expression should the SDK generate?\nA) Should it replace or add the 'mainAddress' with the provided object (setting all\nattributes to null other than city)\nas shown in the following simplified JSON?\n{\n\"TableName\": \"PersonTable\",\n\"Key\": {\n\"id\": {\n\"N\": \"1\"\n}\n},\n\"ReturnValues\": \"ALL_NEW\",\n\"UpdateExpression\": \"SET #mainAddress = :mainAddress\",\n\"ExpressionAttributeNames\": {\n\"#mainAddress\": \"mainAddress\"\n},\n\"ExpressionAttributeValues\": {\n\":mainAddress\": {\n\"M\": {\n\"zipCode\": {\n\"NULL\": true\n},\n\"city\": {\n\"S\": \"YourCity\"\n},\n\"street\": {\n\"NULL\": true\n},\n\"state\": {\n\"NULL\": true\n}\n}\n}\n}\n}\nB) Or should it update only the 'city' attribute of an existing 'mainAddress' as shown\nin the following simplified JSON?\n{\n\"TableName\": \"PersonTable\",\nMap objects to DynamoDB items 309\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"Key\": {\n\"id\": {\n\"N\": \"1\"\n}\n},\n\"ReturnValues\": \"ALL_NEW\",\n\"UpdateExpression\": \"SET #mainAddress.#city = :mainAddress_city\",\n\"ExpressionAttributeNames\": {\n\"#city\": \"city\",\n\"#mainAddress\": \"mainAddress\"\n},\n\"ExpressionAttributeValues\": {\n\":mainAddress_city\": {\n\"S\": \"YourCity\"\n}\n}\n}\nHowever, assume that we don't know if the 'mainAddress' already exists. If it doesn't\nexist, the SDK would try to update\nan attribute of a non-existent map, which results in an exception.\nIn this particular case, we would likely select option B (SCALAR_ONLY) to retain the\nother values of the 'mainAddress'.\n*/\nThe following two examples show uses of the MAPS_ONLY and SCALAR_ONLY enumerated values.\nMAPS_ONLY adds a map and SCALAR_ONLY updates a map.\nIgnoreNullsMode.MAPS_ONLY example\npublic void mapsOnlyModeExample() {\n// Assume that we ran this code yesterday.\nPerson person = new Person();\nperson.setId(1);\nperson.setFirstName(\"FirstName\");\npersonDynamoDbTable.putItem(person);\n// Assume that we are running this code now.\n/* Note that we create a new Person with only the necessary information to\nupdate the city value\nMap objects to DynamoDB items 310\nAWS SDK for Java 2.x Developer Guide for version 2.x\nof the mainAddress. */\nPerson personForUpdate = new Person();\npersonForUpdate.setId(1);\n// The update we want to make changes the city.\nAddress mainAddressForUpdate = new Address();\nmainAddressForUpdate.setCity(\"YourCity\");\npersonForUpdate.setMainAddress(mainAddressForUpdate);\nPerson updatedPerson = personDynamoDbTable.updateItem(r -> r\n.item(personForUpdate)\n.ignoreNullsMode(IgnoreNullsMode.MAPS_ONLY)); // Since the mainAddress\nproperty does not exist, use MAPS_ONLY mode.\nassert updatedPerson.getMainAddress().getCity().equals(\"YourCity\");\nassert updatedPerson.getMainAddress().getState() == null;\n}\nIgnoreNullsMode.SCALAR_ONLY example\npublic void scalarOnlyExample() {\n// Assume that we ran this code yesterday.\nPerson person = new Person();\nperson.setId(1);\nAddress mainAddress = new Address();\nmainAddress.setCity(\"MyCity\");\nmainAddress.setState(\"MyState\");\nperson.setMainAddress(mainAddress);\npersonDynamoDbTable.putItem(person);\n// Assume that we are running this code now.", "mimetype": "text/plain", "start_char_idx": 539496, "end_char_idx": 543723, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f59d0f78-fd43-4f37-9205-dc0f9c28bdf8": {"__data__": {"id_": "f59d0f78-fd43-4f37-9205-dc0f9c28bdf8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "580275da-3407-4437-bc74-3a33f40047ca", "node_type": "1", "metadata": {}, "hash": "677fe1d95170b6eb17becf63240da765bc4b9d95d1ad8ea3dd70041459e1fc31", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8fc6e583-86ab-4496-85c5-01cc949e66ce", "node_type": "1", "metadata": {}, "hash": "a8f3181d72637bbfb52cee72b33b829b708d556b7018a172428af37dbca0e4c2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Address mainAddressForUpdate = new Address();\nmainAddressForUpdate.setCity(\"YourCity\");\npersonForUpdate.setMainAddress(mainAddressForUpdate);\nPerson updatedPerson = personDynamoDbTable.updateItem(r -> r\n.item(personForUpdate)\n.ignoreNullsMode(IgnoreNullsMode.MAPS_ONLY)); // Since the mainAddress\nproperty does not exist, use MAPS_ONLY mode.\nassert updatedPerson.getMainAddress().getCity().equals(\"YourCity\");\nassert updatedPerson.getMainAddress().getState() == null;\n}\nIgnoreNullsMode.SCALAR_ONLY example\npublic void scalarOnlyExample() {\n// Assume that we ran this code yesterday.\nPerson person = new Person();\nperson.setId(1);\nAddress mainAddress = new Address();\nmainAddress.setCity(\"MyCity\");\nmainAddress.setState(\"MyState\");\nperson.setMainAddress(mainAddress);\npersonDynamoDbTable.putItem(person);\n// Assume that we are running this code now.\n/* Note that we create a new Person with only the necessary information to\nupdate the city value\nof the mainAddress. */\nPerson personForUpdate = new Person();\npersonForUpdate.setId(1);\n// The update we want to make changes the city.\nAddress mainAddressForUpdate = new Address();\nmainAddressForUpdate.setCity(\"YourCity\");\npersonForUpdate.setMainAddress(mainAddressForUpdate);\nPerson updatedPerson = personDynamoDbTable.updateItem(r -> r\nMap objects to DynamoDB items 311\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.item(personForUpdate)\n.ignoreNullsMode(IgnoreNullsMode.SCALAR_ONLY)); // SCALAR_ONLY mode\nignores null properties in the in mainAddress.\nassert updatedPerson.getMainAddress().getCity().equals(\"YourCity\");\nassert updatedPerson.getMainAddress().getState().equals(\"MyState\"); // The\nstate property remains the same.\n}\nRefer to the following table to see which null values are ignored for each mode. You can often\nwork with either SCALAR_ONLY and MAPS_ONLY except when you work with beans or maps.\nWhich null-valued properties in the object submitted to updateItem does the SDK ignore for\neach mode?\nType of property in SCALAR_ONLY in MAPS_ONLY in DEFAULT mode\nmode mode\nTop scalar Yes Yes No\nBean or map Yes Yes No\n1 2\nScalar value of a bean Yes No No\nor map entry\nList or set Yes Yes No\n1\nThis assumes the map already exists in DynamoDB. Any scalar value\u2014null or not null\u2014of the\nbean or map that you provide in the object for update requires that a path to the value exists in\nDynamoDB. The SDK constructs a path to the attribute by using the . (dot) dereference operator\nbefore it submits the request.\n2\nSince you use MAPS_ONLY mode to fully replace or to add a bean or map, all null values in the\nbean or map are retained in the map saved to DynamoDB.\nPreserve empty objects with @DynamoDbPreserveEmptyObject\nIf you save a bean to Amazon DynamoDB with empty objects and you want the SDK to\nrecreate the empty objects upon retrieval, annotate the getter of the inner bean with\n@DynamoDbPreserveEmptyObject.\nTo illustrate how the annotation works, the code example uses the following two beans.\nMap objects to DynamoDB items 312\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExample beans\nThe following data class contains two InnerBean fields. The getter method,\ngetInnerBeanWithoutAnno(), is not annotated with @DynamoDbPreserveEmptyObject. The\ngetInnerBeanWithAnno() method is annotated.", "mimetype": "text/plain", "start_char_idx": 542875, "end_char_idx": 546143, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8fc6e583-86ab-4496-85c5-01cc949e66ce": {"__data__": {"id_": "8fc6e583-86ab-4496-85c5-01cc949e66ce", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f59d0f78-fd43-4f37-9205-dc0f9c28bdf8", "node_type": "1", "metadata": {}, "hash": "8cd56db0386b0e0fca9fccd70eb05e3236262faf4a97bc4dc12d950be1931188", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a632bea0-7abb-4497-9f68-af5aad303d83", "node_type": "1", "metadata": {}, "hash": "b0804298b19d9f6eecf10f7c5ba8384d02d614d65fe1efd0a2fbe1a2e3cda991", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "2\nSince you use MAPS_ONLY mode to fully replace or to add a bean or map, all null values in the\nbean or map are retained in the map saved to DynamoDB.\nPreserve empty objects with @DynamoDbPreserveEmptyObject\nIf you save a bean to Amazon DynamoDB with empty objects and you want the SDK to\nrecreate the empty objects upon retrieval, annotate the getter of the inner bean with\n@DynamoDbPreserveEmptyObject.\nTo illustrate how the annotation works, the code example uses the following two beans.\nMap objects to DynamoDB items 312\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExample beans\nThe following data class contains two InnerBean fields. The getter method,\ngetInnerBeanWithoutAnno(), is not annotated with @DynamoDbPreserveEmptyObject. The\ngetInnerBeanWithAnno() method is annotated.\n@DynamoDbBean\npublic class MyBean {\nprivate String id;\nprivate String name;\nprivate InnerBean innerBeanWithoutAnno;\nprivate InnerBean innerBeanWithAnno;\n@DynamoDbPartitionKey\npublic String getId() { return id; }\npublic void setId(String id) { this.id = id; }\npublic String getName() { return name; }\npublic void setName(String name) { this.name = name; }\npublic InnerBean getInnerBeanWithoutAnno() { return innerBeanWithoutAnno; }\npublic void setInnerBeanWithoutAnno(InnerBean innerBeanWithoutAnno)\n{ this.innerBeanWithoutAnno = innerBeanWithoutAnno; }\n@DynamoDbPreserveEmptyObject\npublic InnerBean getInnerBeanWithAnno() { return innerBeanWithAnno; }\npublic void setInnerBeanWithAnno(InnerBean innerBeanWithAnno)\n{ this.innerBeanWithAnno = innerBeanWithAnno; }\n@Override\npublic String toString() {\nreturn new StringJoiner(\", \", MyBean.class.getSimpleName() + \"[\", \"]\")\n.add(\"innerBeanWithoutAnno=\" + innerBeanWithoutAnno)\n.add(\"innerBeanWithAnno=\" + innerBeanWithAnno)\n.add(\"id='\" + id + \"'\")\n.add(\"name='\" + name + \"'\")\n.toString();\n}\n}\nInstances of the following InnerBean class are fields of MyBean and are initialized as empty\nobjects in the example code.\nMap objects to DynamoDB items 313\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@DynamoDbBean\npublic class InnerBean {\nprivate String innerBeanField;\npublic String getInnerBeanField() {\nreturn innerBeanField;\n}\npublic void setInnerBeanField(String innerBeanField) {\nthis.innerBeanField = innerBeanField;\n}\n@Override\npublic String toString() {\nreturn \"InnerBean{\" +\n\"innerBeanField='\" + innerBeanField + '\\'' +\n'}';\n}\n}\nThe following code example saves a MyBean object with initialized inner beans to DynamoDB\nand then retrieves the item. The logged output shows that the innerBeanWithoutAnno is not\ninitialized, but innerBeanWithAnno has been created.\npublic MyBean preserveEmptyObjectAnnoUsingGetItemExample(DynamoDbTable\nmyBeanTable) {\n// Save an item to DynamoDB.\nMyBean bean = new MyBean();\nbean.setId(\"1\");\nbean.setInnerBeanWithoutAnno(new InnerBean()); // Instantiate the inner bean.\nbean.setInnerBeanWithAnno(new InnerBean()); // Instantiate the inner bean.\nmyBeanTable.putItem(bean);\nGetItemEnhancedRequest request = GetItemEnhancedRequest.builder()\n.key(Key.builder().partitionValue(\"1\").build())\n.build();\nMyBean myBean = myBeanTable.getItem(request);\nlogger.info(myBean.toString());\n// Output 'MyBean[innerBeanWithoutAnno=null,\ninnerBeanWithAnno=InnerBean{innerBeanField='null'}, id='1', name='null']'.\nMap objects to DynamoDB items 314\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn myBean;\n}\nAlternative static schema\nYou can use the following StaticTableSchema version of the table schemas in place of the\nannotations on the beans.", "mimetype": "text/plain", "start_char_idx": 545349, "end_char_idx": 548878, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a632bea0-7abb-4497-9f68-af5aad303d83": {"__data__": {"id_": "a632bea0-7abb-4497-9f68-af5aad303d83", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8fc6e583-86ab-4496-85c5-01cc949e66ce", "node_type": "1", "metadata": {}, "hash": "a8f3181d72637bbfb52cee72b33b829b708d556b7018a172428af37dbca0e4c2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4f9cd22d-deeb-45cd-9e7f-af10c1c65c46", "node_type": "1", "metadata": {}, "hash": "112dd943eedf71d9d97dcfa9a68951c163acd6319809556259e5b31820ac6afd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "MyBean bean = new MyBean();\nbean.setId(\"1\");\nbean.setInnerBeanWithoutAnno(new InnerBean()); // Instantiate the inner bean.\nbean.setInnerBeanWithAnno(new InnerBean()); // Instantiate the inner bean.\nmyBeanTable.putItem(bean);\nGetItemEnhancedRequest request = GetItemEnhancedRequest.builder()\n.key(Key.builder().partitionValue(\"1\").build())\n.build();\nMyBean myBean = myBeanTable.getItem(request);\nlogger.info(myBean.toString());\n// Output 'MyBean[innerBeanWithoutAnno=null,\ninnerBeanWithAnno=InnerBean{innerBeanField='null'}, id='1', name='null']'.\nMap objects to DynamoDB items 314\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn myBean;\n}\nAlternative static schema\nYou can use the following StaticTableSchema version of the table schemas in place of the\nannotations on the beans.\npublic static TableSchema buildStaticSchemas() {\nStaticTableSchema innerBeanStaticTableSchema =\nStaticTableSchema.builder(InnerBean.class)\n.newItemSupplier(InnerBean::new)\n.addAttribute(String.class, a -> a.name(\"innerBeanField\")\n.getter(InnerBean::getInnerBeanField)\n.setter(InnerBean::setInnerBeanField))\n.build();\nreturn StaticTableSchema.builder(MyBean.class)\n.newItemSupplier(MyBean::new)\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(MyBean::getId)\n.setter(MyBean::setId)\n.addTag(primaryPartitionKey()))\n.addAttribute(String.class, a -> a.name(\"name\")\n.getter(MyBean::getName)\n.setter(MyBean::setName))\n.addAttribute(EnhancedType.documentOf(InnerBean.class,\ninnerBeanStaticTableSchema),\na -> a.name(\"innerBean1\")\n.getter(MyBean::getInnerBeanWithoutAnno)\n.setter(MyBean::setInnerBeanWithoutAnno))\n.addAttribute(EnhancedType.documentOf(InnerBean.class,\ninnerBeanStaticTableSchema,\nb -> b.preserveEmptyObject(true)),\na -> a.name(\"innerBean2\")\n.getter(MyBean::getInnerBeanWithAnno)\n.setter(MyBean::setInnerBeanWithAnno))\n.build();\n}\nMap objects to DynamoDB items 315\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAvoid saving null attributes of nested objects\nYou can skip null attributes of nested objects when saving a data class object to DynamoDB by\napplying the @DynamoDbIgnoreNulls annotation. By contrast, top-level attributes with null\nvalues are never saved to the database.\nTo illustrate how the annotation works, the code example uses the following two beans.\nExample beans\nThe following data class contains two InnerBean fields. The getter\nmethod, getInnerBeanWithoutAnno(), is not annotated. The\ngetInnerBeanWithIgnoreNullsAnno() method is annotated with @DynamoDbIgnoreNulls.\n@DynamoDbBean\npublic class MyBean {\nprivate String id;\nprivate String name;\nprivate InnerBean innerBeanWithoutAnno;\nprivate InnerBean innerBeanWithIgnoreNullsAnno;\n@DynamoDbPartitionKey\npublic String getId() { return id; }\npublic void setId(String id) { this.id = id; }\npublic String getName() { return name; }\npublic void setName(String name) { this.name = name; }\npublic InnerBean getInnerBeanWithoutAnno() { return innerBeanWithoutAnno; }\npublic void setInnerBeanWithoutAnno(InnerBean innerBeanWithoutAnno)\n{ this.innerBeanWithoutAnno = innerBeanWithoutAnno; }\n@DynamoDbIgnoreNulls\npublic InnerBean getInnerBeanWithIgnoreNullsAnno() { return\ninnerBeanWithIgnoreNullsAnno; }\npublic void setInnerBeanWithIgnoreNullsAnno(InnerBean innerBeanWithAnno)\n{ this.innerBeanWithIgnoreNullsAnno = innerBeanWithAnno; }\n@Override\npublic String toString() {\nreturn new StringJoiner(\", \", MyBean.class.getSimpleName() + \"[\", \"]\")\n.add(\"innerBeanWithoutAnno=\" + innerBeanWithoutAnno)\nMap objects to DynamoDB items 316\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.add(\"innerBeanWithIgnoreNullsAnno=\" + innerBeanWithIgnoreNullsAnno)\n.add(\"id='\" + id + \"'\")\n.add(\"name='\" + name + \"'\")\n.toString();\n}\n}\nInstances of the following InnerBean class are fields of MyBean and are used in the following\nexample code.", "mimetype": "text/plain", "start_char_idx": 548087, "end_char_idx": 551907, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4f9cd22d-deeb-45cd-9e7f-af10c1c65c46": {"__data__": {"id_": "4f9cd22d-deeb-45cd-9e7f-af10c1c65c46", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a632bea0-7abb-4497-9f68-af5aad303d83", "node_type": "1", "metadata": {}, "hash": "b0804298b19d9f6eecf10f7c5ba8384d02d614d65fe1efd0a2fbe1a2e3cda991", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55e81afb-bb97-43fe-9e96-90f7ed1e38c5", "node_type": "1", "metadata": {}, "hash": "479e86705bc210092de874c49e3a6f5992486b6561e63ac1d88d9c923886b012", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "@DynamoDbBean\npublic class InnerBean {\nprivate String innerBeanFieldString;\nprivate Integer innerBeanFieldInteger;\npublic String getInnerBeanFieldString() { return innerBeanFieldString; }\npublic void setInnerBeanFieldString(String innerBeanFieldString)\n{ this.innerBeanFieldString = innerBeanFieldString; }\npublic Integer getInnerBeanFieldInteger() { return innerBeanFieldInteger; }\npublic void setInnerBeanFieldInteger(Integer innerBeanFieldInteger)\n{ this.innerBeanFieldInteger = innerBeanFieldInteger; }\n@Override\npublic String toString() {\nreturn new StringJoiner(\", \", InnerBean.class.getSimpleName() + \"[\", \"]\")\n.add(\"innerBeanFieldString='\" + innerBeanFieldString + \"'\")\n.add(\"innerBeanFieldInteger=\" + innerBeanFieldInteger)\n.toString();\n}\n}\nThe following code example creates an InnerBean object and sets only one of its two attributes\nwith a value.\npublic void ignoreNullsAnnoUsingPutItemExample(DynamoDbTable myBeanTable) {\n// Create an InnerBean object and give only one attribute a value.\nInnerBean innerBeanOneAttributeSet = new InnerBean();\ninnerBeanOneAttributeSet.setInnerBeanFieldInteger(200);\nMap objects to DynamoDB items 317\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create a MyBean instance and use the same InnerBean instance both for\nattributes.\nMyBean bean = new MyBean();\nbean.setId(\"1\");\nbean.setInnerBeanWithoutAnno(innerBeanOneAttributeSet);\nbean.setInnerBeanWithIgnoreNullsAnno(innerBeanOneAttributeSet);\nMap itemMap = myBeanTable.tableSchema().itemToMap(bean,\ntrue);\nlogger.info(itemMap.toString());\n// Log the map that is sent to the database.\n//\n{innerBeanWithIgnoreNullsAnno=AttributeValue(M={innerBeanFieldInteger=AttributeValue(N=200)}),\nid=AttributeValue(S=1),\ninnerBeanWithoutAnno=AttributeValue(M={innerBeanFieldInteger=AttributeValue(N=200),\ninnerBeanFieldString=AttributeValue(NUL=true)})}\n// Save the MyBean object to the table.\nmyBeanTable.putItem(bean);\n}\nTo visualize the low-level data that is sent to DynamoDB, the code logs the attribute map before\nsaving the MyBean object.\nThe logged output shows that the innerBeanWithIgnoreNullsAnno outputs one attribute,\ninnerBeanWithIgnoreNullsAnno=AttributeValue(M={innerBeanFieldInteger=AttributeValue(N=200)})\nThe innerBeanWithoutAnno instance outputs two attributes. One attribute has a value of 200\nand the other is a null-valued attribute.\ninnerBeanWithoutAnno=AttributeValue(M={innerBeanFieldInteger=AttributeValue(N=200),\ninnerBeanFieldString=AttributeValue(NUL=true)})\nJSON representation of the attribute map\nThe following JSON representation makes it easier to see the data that is saved to DynamoDB.\n{\n\"id\": {\n\"S\": \"1\"\n},\nMap objects to DynamoDB items 318\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"innerBeanWithIgnoreNullsAnno\": {\n\"M\": {\n\"innerBeanFieldInteger\": {\n\"N\": \"200\"\n}\n}\n},\n\"innerBeanWithoutAnno\": {\n\"M\": {\n\"innerBeanFieldInteger\": {\n\"N\": \"200\"\n},\n\"innerBeanFieldString\": {\n\"NULL\": true\n}\n}\n}\n}\nAlternative static schema\nYou can use the following StaticTableSchema version of the table schemas in place data class\nannotations.", "mimetype": "text/plain", "start_char_idx": 551908, "end_char_idx": 555001, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "55e81afb-bb97-43fe-9e96-90f7ed1e38c5": {"__data__": {"id_": "55e81afb-bb97-43fe-9e96-90f7ed1e38c5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4f9cd22d-deeb-45cd-9e7f-af10c1c65c46", "node_type": "1", "metadata": {}, "hash": "112dd943eedf71d9d97dcfa9a68951c163acd6319809556259e5b31820ac6afd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c12c45e0-5683-4805-95d6-3459e911eaf6", "node_type": "1", "metadata": {}, "hash": "d2c55cc992b12c2275a6f1be51d80de3867cea9a7895468dc058d7cb785063f5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "One attribute has a value of 200\nand the other is a null-valued attribute.\ninnerBeanWithoutAnno=AttributeValue(M={innerBeanFieldInteger=AttributeValue(N=200),\ninnerBeanFieldString=AttributeValue(NUL=true)})\nJSON representation of the attribute map\nThe following JSON representation makes it easier to see the data that is saved to DynamoDB.\n{\n\"id\": {\n\"S\": \"1\"\n},\nMap objects to DynamoDB items 318\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"innerBeanWithIgnoreNullsAnno\": {\n\"M\": {\n\"innerBeanFieldInteger\": {\n\"N\": \"200\"\n}\n}\n},\n\"innerBeanWithoutAnno\": {\n\"M\": {\n\"innerBeanFieldInteger\": {\n\"N\": \"200\"\n},\n\"innerBeanFieldString\": {\n\"NULL\": true\n}\n}\n}\n}\nAlternative static schema\nYou can use the following StaticTableSchema version of the table schemas in place data class\nannotations.\npublic static TableSchema buildStaticSchemas() {\nStaticTableSchema innerBeanStaticTableSchema =\nStaticTableSchema.builder(InnerBean.class)\n.newItemSupplier(InnerBean::new)\n.addAttribute(String.class, a -> a.name(\"innerBeanFieldString\")\n.getter(InnerBean::getInnerBeanFieldString)\n.setter(InnerBean::setInnerBeanFieldString))\n.addAttribute(Integer.class, a -> a.name(\"innerBeanFieldInteger\")\n.getter(InnerBean::getInnerBeanFieldInteger)\n.setter(InnerBean::setInnerBeanFieldInteger))\n.build();\nreturn StaticTableSchema.builder(MyBean.class)\n.newItemSupplier(MyBean::new)\n.addAttribute(String.class, a -> a.name(\"id\")\n.getter(MyBean::getId)\n.setter(MyBean::setId)\n.addTag(primaryPartitionKey()))\nMap objects to DynamoDB items 319\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.addAttribute(String.class, a -> a.name(\"name\")\n.getter(MyBean::getName)\n.setter(MyBean::setName))\n.addAttribute(EnhancedType.documentOf(InnerBean.class,\ninnerBeanStaticTableSchema),\na -> a.name(\"innerBeanWithoutAnno\")\n.getter(MyBean::getInnerBeanWithoutAnno)\n.setter(MyBean::setInnerBeanWithoutAnno))\n.addAttribute(EnhancedType.documentOf(InnerBean.class,\ninnerBeanStaticTableSchema,\nb -> b.ignoreNulls(true)),\na -> a.name(\"innerBeanWithIgnoreNullsAnno\")\n.getter(MyBean::getInnerBeanWithIgnoreNullsAnno)\n.setter(MyBean::setInnerBeanWithIgnoreNullsAnno))\n.build();\n}\nWork with JSON documents with the Enhanced Document API for DynamoDB\nThe Enhanced Document API for AWS SDK for Java 2.x is designed to work with document-oriented\ndata that has no fixed schema. However, it also lets you use custom classes to map individual\nattributes.\nThe Enhanced Document API is the successor to the Document API of the AWS SDK for Java v1.x.\nContents\n\u2022 Get started using the Enhanced Document API\n\u2022 Create a DocumentTableSchema and a DynamoDbTable\n\u2022 Build enhanced documents\n\u2022 Build from a JSON string\n\u2022 Build from individual elements\n\u2022 Perform CRUD operations\n\u2022 Access enhanced document attributes as custom objects\n\u2022 Use an EnhancedDocument without DynamoDB\nMap objects to DynamoDB items 320\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGet started using the Enhanced Document API\nThe Enhanced Document API requires the same dependencies that are needed for the DynamoDB\nEnhanced Client API. It also requires a DynamoDbEnhancedClient instance as shown at the start\nof this topic.\nBecause the Enhanced Document API was released with version 2.20.3 of the AWS SDK for Java 2.x,\nyou need that version or greater.\nCreate a DocumentTableSchema and a DynamoDbTable\nTo invoke commands against a DynamoDB table using the Enhanced Document API, associate the\ntable with a client-side DynamoDbTable resource object.\nThe enhanced client's table() method creates a DynamoDbTable\ninstance and requires parameters for the DynamoDB table name and a DocumentTableSchema.\nThe builder for a DocumentTableSchema requires a primary index key and one or more attribute\nconverter providers. The AttributeConverterProvider.defaultProvider() method\nprovides converters for default types. It should be specified even if you provide a custom attribute\nconverter provider. You can add an optional secondary index key to the builder.\nThe following code snippet shows the code that generates the client-side representation of a\nDynamoDB person table that stores schemaless EnhancedDocument objects.\nDynamoDbTable documentDynamoDbTable =\nenhancedClient.table(\"person\",\nTableSchema.documentSchemaBuilder()\n// Specify the primary key attributes.", "mimetype": "text/plain", "start_char_idx": 554213, "end_char_idx": 558565, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c12c45e0-5683-4805-95d6-3459e911eaf6": {"__data__": {"id_": "c12c45e0-5683-4805-95d6-3459e911eaf6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "55e81afb-bb97-43fe-9e96-90f7ed1e38c5", "node_type": "1", "metadata": {}, "hash": "479e86705bc210092de874c49e3a6f5992486b6561e63ac1d88d9c923886b012", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e0dd620a-fe30-4fb1-8293-0677b36200a4", "node_type": "1", "metadata": {}, "hash": "703a2fe12c419ebc5af5f04e0596355631908d9ddf45f5bd802815453fe10a17", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The enhanced client's table() method creates a DynamoDbTable\ninstance and requires parameters for the DynamoDB table name and a DocumentTableSchema.\nThe builder for a DocumentTableSchema requires a primary index key and one or more attribute\nconverter providers. The AttributeConverterProvider.defaultProvider() method\nprovides converters for default types. It should be specified even if you provide a custom attribute\nconverter provider. You can add an optional secondary index key to the builder.\nThe following code snippet shows the code that generates the client-side representation of a\nDynamoDB person table that stores schemaless EnhancedDocument objects.\nDynamoDbTable documentDynamoDbTable =\nenhancedClient.table(\"person\",\nTableSchema.documentSchemaBuilder()\n// Specify the primary key attributes.\n.addIndexPartitionKey(TableMetadata.primaryIndexName(),\"id\", AttributeValueType.S)\n.addIndexSortKey(TableMetadata.primaryIndexName(),\n\"lastName\", AttributeValueType.S)\n// Specify attribute converter providers. Minimally add the\ndefault one.\n.attributeConverterProviders(AttributeConverterProvider.defaultProvider())\n.build());\n// Call documentTable.createTable() if \"person\" does not exist in DynamoDB.\n// createTable() should be called only one time.\nMap objects to DynamoDB items 321\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following shows the JSON representation of a person object that is used throughout this\nsection.\nJSON person object\n{\n\"id\": 1,\n\"firstName\": \"Richard\",\n\"lastName\": \"Roe\",\n\"age\": 25,\n\"addresses\":\n{\n\"home\": {\n\"zipCode\": \"00000\",\n\"city\": \"Any Town\",\n\"state\": \"FL\",\n\"street\": \"123 Any Street\"\n},\n\"work\": {\n\"zipCode\": \"00001\",\n\"city\": \"Anywhere\",\n\"state\": \"FL\",\n\"street\": \"100 Main Street\"\n}\n},\n\"hobbies\": [\n\"Hobby 1\",\n\"Hobby 2\"\n],\n\"phoneNumbers\": [\n{\n\"type\": \"Home\",\n\"number\": \"555-0100\"\n},\n{\n\"type\": \"Work\",\n\"number\": \"555-0119\"\n}\n]\n}\nMap objects to DynamoDB items 322\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBuild enhanced documents\nAn EnhancedDocument represents a document-type object that has complex structure with\nnested attributes. An EnhancedDocument requires top-level attributes that match the primary key\nattributes specified for the DocumentTableSchema. The remaining content is arbitrary and can\nconsist of top-level attributes and also deeply nested attributes.\nYou create an EnhancedDocument instance by using a builder that provides several ways to add\nelements.\nBuild from a JSON string\nWith a JSON string, you can build an EnhancedDocument in one method call. The following\nsnippet creates an EnhancedDocument from a JSON string returned by the jsonPerson() helper\nmethod. The jsonPerson() method returns the JSON string version of the person object shown\npreviously.\nEnhancedDocument document =\nEnhancedDocument.builder()\n.json( jsonPerson() )\n.build());\nBuild from individual elements\nAlternatively, you can build an EnhancedDocument instance from individual components using\ntype-safe methods of the builder.\nThe following example builds a person enhanced document similar to the enhanced document\nthat is built from the JSON string in the previous example.\n/* Define the shape of an address map whose JSON representation looks like the\nfollowing.\nUse 'addressMapEnhancedType' in the following EnhancedDocument.builder() to\nsimplify the code.\n\"home\": {\n\"zipCode\": \"00000\",\n\"city\": \"Any Town\",\n\"state\": \"FL\",\n\"street\": \"123 Any Street\"\n}*/\nEnhancedType> addressMapEnhancedType =\nMap objects to DynamoDB items 323\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnhancedType.mapOf(EnhancedType.of(String.class),\nEnhancedType.of(String.class));\n// Use the builder's typesafe methods to add elements to the enhanced\ndocument.\nEnhancedDocument personDocument = EnhancedDocument.builder()\n.putNumber(\"id\", 50)\n.putString(\"firstName\", \"Shirley\")\n.putString(\"lastName\", \"Rodriguez\")\n.putNumber(\"age\", 53)\n.putNull(\"nullAttribute\")\n.putJson(\"phoneNumbers\", phoneNumbersJSONString())\n/* Add the map of addresses whose JSON representation looks like the\nfollowing.", "mimetype": "text/plain", "start_char_idx": 557722, "end_char_idx": 561817, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e0dd620a-fe30-4fb1-8293-0677b36200a4": {"__data__": {"id_": "e0dd620a-fe30-4fb1-8293-0677b36200a4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c12c45e0-5683-4805-95d6-3459e911eaf6", "node_type": "1", "metadata": {}, "hash": "d2c55cc992b12c2275a6f1be51d80de3867cea9a7895468dc058d7cb785063f5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6e376087-7056-4791-aa93-7b9328a0d196", "node_type": "1", "metadata": {}, "hash": "c6a4d31992444999b482c304965081a8c56682a963a71e583a16713d692477d8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"home\": {\n\"zipCode\": \"00000\",\n\"city\": \"Any Town\",\n\"state\": \"FL\",\n\"street\": \"123 Any Street\"\n}*/\nEnhancedType> addressMapEnhancedType =\nMap objects to DynamoDB items 323\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEnhancedType.mapOf(EnhancedType.of(String.class),\nEnhancedType.of(String.class));\n// Use the builder's typesafe methods to add elements to the enhanced\ndocument.\nEnhancedDocument personDocument = EnhancedDocument.builder()\n.putNumber(\"id\", 50)\n.putString(\"firstName\", \"Shirley\")\n.putString(\"lastName\", \"Rodriguez\")\n.putNumber(\"age\", 53)\n.putNull(\"nullAttribute\")\n.putJson(\"phoneNumbers\", phoneNumbersJSONString())\n/* Add the map of addresses whose JSON representation looks like the\nfollowing.\n{\n\"home\": {\n\"zipCode\": \"00000\",\n\"city\": \"Any Town\",\n\"state\": \"FL\",\n\"street\": \"123 Any Street\"\n}\n} */\n.putMap(\"addresses\", getAddresses(), EnhancedType.of(String.class),\naddressMapEnhancedType)\n.putList(\"hobbies\", List.of(\"Theater\", \"Golf\"),\nEnhancedType.of(String.class))\n.build();\nHelper methods\nprivate static String phoneNumbersJSONString() {\nreturn \" [\" +\n\" {\" +\n\" \\\"type\\\": \\\"Home\\\",\" +\n\" \\\"number\\\": \\\"555-0140\\\"\" +\n\" },\" +\n\" {\" +\n\" \\\"type\\\": \\\"Work\\\",\" +\n\" \\\"number\\\": \\\"555-0155\\\"\" +\n\" }\" +\n\" ]\";\n}\nMap objects to DynamoDB items 324\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static Map> getAddresses() {\nreturn Map.of(\n\"home\", Map.of(\n\"zipCode\", \"00002\",\n\"city\", \"Any Town\",\n\"state\", \"ME\",\n\"street\", \"123 Any Street\"));\n}\nPerform CRUD operations\nAfter you define an EnhancedDocument instance, you can save it to a DynamoDB table. The\nfollowing code snippet uses the personDocument that was created from individual elements.\ndocumentDynamoDbTable.putItem(personDocument);\nAfter you read an enhanced document instance from DynamoDB, you can extract the individual\nattribute values using getters as shown in the following code snippet that access the data saved\nfrom the personDocument. Alternatively, you can extract the complete content to a JSON string\nas shown in the last part of the example code.\n// Read the item.\nEnhancedDocument personDocFromDb =\ndocumentDynamoDbTable.getItem(Key.builder().partitionValue(50).build());\n// Access top-level attributes.\nlogger.info(\"Name: {} {}\", personDocFromDb.getString(\"firstName\"),\npersonDocFromDb.getString(\"lastName\"));\n// Name: Shirley Rodriguez\n// Typesafe access of a deeply nested attribute. The addressMapEnhancedType\nshown previously defines the shape of an addresses map.\nMap> addresses =\npersonDocFromDb.getMap(\"addresses\", EnhancedType.of(String.class),\naddressMapEnhancedType);\naddresses.keySet().forEach(k -> logger.info(addresses.get(k).toString()));\n// {zipCode=00002, city=Any Town, street=123 Any Street, state=ME}\n// Alternatively, work with AttributeValue types checking along the way for\ndeeply nested attributes.", "mimetype": "text/plain", "start_char_idx": 561082, "end_char_idx": 563977, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6e376087-7056-4791-aa93-7b9328a0d196": {"__data__": {"id_": "6e376087-7056-4791-aa93-7b9328a0d196", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e0dd620a-fe30-4fb1-8293-0677b36200a4", "node_type": "1", "metadata": {}, "hash": "703a2fe12c419ebc5af5f04e0596355631908d9ddf45f5bd802815453fe10a17", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "235ecd4a-02ed-4214-af6c-98098e939480", "node_type": "1", "metadata": {}, "hash": "46b74c766c319e00e4c02ee753f7576536b4684aeb2cc57588ecbd1dba30bf25", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Read the item.\nEnhancedDocument personDocFromDb =\ndocumentDynamoDbTable.getItem(Key.builder().partitionValue(50).build());\n// Access top-level attributes.\nlogger.info(\"Name: {} {}\", personDocFromDb.getString(\"firstName\"),\npersonDocFromDb.getString(\"lastName\"));\n// Name: Shirley Rodriguez\n// Typesafe access of a deeply nested attribute. The addressMapEnhancedType\nshown previously defines the shape of an addresses map.\nMap> addresses =\npersonDocFromDb.getMap(\"addresses\", EnhancedType.of(String.class),\naddressMapEnhancedType);\naddresses.keySet().forEach(k -> logger.info(addresses.get(k).toString()));\n// {zipCode=00002, city=Any Town, street=123 Any Street, state=ME}\n// Alternatively, work with AttributeValue types checking along the way for\ndeeply nested attributes.\nMap objects to DynamoDB items 325\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMap addressesMap =\npersonDocFromDb.getMapOfUnknownType(\"addresses\");\naddressesMap.keySet().forEach((String k) -> {\nlogger.info(\"Looking at data for [{}] address\", k);\n// Looking at data for [home] address\nAttributeValue value = addressesMap.get(k);\nAttributeValue cityValue = value.m().get(\"city\");\nif (cityValue != null) {\nlogger.info(cityValue.s());\n// Any Town\n}\n});\nList phoneNumbers =\npersonDocFromDb.getListOfUnknownType(\"phoneNumbers\");\nphoneNumbers.forEach((AttributeValue av) -> {\nif (av.hasM()) {\nAttributeValue type = av.m().get(\"type\");\nif (type.s() != null) {\nlogger.info(\"Type of phone: {}\", type.s());\n// Type of phone: Home\n// Type of phone: Work\n}\n}\n});\nString jsonPerson = personDocFromDb.toJson();\nlogger.info(jsonPerson);\n// {\"firstName\":\"Shirley\",\"lastName\":\"Rodriguez\",\"addresses\":\n{\"home\":{\"zipCode\":\"00002\",\"city\":\"Any Town\",\"street\":\"123 Any\nStreet\",\"state\":\"ME\"}},\"hobbies\":[\"Theater\",\"Golf\"],\n// \"id\":50,\"nullAttribute\":null,\"age\":53,\"phoneNumbers\":\n[{\"number\":\"555-0140\",\"type\":\"Home\"},{\"number\":\"555-0155\",\"type\":\"Work\"}]}\nEnhancedDocument instances can be used with any method of DynamoDbTable or\nDynamoDbEnhancedClient in place of mapped data classes.\nAccess enhanced document attributes as custom objects\nIn addition to providing an API to read and write attributes with schemaless structures, the\nEnhanced Document API lets you convert attributes to and from instances of custom classes.\nMap objects to DynamoDB items 326\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe Enhanced Document API uses AttributeConverterProviders and\nAttributeConverters that were shown in the control attribute conversion section as part of the\nDynamoDB Enhanced Client API.\nIn the following example, we use a CustomAttributeConverterProvider with its nested\nAddressConverter class to convert Address objects.\nThis example shows that you can mix data from classes and also data from structures that are\nbuilt as needed. This example also shows that custom classes can be used at any level of a nested\nstructure. The Address objects in this example are values used in a map.\npublic static void attributeToAddressClassMappingExample(DynamoDbEnhancedClient\nenhancedClient, DynamoDbClient standardClient) {\nString tableName = \"customer\";\n// Define the DynamoDbTable for an enhanced document.\n// The schema builder provides methods for attribute converter providers and\nkeys.\nDynamoDbTable documentDynamoDbTable =\nenhancedClient.table(tableName,\nDocumentTableSchema.builder()\n// Add the CustomAttributeConverterProvider along with the\ndefault when you build the table schema.\n.attributeConverterProviders(\nList.of(\nnew CustomAttributeConverterProvider(),\nAttributeConverterProvider.defaultProvider()))\n.addIndexPartitionKey(TableMetadata.primaryIndexName(), \"id\",\nAttributeValueType.N)\n.addIndexSortKey(TableMetadata.primaryIndexName(), \"lastName\",\nAttributeValueType.S)\n.build());\n// Create the DynamoDB table if needed.\ndocumentDynamoDbTable.createTable();\nwaitForTableCreation(tableName, standardClient);\n// The getAddressesForCustomMappingExample() helper method that provides\n'addresses' shows the use of a custom Address class\n// rather than using a Map to hold the address\ndata.\nMap addresses = getAddressesForCustomMappingExample();\nMap objects to DynamoDB items 327\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Build an EnhancedDocument instance to save an item with a mix of structures\ndefined as needed and static classes.", "mimetype": "text/plain", "start_char_idx": 563173, "end_char_idx": 567628, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "235ecd4a-02ed-4214-af6c-98098e939480": {"__data__": {"id_": "235ecd4a-02ed-4214-af6c-98098e939480", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6e376087-7056-4791-aa93-7b9328a0d196", "node_type": "1", "metadata": {}, "hash": "c6a4d31992444999b482c304965081a8c56682a963a71e583a16713d692477d8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "05f0954a-11d4-4d41-ac1d-f37c2a8e27e4", "node_type": "1", "metadata": {}, "hash": "3289a2fb4c3367efdd62c7f52131518d6446ac7a9cf09acb36aae31366fefb3c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".attributeConverterProviders(\nList.of(\nnew CustomAttributeConverterProvider(),\nAttributeConverterProvider.defaultProvider()))\n.addIndexPartitionKey(TableMetadata.primaryIndexName(), \"id\",\nAttributeValueType.N)\n.addIndexSortKey(TableMetadata.primaryIndexName(), \"lastName\",\nAttributeValueType.S)\n.build());\n// Create the DynamoDB table if needed.\ndocumentDynamoDbTable.createTable();\nwaitForTableCreation(tableName, standardClient);\n// The getAddressesForCustomMappingExample() helper method that provides\n'addresses' shows the use of a custom Address class\n// rather than using a Map to hold the address\ndata.\nMap addresses = getAddressesForCustomMappingExample();\nMap objects to DynamoDB items 327\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Build an EnhancedDocument instance to save an item with a mix of structures\ndefined as needed and static classes.\nEnhancedDocument personDocument = EnhancedDocument.builder()\n.putNumber(\"id\", 50)\n.putString(\"firstName\", \"Shirley\")\n.putString(\"lastName\", \"Rodriguez\")\n.putNumber(\"age\", 53)\n.putNull(\"nullAttribute\")\n.putJson(\"phoneNumbers\", phoneNumbersJSONString())\n// Note the use of 'EnhancedType.of(Address.class)' instead of the more\ngeneric\n// 'EnhancedType.mapOf(EnhancedType.of(String.class),\nEnhancedType.of(String.class))' that was used in a previous example.\n.putMap(\"addresses\", addresses, EnhancedType.of(String.class),\nEnhancedType.of(Address.class))\n.putList(\"hobbies\", List.of(\"Hobby 1\", \"Hobby 2\"),\nEnhancedType.of(String.class))\n.build();\n// Save the item to DynamoDB.\ndocumentDynamoDbTable.putItem(personDocument);\n// Retrieve the item just saved.\nEnhancedDocument srPerson =\ndocumentDynamoDbTable.getItem(Key.builder().partitionValue(50).sortValue(\"Rodriguez\").build());\n// Access the addresses attribute.\nMap srAddresses = srPerson.get(\"addresses\",\nEnhancedType.mapOf(EnhancedType.of(String.class),\nEnhancedType.of(Address.class)));\nsrAddresses.keySet().forEach(k -> logger.info(addresses.get(k).toString()));\ndocumentDynamoDbTable.deleteTable();\n// The content logged to the console shows that the saved maps were converted to\nAddress instances.\nAddress{street='123 Main Street', city='Any Town', state='NC', zipCode='00000'}\nAddress{street='100 Any Street', city='Any Town', state='NC', zipCode='00000'}\nCustomAttributeConverterProvider code\npublic class CustomAttributeConverterProvider implements AttributeConverterProvider {\nMap objects to DynamoDB items 328\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate final Map, AttributeConverter> converterCache =\nImmutableMap.of(\n// 1. Add AddressConverter to the internal cache.\nEnhancedType.of(Address.class), new AddressConverter());\npublic static CustomAttributeConverterProvider create() {\nreturn new CustomAttributeConverterProvider();\n}\n// 2. The enhanced client queries the provider for attribute converters if it\n// encounters a type that it does not know how to convert.\n@SuppressWarnings(\"unchecked\")\n@Override\npublic AttributeConverter converterFor(EnhancedType enhancedType) {\nreturn (AttributeConverter) converterCache.get(enhancedType);\n}\n// 3. Custom attribute converter\nprivate class AddressConverter implements AttributeConverter
{\n// 4. Transform an Address object into a DynamoDB map.\n@Override\npublic AttributeValue transformFrom(Address address) {\nMap attributeValueMap = Map.of(\n\"street\", AttributeValue.fromS(address.getStreet()),\n\"city\", AttributeValue.fromS(address.getCity()),\n\"state\", AttributeValue.fromS(address.getState()),\n\"zipCode\", AttributeValue.fromS(address.getZipCode()));\nreturn AttributeValue.fromM(attributeValueMap);\n}\n// 5. Transform the DynamoDB map attribute to an Address oject.", "mimetype": "text/plain", "start_char_idx": 566715, "end_char_idx": 570501, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "05f0954a-11d4-4d41-ac1d-f37c2a8e27e4": {"__data__": {"id_": "05f0954a-11d4-4d41-ac1d-f37c2a8e27e4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "235ecd4a-02ed-4214-af6c-98098e939480", "node_type": "1", "metadata": {}, "hash": "46b74c766c319e00e4c02ee753f7576536b4684aeb2cc57588ecbd1dba30bf25", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b103e39c-d442-4dae-9504-2656e846e9c2", "node_type": "1", "metadata": {}, "hash": "61ad3334d9aa80ed4b3a3b0b66781bfee4287e74b2c28dfac4ca65694e1f3bd9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The enhanced client queries the provider for attribute converters if it\n// encounters a type that it does not know how to convert.\n@SuppressWarnings(\"unchecked\")\n@Override\npublic AttributeConverter converterFor(EnhancedType enhancedType) {\nreturn (AttributeConverter) converterCache.get(enhancedType);\n}\n// 3. Custom attribute converter\nprivate class AddressConverter implements AttributeConverter
{\n// 4. Transform an Address object into a DynamoDB map.\n@Override\npublic AttributeValue transformFrom(Address address) {\nMap attributeValueMap = Map.of(\n\"street\", AttributeValue.fromS(address.getStreet()),\n\"city\", AttributeValue.fromS(address.getCity()),\n\"state\", AttributeValue.fromS(address.getState()),\n\"zipCode\", AttributeValue.fromS(address.getZipCode()));\nreturn AttributeValue.fromM(attributeValueMap);\n}\n// 5. Transform the DynamoDB map attribute to an Address oject.\n@Override\npublic Address transformTo(AttributeValue attributeValue) {\nMap m = attributeValue.m();\nAddress address = new Address();\naddress.setStreet(m.get(\"street\").s());\naddress.setCity(m.get(\"city\").s());\naddress.setState(m.get(\"state\").s());\naddress.setZipCode(m.get(\"zipCode\").s());\nreturn address;\n}\nMap objects to DynamoDB items 329\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic EnhancedType
type() {\nreturn EnhancedType.of(Address.class);\n}\n@Override\npublic AttributeValueType attributeValueType() {\nreturn AttributeValueType.M;\n}\n}\n}\nAddress class\npublic class Address {\nprivate String street;\nprivate String city;\nprivate String state;\nprivate String zipCode;\npublic Address() {\n}\npublic String getStreet() {\nreturn this.street;\n}\npublic String getCity() {\nreturn this.city;\n}\npublic String getState() {\nreturn this.state;\n}\npublic String getZipCode() {\nreturn this.zipCode;\n}\npublic void setStreet(String street) {\nthis.street = street;\n}\nMap objects to DynamoDB items 330\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void setCity(String city) {\nthis.city = city;\n}\npublic void setState(String state) {\nthis.state = state;\n}\npublic void setZipCode(String zipCode) {\nthis.zipCode = zipCode;\n}\n}\nHelper method that provides addresses\nThe following helper method provides the map that use custom Address instances for values\nrather than generic Map instances for values.\nprivate static Map getAddressesForCustomMappingExample() {\nAddress homeAddress = new Address();\nhomeAddress.setStreet(\"100 Any Street\");\nhomeAddress.setCity(\"Any Town\");\nhomeAddress.setState(\"NC\");\nhomeAddress.setZipCode(\"00000\");\nAddress workAddress = new Address();\nworkAddress.setStreet(\"123 Main Street\");\nworkAddress.setCity(\"Any Town\");\nworkAddress.setState(\"NC\");\nworkAddress.setZipCode(\"00000\");\nreturn Map.of(\"home\", homeAddress,\n\"work\", workAddress);\n}\nUse an EnhancedDocument without DynamoDB\nAlthough you usually use an instance of an EnhancedDocument to read and write document-type\nDynamoDB items, it can also be used independently of DynamoDB.\nYou can use EnhancedDocuments for their ability to convert between JSON strings or custom\nobjects to low-level maps of AttributeValues as shown in the following example.\nMap objects to DynamoDB items 331\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void conversionWithoutDynamoDbExample() {\nAddress address = new Address();\naddress.setCity(\"my city\");\naddress.setState(\"my state\");\naddress.setStreet(\"my street\");\naddress.setZipCode(\"00000\");\n// Build an EnhancedDocument instance for its conversion functionality alone.\nEnhancedDocument addressEnhancedDoc = EnhancedDocument.builder()\n// Important: You must specify attribute converter providers when you\nbuild an EnhancedDocument instance not used with a DynamoDB table.\n.attributeConverterProviders(new CustomAttributeConverterProvider(),\nDefaultAttributeConverterProvider.create())\n.put(\"addressDoc\", address, Address.class)\n.build();\n// Convert address to a low-level item representation.\nfinal Map addressAsAttributeMap =\naddressEnhancedDoc.getMapOfUnknownType(\"addressDoc\");\nlogger.info(\"addressAsAttributeMap: {}\", addressAsAttributeMap.toString());\n// Convert address to a JSON string.\nString addressAsJsonString = addressEnhancedDoc.getJson(\"addressDoc\");\nlogger.info(\"addressAsJsonString: {}\", addressAsJsonString);\n// Convert addressEnhancedDoc back to an Address instance.", "mimetype": "text/plain", "start_char_idx": 569581, "end_char_idx": 574025, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b103e39c-d442-4dae-9504-2656e846e9c2": {"__data__": {"id_": "b103e39c-d442-4dae-9504-2656e846e9c2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "05f0954a-11d4-4d41-ac1d-f37c2a8e27e4", "node_type": "1", "metadata": {}, "hash": "3289a2fb4c3367efdd62c7f52131518d6446ac7a9cf09acb36aae31366fefb3c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1293c4ac-54b4-47e0-ad2c-5cab7986f521", "node_type": "1", "metadata": {}, "hash": "d4e6c8cf170b259a2703f80186b477124ac37c6bf3239594ae0091e223bf0cb3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "EnhancedDocument addressEnhancedDoc = EnhancedDocument.builder()\n// Important: You must specify attribute converter providers when you\nbuild an EnhancedDocument instance not used with a DynamoDB table.\n.attributeConverterProviders(new CustomAttributeConverterProvider(),\nDefaultAttributeConverterProvider.create())\n.put(\"addressDoc\", address, Address.class)\n.build();\n// Convert address to a low-level item representation.\nfinal Map addressAsAttributeMap =\naddressEnhancedDoc.getMapOfUnknownType(\"addressDoc\");\nlogger.info(\"addressAsAttributeMap: {}\", addressAsAttributeMap.toString());\n// Convert address to a JSON string.\nString addressAsJsonString = addressEnhancedDoc.getJson(\"addressDoc\");\nlogger.info(\"addressAsJsonString: {}\", addressAsJsonString);\n// Convert addressEnhancedDoc back to an Address instance.\nAddress addressConverted = addressEnhancedDoc.get(\"addressDoc\",\nAddress.class);\nlogger.info(\"addressConverted: {}\", addressConverted.toString());\n}\n/* Console output:\naddressAsAttributeMap: {zipCode=AttributeValue(S=00000),\nstate=AttributeValue(S=my state), street=AttributeValue(S=my street),\ncity=AttributeValue(S=my city)}\naddressAsJsonString: {\"zipCode\":\"00000\",\"state\":\"my state\",\"street\":\"my\nstreet\",\"city\":\"my city\"}\naddressConverted: Address{street='my street', city='my city', state='my\nstate', zipCode='00000'}\n*/\nMap objects to DynamoDB items 332\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nWhen you use an enhanced document independent of a DynamoDB table, make sure you\nexplicitly set attribute converter providers on the builder.\nIn contrast, the document table schema supplies the converter providers when an\nenhanced document is used with a DynamoDB table.\nUse extensions\nThe DynamoDB Enhanced Client API supports plugin extensions that provide functionality beyond\nmapping operations. Extensions have two hook methods, beforeWrite() and afterRead().\nbeforeWrite() modifies a write operation before it happens, and the afterRead() method\nmodifies the results of a read operation after it happens. Because some operations (such as item\nupdates) perform both a write and then a read, both hook methods are called.\nExtensions are loaded in the order that they are specified in the enhanced client builder. The load\norder can be important because one extension can act on values that have been transformed by a\nprevious extension.\nThe enhanced client API comes with a set of plugin extensions that are located in the extensions\npackage. By default, the enhanced client loads the VersionedRecordExtension and the\nAtomicCounterExtension. You can override the default behavior with the enhance client\nbuilder and load any extension. You can also specify none if you don't want the default extensions.\nIf you load your own extensions, the enhanced client doesn't load any default extensions. If you\nwant the behavior provided by either default extension, you need to explicitly add it to the list of\nextensions.\nIn the following example, a custom extension named verifyChecksumExtension is loaded\nafter the VersionedRecordExtension, which is usually loaded by default by itself. The\nAtomicCounterExtension is not loaded in this example.\nDynamoDbEnhancedClientExtension versionedRecordExtension =\nVersionedRecordExtension.builder().build();\nDynamoDbEnhancedClient enhancedClient =\nDynamoDbEnhancedClient.builder()\n.dynamoDbClient(dynamoDbClient)\nMap objects to DynamoDB items 333\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.extensions(versionedRecordExtension,\nverifyChecksumExtension)\n.build();\nVersionedRecordExtension\nThe VersionedRecordExtension is loaded by default and will increment and track an item\nversion number as items are written to the database. A condition will be added to every write\nthat causes the write to fail if the version number of the actual persisted item doesn't match the\nvalue that the application last read. This behavior effectively provides optimistic locking for item\nupdates. If another process updates an item between the time the first process has read the item\nand is writing an update to it, the write will fail.\nTo specify which attribute to use to track the item version number, tag a numeric attribute in the\ntable schema.\nThe following snippet specifies that the version attribute should hold the item version number.\n@DynamoDbVersionAttribute\npublic Integer getVersion() {...};\npublic void setVersion(Integer version) {...};\nThe equivalent static table schema approach is shown in the following snippet.\n.addAttribute(Integer.class, a -> a.name(\"version\")\n.getter(Customer::getVersion)\n.setter(Customer::setVersion)\n// Apply the 'version' tag to the attribute.\n.tags(VersionedRecordExtension.AttributeTags.versionAttribute())\nAtomicCounterExtension\nThe AtomicCounterExtension is loaded by default and increments a tagged numerical attribute\neach time a record is written to the database. Start and increment values can be specified.", "mimetype": "text/plain", "start_char_idx": 573187, "end_char_idx": 578133, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1293c4ac-54b4-47e0-ad2c-5cab7986f521": {"__data__": {"id_": "1293c4ac-54b4-47e0-ad2c-5cab7986f521", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b103e39c-d442-4dae-9504-2656e846e9c2", "node_type": "1", "metadata": {}, "hash": "61ad3334d9aa80ed4b3a3b0b66781bfee4287e74b2c28dfac4ca65694e1f3bd9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3db5805e-b1ec-4ea4-8f2b-ca91cff3d640", "node_type": "1", "metadata": {}, "hash": "da35c60c464ff444d90c5d2904d77d5ce8ed3ae1ceb99668830f2cea038ccfb8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This behavior effectively provides optimistic locking for item\nupdates. If another process updates an item between the time the first process has read the item\nand is writing an update to it, the write will fail.\nTo specify which attribute to use to track the item version number, tag a numeric attribute in the\ntable schema.\nThe following snippet specifies that the version attribute should hold the item version number.\n@DynamoDbVersionAttribute\npublic Integer getVersion() {...};\npublic void setVersion(Integer version) {...};\nThe equivalent static table schema approach is shown in the following snippet.\n.addAttribute(Integer.class, a -> a.name(\"version\")\n.getter(Customer::getVersion)\n.setter(Customer::setVersion)\n// Apply the 'version' tag to the attribute.\n.tags(VersionedRecordExtension.AttributeTags.versionAttribute())\nAtomicCounterExtension\nThe AtomicCounterExtension is loaded by default and increments a tagged numerical attribute\neach time a record is written to the database. Start and increment values can be specified. If no\nvalues are specified, the start value is set to 0 and the attribute's value increments by 1.\nTo specify which attribute is a counter, tag an attribute of type Long in the table schema.\nThe following snippet shows the use of the default start and increment values for the counter\nattribute.\nMap objects to DynamoDB items 334\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@DynamoDbAtomicCounter\npublic Long getCounter() {...};\npublic void setCounter(Long counter) {...};\nThe static table schema approach is shown in the following snippet. The atomic counter extension\nuses a start value of 10 and increments the value by 5 each time the record is written.\n.addAttribute(Integer.class, a -> a.name(\"counter\")\n.getter(Customer::getCounter)\n.setter(Customer::setCounter)\n// Apply the 'atomicCounter' tag to the\nattribute with start and increment values.\n.tags(StaticAttributeTags.atomicCounter(10L,\n5L))\nAutoGeneratedTimestampRecordExtension\nThe AutoGeneratedTimestampRecordExtension automatically updates tagged attributes\nof type Instant with a current timestamp every time the item is successfully written to the\ndatabase.\nThis extension is not loaded by default. Therefore, you need to specify it as a custom extension\nwhen you build the enhanced client as shown in the first example in this topic.\nTo specify which attribute to update with the current timestamp, tag the Instant attribute in the\ntable schema.\nThe lastUpdate attribute is the target of the extensions behavior in the following snippet. Note\nthe requirement that the attribute must be an Instant type.\n@DynamoDbAutoGeneratedTimestampAttribute\npublic Instant getLastUpdate() {...}\npublic void setLastUpdate(Instant lastUpdate) {...}\nThe equivalent static table schema approach is shown in the following snippet.\n.addAttribute(Instant.class, a -> a.name(\"lastUpdate\")\n.getter(Customer::getLastUpdate)\n.setter(Customer::setLastUpdate)\n// Applying the 'autoGeneratedTimestamp' tag to\nthe attribute.\nMap objects to DynamoDB items 335\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.tags(AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute())\nAutoGeneratedUuidExtension\nYou can generate a unique UUID (Universally Unique Identifier) for an attribute when a new\nrecord is written to the database by using the AutoGeneratedUuidExtension. The Java JDK\nUUID.randomUUID() method generates the value and you apply the extension to a attributes of\ntype java.lang.String.\nSince the Java SDK does not load this extension by default, you need to specify it as a custom\nextension when you build the enhanced client as shown in the first example in this topic.\nThe uniqueId attribute is the target of the extension's behavior in the following snippet.\n@AutoGeneratedUuidExtension\npublic String getUniqueId() {...}\npublic void setUniqueId(String uniqueId) {...}\nThe equivalent static table schema approach is shown in the following snippet.\n.addAttribute(String.class, a -> a.name(\"uniqueId\")\n.getter(Customer::getUniqueId)\n.setter(Customer::setUniqueId)\n// Applying the 'autoGeneratedUuid' tag to the\nattribute.\n.tags(AutoGeneratedUuidExtension.AttributeTags.autoGeneratedUuidAttribute())\nIf you want the extension to populate the UUID only for putItem methods and not for\nupdateItem methods, add the update behavior annotation as shown in the following snippet.\n@AutoGeneratedUuidExtension\n@DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)\npublic String getUniqueId() {...}\npublic void setUniqueId(String uniqueId) {...}\nIf you use the static table schema approach, use the following equivalent code.\n.addAttribute(String.class, a -> a.name(\"uniqueId\")\nMap objects to DynamoDB items 336\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.getter(Customer::getUniqueId)\n.setter(Customer::setUniqueId)\n// Applying the 'autoGeneratedUuid' tag to the\nattribute.", "mimetype": "text/plain", "start_char_idx": 577096, "end_char_idx": 582002, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3db5805e-b1ec-4ea4-8f2b-ca91cff3d640": {"__data__": {"id_": "3db5805e-b1ec-4ea4-8f2b-ca91cff3d640", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1293c4ac-54b4-47e0-ad2c-5cab7986f521", "node_type": "1", "metadata": {}, "hash": "d4e6c8cf170b259a2703f80186b477124ac37c6bf3239594ae0091e223bf0cb3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e78ee09e-a34b-479c-9ab8-b6a80a64bc9a", "node_type": "1", "metadata": {}, "hash": "b126ac936eb49cd96bd8496282865343e487a62e5559896f06e5ab8af9dd838c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".tags(AutoGeneratedUuidExtension.AttributeTags.autoGeneratedUuidAttribute())\nIf you want the extension to populate the UUID only for putItem methods and not for\nupdateItem methods, add the update behavior annotation as shown in the following snippet.\n@AutoGeneratedUuidExtension\n@DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)\npublic String getUniqueId() {...}\npublic void setUniqueId(String uniqueId) {...}\nIf you use the static table schema approach, use the following equivalent code.\n.addAttribute(String.class, a -> a.name(\"uniqueId\")\nMap objects to DynamoDB items 336\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.getter(Customer::getUniqueId)\n.setter(Customer::setUniqueId)\n// Applying the 'autoGeneratedUuid' tag to the\nattribute.\n.tags(AutoGeneratedUuidExtension.AttributeTags.autoGeneratedUuidAttribute(),\nStaticAttributeTags.updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS))\nCustom extensions\nThe following custom extension class shows a beforeWrite() method that uses an update\nexpression. After comment line 2, we create a SetAction to set the registrationDate attribute\nif the item in the database doesn't already have a registrationDate attribute. Whenever a\nCustomer object is updated, the extension makes sure that a registrationDate is set.\npublic final class CustomExtension implements DynamoDbEnhancedClientExtension {\n// 1. In a custom extension, use an UpdateExpression to define what action to take\nbefore\n// an item is updated.\n@Override\npublic WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context)\n{\nif ( context.operationContext().tableName().equals(\"Customer\")\n&& context.operationName().equals(OperationName.UPDATE_ITEM)) {\nreturn WriteModification.builder()\n.updateExpression(createUpdateExpression())\n.build();\n}\nreturn WriteModification.builder().build(); // Return an \"empty\"\nWriteModification instance if the extension should not be applied.\n// In this case, if the code is\nnot updating an item on the Customer table.\n}\nprivate static UpdateExpression createUpdateExpression() {\n// 2. Use a SetAction, a subclass of UpdateAction, to provide the values in the\nupdate.\nSetAction setAction =\nSetAction.builder()\n.path(\"registrationDate\")\nMap objects to DynamoDB items 337\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.value(\"if_not_exists(registrationDate, :regValue)\")\n.putExpressionValue(\":regValue\",\nAttributeValue.fromS(Instant.now().toString()))\n.build();\n// 3. Build the UpdateExpression with one or more UpdateAction.\nreturn UpdateExpression.builder()\n.addAction(setAction)\n.build();\n}\n}\nUse the DynamoDB Enhanced Client API asynchronously\nIf your application requires non-blocking, asynchronous calls to DynamoDB, you can use the\nDynamoDbEnhancedAsyncClient. It's similar to the synchronous implementation but with the\nfollowing key differences:\n1. When you build the DynamoDbEnhancedAsyncClient, you must provide the asynchronous\nversion of the standard client, DynamoDbAsyncClient, as shown in the following snippet.\nDynamoDbEnhancedAsyncClient enhancedClient =\nDynamoDbEnhancedAsyncClient.builder()\n.dynamoDbClient(dynamoDbAsyncClient)\n.build();\n2. Methods that return a single data object return a CompletableFuture of the result instead of\nonly the result. Your application can then do other work without having to block on the result.\nThe following snippet shows the asynchronous getItem() method.\nCompletableFuture result = customerDynamoDbTable.getItem(customer);\n// Perform other work here.\nreturn result.join(); // Now block and wait for the result.\n3. Methods that return paginated lists of results return an SdkPublisher instead of an\nSdkIterable that the synchronous DynamoDbEnhanceClient returns for the same methods.\nYour application can then subscribe a handler to that publisher to deal with the results\nasynchronously without having to block.\nPagePublisher results = customerDynamoDbTable.query(r ->\nr.queryConditional(keyEqualTo(k -> k.partitionValue(\"Smith\"))));\nresults.subscribe(myCustomerResultsProcessor);\nMap objects to DynamoDB items 338\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Perform other work and let the processor handle the results asynchronously.\nFor a more complete example of working with the SdkPublisher API, see the example in the\nsection that discusses the asynchronous scan() method of this guide.\nData class annotations\nThe following table lists the annotations that can be used on data classes and provides links to\ninformation and examples in this guide. The table is sorted in ascending alphabetical order by\nannotation name.\nData class annotations used in this guide\nAnnotation name Annotation applies What it does Where it is shown in\n1\nto this guide\n2\nDynamoDbA attribute Increments a tagged Introduction and\ntomicCounter numerical attribute discussion.\neach time a record\nis written to the\ndatabase.\nDynamoDbAttribute attribute Defines or renames \u2022 Initial discussion.", "mimetype": "text/plain", "start_char_idx": 581244, "end_char_idx": 586186, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e78ee09e-a34b-479c-9ab8-b6a80a64bc9a": {"__data__": {"id_": "e78ee09e-a34b-479c-9ab8-b6a80a64bc9a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3db5805e-b1ec-4ea4-8f2b-ca91cff3d640", "node_type": "1", "metadata": {}, "hash": "da35c60c464ff444d90c5d2904d77d5ce8ed3ae1ceb99668830f2cea038ccfb8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "635dd438-2ff7-45e9-9aa8-c4dc78b43f86", "node_type": "1", "metadata": {}, "hash": "ee5b202a231fb30988baa4b4b920075de5ecfd1b963f50ee4b5298d176726eaa", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "For a more complete example of working with the SdkPublisher API, see the example in the\nsection that discusses the asynchronous scan() method of this guide.\nData class annotations\nThe following table lists the annotations that can be used on data classes and provides links to\ninformation and examples in this guide. The table is sorted in ascending alphabetical order by\nannotation name.\nData class annotations used in this guide\nAnnotation name Annotation applies What it does Where it is shown in\n1\nto this guide\n2\nDynamoDbA attribute Increments a tagged Introduction and\ntomicCounter numerical attribute discussion.\neach time a record\nis written to the\ndatabase.\nDynamoDbAttribute attribute Defines or renames \u2022 Initial discussion.\na bean property\n\u2022 Get started section\nthat is mapped to\n\u2014see Note.\na DynamoDB table\n\u2022 In MovieActor class\nattribute.\nIn Query method\nexamples.\nDynamoDbA attribute Updates a tagged Introduction and\nutoGeneratedTimest attribute with a discussion.\nampAttribute current timestamp\nevery time the item\nis successfully written\nto the database\nDynamoDbA attribute Generate a unique Introduction and\nutoGeneratedUuid UUID (Universally discussion.\nMap objects to DynamoDB items 339\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAnnotation name Annotation applies What it does Where it is shown in\n1\nto this guide\nUnique Identifier) for\nan attribute when a\nnew record is written\nto the database.\nDynamoDbBean class Marks a data class as First use on the\nmappable to a table Customer class in the\nschema. Get started section.\nSeveral usages\nappear throughout\nthe guide.\nDynamoDbC attribute Associates a Initial discussion and\nonvertedBy custom Attribute example.\nConverter\nwith the annotated\nattribute.\nDynamoDbFlatten attribute Flattens all the \u2022 Initial discussion.\nattributes of a\n\u2022 Implications for\nseparate DynamoDB\nother code.\ndata class and adds\nthem as top-level\nattributes to the\nrecord that is read\nand written to the\ndatabase.\nDynamoDbIgnore attribute Results in the \u2022 Initial discussion.\nattribute remaining\n\u2022 Use in the\nunmapped.\nProductCatalog\nclass.\nMap objects to DynamoDB items 340\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAnnotation name Annotation applies What it does Where it is shown in\n1\nto this guide\nDynamoDbIgnoreNull attribute Prevents saving null Discussion and\ns attributes of nested examples.\nDynamoDb objects.\nDynamoDbI class Marks an immutable \u2022 Introduction to the\nmmutable data class as annotation.\nmappable to a table\n\u2022 Use in the\nschema.\nProductCatalog\nclass.\n\u2022 Use with Lombok.\nDynamoDbPartitionK attribute Marks an attribute as \u2022 Initial usage on\ney the primary partition the Customer class\nkey (hash key) of the in the Get started\nDynamoDb table. section.\n\u2022 With Lombok.\nDynamoDbP attribute Specifies that if no Discussion and\nreserveEmptyObject data is present for examples.\nthe object mapped\nto the annotated\nattribute, the object\nshould be initialized\nwith all null fields.\nDynamoDbS attribute Marks an attribute \u2022 Use in secondary\necondaryPartitionKey as a partition key for indices and\na global secondary example.\nindex.\n\u2022 In Query method\nexamples.\n\u2022 In Lombok example\n\u2022 With immutable\nclasses.\nMap objects to DynamoDB items 341\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAnnotation name Annotation applies What it does Where it is shown in\n1\nto this guide\nDynamoDbS attribute Marks an attribute as \u2022 Use in secondary\necondarySortKey an optional sort key indices and\nfor a global or local example.\nsecondary index.\n\u2022 In Query method\nexamples.\n\u2022 In Lombok\nexample.\n\u2022 With immutable\nclasses.\nDynamoDbSortKey attribute Marks an attribute as \u2022 Get started section\nthe optional primary on Customer class.\nsort key (range key).\n\u2022 With immutable\nclasses.\n\u2022 In Lombok\nexample.\n\u2022 In Query method\nexamples.\nDynamoDbU attribute Specifies the behavior Introduction and\npdateBehavior when this attribute example.\nis updated as part of\nan 'update' operation\nsuch as UpdateItem.\nDynamoDbVersionAtt attribute Increments an item Introduction and\nribute version number. discussion.\n1\nYou can apply an attribute-level annotations to the getter or setter, but not both. This guide\nshows annotations on getters.\nMap objects to DynamoDB items 342\nAWS SDK for Java 2.x Developer Guide for version 2.x\n2\nThe term property is normally used for a value encapsulated in a JavaBean data class. However,\nthis guide uses the term attribute instead, to be consistent with the terminology used by\nDynamoDB.", "mimetype": "text/plain", "start_char_idx": 585450, "end_char_idx": 589922, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "635dd438-2ff7-45e9-9aa8-c4dc78b43f86": {"__data__": {"id_": "635dd438-2ff7-45e9-9aa8-c4dc78b43f86", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e78ee09e-a34b-479c-9ab8-b6a80a64bc9a", "node_type": "1", "metadata": {}, "hash": "b126ac936eb49cd96bd8496282865343e487a62e5559896f06e5ab8af9dd838c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "791530e6-1751-442a-8d0a-3372b5a1c103", "node_type": "1", "metadata": {}, "hash": "e810764471ab42466b63d16743ee8c62eb5fb66a6b6d84dacaca116fca90283b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "sort key (range key).\n\u2022 With immutable\nclasses.\n\u2022 In Lombok\nexample.\n\u2022 In Query method\nexamples.\nDynamoDbU attribute Specifies the behavior Introduction and\npdateBehavior when this attribute example.\nis updated as part of\nan 'update' operation\nsuch as UpdateItem.\nDynamoDbVersionAtt attribute Increments an item Introduction and\nribute version number. discussion.\n1\nYou can apply an attribute-level annotations to the getter or setter, but not both. This guide\nshows annotations on getters.\nMap objects to DynamoDB items 342\nAWS SDK for Java 2.x Developer Guide for version 2.x\n2\nThe term property is normally used for a value encapsulated in a JavaBean data class. However,\nthis guide uses the term attribute instead, to be consistent with the terminology used by\nDynamoDB.\nWork with Amazon EC2\nThis section provides examples of programming Amazon EC2 that use the AWS SDK for Java 2.x.\nTopics\n\u2022 Manage Amazon EC2 instances\n\u2022 Use AWS Regions and Availability Zones\n\u2022 Work with security groups in Amazon EC2\n\u2022 Work with Amazon EC2 instance metadata\nManage Amazon EC2 instances\nCreate an instance\nCreate a new Amazon EC2 instance by calling the Ec2Client\u2019s runInstances method, providing it\nwith a RunInstancesRequest containing the Amazon Machine Image (AMI) to use and an instance\ntype.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.InstanceType;\nimport software.amazon.awssdk.services.ec2.model.RunInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.RunInstancesResponse;\nimport software.amazon.awssdk.services.ec2.model.Tag;\nimport software.amazon.awssdk.services.ec2.model.CreateTagsRequest;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nCode\npublic static String createEC2Instance(Ec2Client ec2,String name, String amiId ) {\nRunInstancesRequest runRequest = RunInstancesRequest.builder()\nAmazon EC2 343\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.imageId(amiId)\n.instanceType(InstanceType.T1_MICRO)\n.maxCount(1)\n.minCount(1)\n.build();\nRunInstancesResponse response = ec2.runInstances(runRequest);\nString instanceId = response.instances().get(0).instanceId();\nTag tag = Tag.builder()\n.key(\"Name\")\n.value(name)\n.build();\nCreateTagsRequest tagRequest = CreateTagsRequest.builder()\n.resources(instanceId)\n.tags(tag)\n.build();\ntry {\nec2.createTags(tagRequest);\nSystem.out.printf(\n\"Successfully started EC2 Instance %s based on AMI %s\",\ninstanceId, amiId);\nreturn instanceId;\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nStart an instance\nTo start an Amazon EC2 instance, call the Ec2Client\u2019s startInstances method, providing it with\na StartInstancesRequest containing the ID of the instance to start.\nImports\nManage Amazon EC2 instances 344\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.StartInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.StopInstancesRequest;\nCode\npublic static void startInstance(Ec2Client ec2, String instanceId) {\nStartInstancesRequest request = StartInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nec2.startInstances(request);\nSystem.out.printf(\"Successfully started instance %s\", instanceId);\n}\nSee the complete example on GitHub.\nStop an instance\nTo stop an Amazon EC2 instance, call the Ec2Client\u2019s stopInstances method, providing it with a\nStopInstancesRequest containing the ID of the instance to stop.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.StartInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.StopInstancesRequest;\nCode\npublic static void stopInstance(Ec2Client ec2, String instanceId) {\nStopInstancesRequest request = StopInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nec2.stopInstances(request);\nSystem.out.printf(\"Successfully stopped instance %s\", instanceId);\nManage Amazon EC2 instances 345\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nSee the complete example on GitHub.\nReboot an instance\nTo reboot an Amazon EC2 instance, call the Ec2Client\u2019s rebootInstances method, providing it\nwith a RebootInstancesRequest containing the ID of the instance to reboot.", "mimetype": "text/plain", "start_char_idx": 589148, "end_char_idx": 593650, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "791530e6-1751-442a-8d0a-3372b5a1c103": {"__data__": {"id_": "791530e6-1751-442a-8d0a-3372b5a1c103", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "635dd438-2ff7-45e9-9aa8-c4dc78b43f86", "node_type": "1", "metadata": {}, "hash": "ee5b202a231fb30988baa4b4b920075de5ecfd1b963f50ee4b5298d176726eaa", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3ddcd0e8-d9e7-4b4a-8328-9064d699f36f", "node_type": "1", "metadata": {}, "hash": "1bdfeadcdb7179501f210ebee1dff1edd4b979f1d4ade5fe4a7b3a57a73230cf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Imports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.StartInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.StopInstancesRequest;\nCode\npublic static void stopInstance(Ec2Client ec2, String instanceId) {\nStopInstancesRequest request = StopInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nec2.stopInstances(request);\nSystem.out.printf(\"Successfully stopped instance %s\", instanceId);\nManage Amazon EC2 instances 345\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nSee the complete example on GitHub.\nReboot an instance\nTo reboot an Amazon EC2 instance, call the Ec2Client\u2019s rebootInstances method, providing it\nwith a RebootInstancesRequest containing the ID of the instance to reboot.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nimport software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;\nCode\npublic static void rebootEC2Instance(Ec2Client ec2, String instanceId) {\ntry {\nRebootInstancesRequest request = RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nec2.rebootInstances(request);\nSystem.out.printf(\n\"Successfully rebooted instance %s\", instanceId);\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nDescribe instances\nTo list your instances, create a DescribeInstancesRequest and call the Ec2Client\u2019s\ndescribeInstances method. It will return a DescribeInstancesResponse object that you can use\nto list the Amazon EC2 instances for your account and region.\nManage Amazon EC2 instances 346\nAWS SDK for Java 2.x Developer Guide for version 2.x\nInstances are grouped by reservation. Each reservation corresponds to the call to\nstartInstances that launched the instance. To list your instances, you must first call the\nDescribeInstancesResponse class' reservations method, and then call instances on each\nreturned Reservation object.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;\nimport software.amazon.awssdk.services.ec2.model.Instance;\nimport software.amazon.awssdk.services.ec2.model.Reservation;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nCode\npublic static void describeEC2Instances( Ec2Client ec2){\nString nextToken = null;\ntry {\ndo {\nDescribeInstancesRequest request =\nDescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken).build();\nDescribeInstancesResponse response = ec2.describeInstances(request);\nfor (Reservation reservation : response.reservations()) {\nfor (Instance instance : reservation.instances()) {\nSystem.out.println(\"Instance Id is \" + instance.instanceId());\nSystem.out.println(\"Image id is \"+ instance.imageId());\nSystem.out.println(\"Instance type is \"+\ninstance.instanceType());\nSystem.out.println(\"Instance state name is \"+\ninstance.state().name());\nSystem.out.println(\"monitoring information is \"+\ninstance.monitoring().state());\n}\n}\nnextToken = response.nextToken();\n} while (nextToken != null);\nManage Amazon EC2 instances 347\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nResults are paged; you can get further results by passing the value returned from the result object\u2019s\nnextToken method to a new request object\u2019s nextToken method, then using the new request\nobject in your next call to describeInstances.\nSee the complete example on GitHub.\nMonitor an instance\nYou can monitor various aspects of your Amazon EC2 instances, such as CPU and network\nutilization, available memory, and disk space remaining. To learn more about instance monitoring,\nsee Monitoring Amazon EC2 in the Amazon EC2 User Guide for Linux Instances.\nTo start monitoring an instance, you must create a MonitorInstancesRequest with the ID of the\ninstance to monitor, and pass it to the Ec2Client\u2019s monitorInstances method.", "mimetype": "text/plain", "start_char_idx": 592826, "end_char_idx": 597098, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3ddcd0e8-d9e7-4b4a-8328-9064d699f36f": {"__data__": {"id_": "3ddcd0e8-d9e7-4b4a-8328-9064d699f36f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "791530e6-1751-442a-8d0a-3372b5a1c103", "node_type": "1", "metadata": {}, "hash": "e810764471ab42466b63d16743ee8c62eb5fb66a6b6d84dacaca116fca90283b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca524135-8d96-4465-8527-e6b81af4e8f0", "node_type": "1", "metadata": {}, "hash": "4a87be63f26938b1bb90347bf7903fccb1c023379de3751474036dcf2135b7a9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "See the complete example on GitHub.\nMonitor an instance\nYou can monitor various aspects of your Amazon EC2 instances, such as CPU and network\nutilization, available memory, and disk space remaining. To learn more about instance monitoring,\nsee Monitoring Amazon EC2 in the Amazon EC2 User Guide for Linux Instances.\nTo start monitoring an instance, you must create a MonitorInstancesRequest with the ID of the\ninstance to monitor, and pass it to the Ec2Client\u2019s monitorInstances method.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;\nCode\npublic static void monitorInstance( Ec2Client ec2, String instanceId) {\nMonitorInstancesRequest request = MonitorInstancesRequest.builder()\n.instanceIds(instanceId).build();\nec2.monitorInstances(request);\nSystem.out.printf(\n\"Successfully enabled monitoring for instance %s\",\ninstanceId);\n}\nManage Amazon EC2 instances 348\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example on GitHub.\nStop instance monitoring\nTo stop monitoring an instance, create an UnmonitorInstancesRequest with the ID of the instance\nto stop monitoring, and pass it to the Ec2Client\u2019s unmonitorInstances method.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;\nCode\npublic static void unmonitorInstance(Ec2Client ec2, String instanceId) {\nUnmonitorInstancesRequest request = UnmonitorInstancesRequest.builder()\n.instanceIds(instanceId).build();\nec2.unmonitorInstances(request);\nSystem.out.printf(\n\"Successfully disabled monitoring for instance %s\",\ninstanceId);\n}\nSee the complete example on GitHub.\nMore information\n\u2022 RunInstances in the Amazon EC2 API Reference\n\u2022 DescribeInstances in the Amazon EC2 API Reference\n\u2022 StartInstances in the Amazon EC2 API Reference\n\u2022 StopInstances in the Amazon EC2 API Reference\n\u2022 RebootInstances in the Amazon EC2 API Reference\n\u2022 MonitorInstances in the Amazon EC2 API Reference\n\u2022 UnmonitorInstances in the Amazon EC2 API Reference\nManage Amazon EC2 instances 349\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse AWS Regions and Availability Zones\nDescribe Regions\nTo list the Regions available to your account, call the Ec2Client\u2019s describeRegions method. It\nreturns a DescribeRegionsResponse. Call the returned object\u2019s regions method to get a list of\nRegion objects that represent each Region.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;\nimport java.util.concurrent.CompletableFuture;\nCode\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeRegionsAndZones {\npublic static void main(String[] args) {\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future =\ndescribeEC2RegionsAndZonesAsync(ec2AsyncClient);\nfuture.join(); // Wait for both async operations to complete.\n} catch (RuntimeException rte) {\nUse AWS Regions and Availability Zones 350\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(\"An exception occurred: \" + (rte.getCause() != null ?\nrte.getCause().getMessage() : rte.getMessage()));\n}\n}\n/**\n* Asynchronously describes the EC2 regions and availability zones.", "mimetype": "text/plain", "start_char_idx": 596612, "end_char_idx": 600859, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ca524135-8d96-4465-8527-e6b81af4e8f0": {"__data__": {"id_": "ca524135-8d96-4465-8527-e6b81af4e8f0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3ddcd0e8-d9e7-4b4a-8328-9064d699f36f", "node_type": "1", "metadata": {}, "hash": "1bdfeadcdb7179501f210ebee1dff1edd4b979f1d4ade5fe4a7b3a57a73230cf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6241f454-9e57-4942-998e-11400e850a6b", "node_type": "1", "metadata": {}, "hash": "a62382f7ada47f88e58c408aca75de52acd377d700f9b980180c3f8a71ff0766", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeRegionsAndZones {\npublic static void main(String[] args) {\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future =\ndescribeEC2RegionsAndZonesAsync(ec2AsyncClient);\nfuture.join(); // Wait for both async operations to complete.\n} catch (RuntimeException rte) {\nUse AWS Regions and Availability Zones 350\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(\"An exception occurred: \" + (rte.getCause() != null ?\nrte.getCause().getMessage() : rte.getMessage()));\n}\n}\n/**\n* Asynchronously describes the EC2 regions and availability zones.\n*\n* @param ec2AsyncClient the EC2 async client used to make the API calls\n* @return a {@link CompletableFuture} that completes when both the region and\navailability zone descriptions are complete\n*/\npublic static CompletableFuture\ndescribeEC2RegionsAndZonesAsync(Ec2AsyncClient ec2AsyncClient) {\n// Initiate the asynchronous request to describe regions\nCompletableFuture regionsResponse =\nec2AsyncClient.describeRegions();\n// Handle the response or exception for regions\nCompletableFuture regionsFuture =\nregionsResponse.whenComplete((regionsResp, ex) -> {\nif (ex != null) {\n// Handle the exception by throwing a RuntimeException\nthrow new RuntimeException(\"Failed to describe EC2 regions.\", ex);\n} else if (regionsResp == null || regionsResp.regions().isEmpty()) {\n// Throw an exception if the response is null or the result is empty\nthrow new RuntimeException(\"No EC2 regions found.\");\n} else {\n// Process the response if no exception occurred and the result is not\nempty\nregionsResp.regions().forEach(region -> {\nSystem.out.printf(\n\"Found Region %s with endpoint %s%n\",\nregion.regionName(),\nregion.endpoint());\n});\n}\n});\nCompletableFuture zonesResponse =\nec2AsyncClient.describeAvailabilityZones();\nCompletableFuture zonesFuture =\nzonesResponse.whenComplete((zonesResp, ex) -> {\nif (ex != null) {\nUse AWS Regions and Availability Zones 351\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow new RuntimeException(\"Failed to describe EC2 availability\nzones.\", ex);\n} else if (zonesResp == null || zonesResp.availabilityZones().isEmpty()) {\nthrow new RuntimeException(\"No EC2 availability zones found.\");\n} else {\nzonesResp.availabilityZones().forEach(zone -> {\nSystem.out.printf(\n\"Found Availability Zone %s with status %s in region %s%n\",\nzone.zoneName(),\nzone.state(),\nzone.regionName()\n);\n});\n}\n});\nreturn CompletableFuture.allOf(regionsFuture, zonesFuture);\n}\n}\nSee the complete example on GitHub.\nDescribe availability zones\nTo list each Availability Zone available to your account, call the Ec2Client\u2019s\ndescribeAvailabilityZones method. It returns a DescribeAvailabilityZonesResponse. Call\nits availabilityZones method to get a list of AvailabilityZone objects that represent each\nAvailability Zone.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;\nimport java.util.concurrent.CompletableFuture;\nCode\nCreate the Ec2Client.\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\nUse AWS Regions and Availability Zones 352\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nThen call describeAvailabilityZones() and retrieve results.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeRegionsAndZones {\npublic static void main(String[] args) {\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future =\ndescribeEC2RegionsAndZonesAsync(ec2AsyncClient);\nfuture.join(); // Wait for both async operations to complete.\n}", "mimetype": "text/plain", "start_char_idx": 600057, "end_char_idx": 604697, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6241f454-9e57-4942-998e-11400e850a6b": {"__data__": {"id_": "6241f454-9e57-4942-998e-11400e850a6b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca524135-8d96-4465-8527-e6b81af4e8f0", "node_type": "1", "metadata": {}, "hash": "4a87be63f26938b1bb90347bf7903fccb1c023379de3751474036dcf2135b7a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cf2f91bd-5ca0-4219-84c7-8bad3fa17f36", "node_type": "1", "metadata": {}, "hash": "88f3c32e78314edc5fda1b0e7833461835434889bac41bc08c0672627fd7362b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeRegionsAndZones {\npublic static void main(String[] args) {\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future =\ndescribeEC2RegionsAndZonesAsync(ec2AsyncClient);\nfuture.join(); // Wait for both async operations to complete.\n} catch (RuntimeException rte) {\nSystem.err.println(\"An exception occurred: \" + (rte.getCause() != null ?\nrte.getCause().getMessage() : rte.getMessage()));\n}\n}\n/**\n* Asynchronously describes the EC2 regions and availability zones.\n*\n* @param ec2AsyncClient the EC2 async client used to make the API calls\n* @return a {@link CompletableFuture} that completes when both the region and\navailability zone descriptions are complete\n*/\npublic static CompletableFuture\ndescribeEC2RegionsAndZonesAsync(Ec2AsyncClient ec2AsyncClient) {\nUse AWS Regions and Availability Zones 353\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Initiate the asynchronous request to describe regions\nCompletableFuture regionsResponse =\nec2AsyncClient.describeRegions();\n// Handle the response or exception for regions\nCompletableFuture regionsFuture =\nregionsResponse.whenComplete((regionsResp, ex) -> {\nif (ex != null) {\n// Handle the exception by throwing a RuntimeException\nthrow new RuntimeException(\"Failed to describe EC2 regions.\", ex);\n} else if (regionsResp == null || regionsResp.regions().isEmpty()) {\n// Throw an exception if the response is null or the result is empty\nthrow new RuntimeException(\"No EC2 regions found.\");\n} else {\n// Process the response if no exception occurred and the result is not\nempty\nregionsResp.regions().forEach(region -> {\nSystem.out.printf(\n\"Found Region %s with endpoint %s%n\",\nregion.regionName(),\nregion.endpoint());\n});\n}\n});\nCompletableFuture zonesResponse =\nec2AsyncClient.describeAvailabilityZones();\nCompletableFuture zonesFuture =\nzonesResponse.whenComplete((zonesResp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to describe EC2 availability\nzones.\", ex);\n} else if (zonesResp == null || zonesResp.availabilityZones().isEmpty()) {\nthrow new RuntimeException(\"No EC2 availability zones found.\");\n} else {\nzonesResp.availabilityZones().forEach(zone -> {\nSystem.out.printf(\n\"Found Availability Zone %s with status %s in region %s%n\",\nzone.zoneName(),\nzone.state(),\nzone.regionName()\n);\n});\n}\nUse AWS Regions and Availability Zones 354\nAWS SDK for Java 2.x Developer Guide for version 2.x\n});\nreturn CompletableFuture.allOf(regionsFuture, zonesFuture);\n}\n}\nSee the complete example on GitHub.\nDescribe accounts\nTo list EC2-related information about your account, call the Ec2Client\u2019s\ndescribeAccountAttributes method. This method returns a\nDescribeAccountAttributesResponse object. Invoke this objects accountAttributes method\nto get a list of AccountAttribute objects. You can iterate through the list to retrieve an\nAccountAttribute object.\nYou can get your account\u2019s attribute values by invoking the AccountAttribute object\u2019s\nattributeValues method. This method returns a list of AccountAttributeValue objects. You can\niterate through this second list to display the value of attributes (see the following code example).\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeAccountAttributesResponse;\nimport java.util.concurrent.CompletableFuture;\nCode\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeAccountAttributesResponse;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 603795, "end_char_idx": 608290, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cf2f91bd-5ca0-4219-84c7-8bad3fa17f36": {"__data__": {"id_": "cf2f91bd-5ca0-4219-84c7-8bad3fa17f36", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6241f454-9e57-4942-998e-11400e850a6b", "node_type": "1", "metadata": {}, "hash": "a62382f7ada47f88e58c408aca75de52acd377d700f9b980180c3f8a71ff0766", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a1014947-6138-45b0-895f-7a8bad2d5c92", "node_type": "1", "metadata": {}, "hash": "24b5747f3ff2d9949bf479b2ab4c1496115b15c31ca3251ad51c207adbcf7948", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "You can iterate through the list to retrieve an\nAccountAttribute object.\nYou can get your account\u2019s attribute values by invoking the AccountAttribute object\u2019s\nattributeValues method. This method returns a list of AccountAttributeValue objects. You can\niterate through this second list to display the value of attributes (see the following code example).\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeAccountAttributesResponse;\nimport java.util.concurrent.CompletableFuture;\nCode\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeAccountAttributesResponse;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\nUse AWS Regions and Availability Zones 355\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class DescribeAccount {\npublic static void main(String[] args) {\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future =\ndescribeEC2AccountAsync(ec2AsyncClient);\nfuture.join();\nSystem.out.println(\"EC2 Account attributes described successfully.\");\n} catch (RuntimeException rte) {\nSystem.err.println(\"An exception occurred: \" + (rte.getCause() != null ?\nrte.getCause().getMessage() : rte.getMessage()));\n}\n}\n/**\n* Describes the EC2 account attributes asynchronously.\n*\n* @param ec2AsyncClient the EC2 asynchronous client to use for the operation\n* @return a {@link CompletableFuture} containing the {@link\nDescribeAccountAttributesResponse} with the account attributes\n*/\npublic static CompletableFuture\ndescribeEC2AccountAsync(Ec2AsyncClient ec2AsyncClient) {\nCompletableFuture response =\nec2AsyncClient.describeAccountAttributes();\nreturn response.whenComplete((accountResults, ex) -> {\nif (ex != null) {\n// Handle the exception by throwing a RuntimeException.\nthrow new RuntimeException(\"Failed to describe EC2 account\nattributes.\", ex);\n} else if (accountResults == null ||\naccountResults.accountAttributes().isEmpty()) {\n// Throw an exception if the response is null or no account attributes\nare found.\nthrow new RuntimeException(\"No account attributes found.\");\n} else {\n// Process the response if no exception occurred.\naccountResults.accountAttributes().forEach(attribute -> {\nSystem.out.println(\"\\nThe name of the attribute is \" +\nattribute.attributeName());\nattribute.attributeValues().forEach(\nUse AWS Regions and Availability Zones 356\nAWS SDK for Java 2.x Developer Guide for version 2.x\nmyValue -> System.out.println(\"The value of the attribute is \"\n+ myValue.attributeValue()));\n});\n}\n});\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Regions and Availability Zones in the Amazon EC2 User Guide for Linux Instances\n\u2022 DescribeRegions in the Amazon EC2 API Reference\n\u2022 DescribeAvailabilityZones in the Amazon EC2 API Reference\nWork with security groups in Amazon EC2\nCreate a security group\nTo create a security group, call the Ec2Client\u2019s createSecurityGroup method with a\nCreateSecurityGroupRequest that contains the key\u2019s name.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;\nimport software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;\nimport software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressResponse;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nimport software.amazon.awssdk.services.ec2.model.IpPermission;\nimport software.amazon.awssdk.services.ec2.model.CreateSecurityGroupResponse;\nimport software.amazon.awssdk.services.ec2.model.IpRange;\nCode\nCreateSecurityGroupRequest createRequest =\nCreateSecurityGroupRequest.builder()\n.groupName(groupName)\n.description(groupDesc)\nWork with security groups in Amazon EC2 357\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.vpcId(vpcId)\n.build();\nCreateSecurityGroupResponse resp= ec2.createSecurityGroup(createRequest);\nSee the complete example on GitHub.\nConfigure a security group\nA security group can control both inbound (ingress) and outbound (egress) traffic to your Amazon\nEC2 instances.", "mimetype": "text/plain", "start_char_idx": 607337, "end_char_idx": 612000, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a1014947-6138-45b0-895f-7a8bad2d5c92": {"__data__": {"id_": "a1014947-6138-45b0-895f-7a8bad2d5c92", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cf2f91bd-5ca0-4219-84c7-8bad3fa17f36", "node_type": "1", "metadata": {}, "hash": "88f3c32e78314edc5fda1b0e7833461835434889bac41bc08c0672627fd7362b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "597cd494-1612-4bcf-9bd9-1504a7c76bd4", "node_type": "1", "metadata": {}, "hash": "ea8ba362d1be65166c493d060d30552b3a34276fa9d4e88f4ba9616f867ea313", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Configure a security group\nA security group can control both inbound (ingress) and outbound (egress) traffic to your Amazon\nEC2 instances.\nTo add ingress rules to your security group, use the Ec2Client\u2019s\nauthorizeSecurityGroupIngress method, providing the name of the security\ngroup and the access rules (IpPermission) you want to assign to it within an\nAuthorizeSecurityGroupIngressRequest object. The following example shows how to add IP\npermissions to a security group.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;\nimport software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;\nimport software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressResponse;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nimport software.amazon.awssdk.services.ec2.model.IpPermission;\nimport software.amazon.awssdk.services.ec2.model.CreateSecurityGroupResponse;\nimport software.amazon.awssdk.services.ec2.model.IpRange;\nCode\nFirst, create an Ec2Client\nRegion region = Region.US_WEST_2;\nEc2Client ec2 = Ec2Client.builder()\n.region(region)\n.build();\nThen use the Ec2Client\u2019s authorizeSecurityGroupIngress method,\nIpRange ipRange = IpRange.builder()\nWork with security groups in Amazon EC2 358\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.cidrIp(\"0.0.0.0/0\").build();\nIpPermission ipPerm = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(80)\n.fromPort(80)\n.ipRanges(ipRange)\n.build();\nIpPermission ipPerm2 = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(22)\n.fromPort(22)\n.ipRanges(ipRange)\n.build();\nAuthorizeSecurityGroupIngressRequest authRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(groupName)\n.ipPermissions(ipPerm, ipPerm2)\n.build();\nAuthorizeSecurityGroupIngressResponse authResponse =\nec2.authorizeSecurityGroupIngress(authRequest);\nSystem.out.printf(\n\"Successfully added ingress policy to Security Group %s\",\ngroupName);\nreturn resp.groupId();\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nTo add an egress rule to the security group, provide similar data in an\nAuthorizeSecurityGroupEgressRequest to the Ec2Client\u2019s authorizeSecurityGroupEgress\nmethod.\nSee the complete example on GitHub.\nWork with security groups in Amazon EC2 359\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribe security groups\nTo describe your security groups or get information about them, call the Ec2Client\u2019s\ndescribeSecurityGroups method. It returns a DescribeSecurityGroupsResponse that you can\nuse to access the list of security groups by calling its securityGroups method, which returns a\nlist of SecurityGroup objects.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;\nimport software.amazon.awssdk.services.ec2.model.SecurityGroup;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nCode\npublic static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) {\ntry {\nDescribeSecurityGroupsRequest request =\nDescribeSecurityGroupsRequest.builder()\n.groupIds(groupId).build();\nDescribeSecurityGroupsResponse response =\nec2.describeSecurityGroups(request);\nfor(SecurityGroup group : response.securityGroups()) {\nSystem.out.printf(\n\"Found Security Group with id %s, \" +\n\"vpc id %s \" +\n\"and description %s\",\ngroup.groupId(),\ngroup.vpcId(),\ngroup.description());\n}\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nWork with security groups in Amazon EC2 360\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example on GitHub.\nDelete a security group\nTo delete a security group, call the Ec2Client\u2019s deleteSecurityGroup method, passing it a\nDeleteSecurityGroupRequest that contains the ID of the security group to delete.", "mimetype": "text/plain", "start_char_idx": 611862, "end_char_idx": 615969, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "597cd494-1612-4bcf-9bd9-1504a7c76bd4": {"__data__": {"id_": "597cd494-1612-4bcf-9bd9-1504a7c76bd4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a1014947-6138-45b0-895f-7a8bad2d5c92", "node_type": "1", "metadata": {}, "hash": "24b5747f3ff2d9949bf479b2ab4c1496115b15c31ca3251ad51c207adbcf7948", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "12bd2db6-d9e7-4822-b422-9125a30b642d", "node_type": "1", "metadata": {}, "hash": "1ad99a7cc9e7ce7ecd7a58bc80da9088760785af85518d683f8575322b593cb1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Delete a security group\nTo delete a security group, call the Ec2Client\u2019s deleteSecurityGroup method, passing it a\nDeleteSecurityGroupRequest that contains the ID of the security group to delete.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2Client;\nimport software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupRequest;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nCode\npublic static void deleteEC2SecGroup(Ec2Client ec2,String groupId) {\ntry {\nDeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()\n.groupId(groupId)\n.build();\nec2.deleteSecurityGroup(request);\nSystem.out.printf(\n\"Successfully deleted Security Group with id %s\", groupId);\n} catch (Ec2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Amazon EC2 Security Groups in the Amazon EC2 User Guide for Linux Instances\n\u2022 Authorize inbound traffic for Your Linux Instances in the Amazon EC2 User Guide for Linux\nInstances\n\u2022 CreateSecurityGroup in the Amazon EC2 API Reference\nWork with security groups in Amazon EC2 361\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 DescribeSecurityGroups in the Amazon EC2 API Reference\n\u2022 DeleteSecurityGroup in the Amazon EC2 API Reference\n\u2022 AuthorizeSecurityGroupIngress in the Amazon EC2 API Reference\nWork with Amazon EC2 instance metadata\nA Java SDK client for the Amazon EC2 Instance Metadata Service (metadata client) allows your\napplications to access metadata on their local EC2 instance. The metadata client works with the\nlocal instance of IMDSv2 (Instance Metadata Service v2) and uses session-oriented requests.\nTwo client classes are available in the SDK. The synchronous Ec2MetadataClient is for blocking\noperations, and the Ec2MetadataAsyncClient is for asynchronous, non-blocking use cases.\nGet started\nTo use the metadata client, add the imds Maven artifact to your project. You also need classes for\nan SdkHttpClient (or an SdkAsyncHttpClient for the asynchronous variant) on the classpath.\nThe following Maven XML shows dependency snippets for using the synchronous\nUrlConnectionHttpClient along with the dependency for metadata clients.\n\n\n\nsoftware.amazon.awssdk\nbom\nVERSION\npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\nimds\n\n\nsoftware.amazon.awssdk\nWork with Amazon EC2 instance metadata 362\nAWS SDK for Java 2.x Developer Guide for version 2.x\nurl-connection-client\n\n\n\nSearch the Maven central repository for the latest version of the bom artifact.\nTo use an asynchronous HTTP client, replace the dependency snippet for the url-connection-\nclient artifact. For example, the following snippet brings in the NettyNioAsyncHttpClient\nimplementation.\n\nsoftware.amazon.awssdk\nnetty-nio-client\n\nUse the metadata client\nInstantiate a metadata client\nYou can instantiate an instance of a synchronous Ec2MetadataClient when only one\nimplementation of the SdkHttpClient interface is present on the classpath. To do so, call the\nstatic Ec2MetadataClient#create() method as shown in the following snippet.\nEc2MetadataClient client = Ec2MetadataClient.create(); //\n'Ec2MetadataAsyncClient#create' is the asynchronous version.\nIf your application has multiple implementations of the SdkHttpClient or\nSdkHttpAsyncClient interface, you must specify an implementation for the metadata client to\nuse as shown in the the section called \u201cConfigurable HTTP client\u201d section.\nNote\nFor most service clients, such as Amazon S3, the SDK for Java automatically adds\nimplementations of the SdkHttpClient or SdkHttpAsyncClient interface. If your\nmetadata client uses the same implementation, then Ec2MetadataClient#create()\nwill work. If you require a different implementation, you must specify it when you create\nthe metadata client.\nWork with Amazon EC2 instance metadata 363\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSend requests\nTo retrieve instance metadata, instantiate the EC2MetadataClient class and call the get method\nwith a path parameter that specifies the instance metadata category.\nThe following example prints the value associated with the ami-id key to the console.", "mimetype": "text/plain", "start_char_idx": 615775, "end_char_idx": 620404, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "12bd2db6-d9e7-4822-b422-9125a30b642d": {"__data__": {"id_": "12bd2db6-d9e7-4822-b422-9125a30b642d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "597cd494-1612-4bcf-9bd9-1504a7c76bd4", "node_type": "1", "metadata": {}, "hash": "ea8ba362d1be65166c493d060d30552b3a34276fa9d4e88f4ba9616f867ea313", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d3e85526-3917-4338-a29a-26974d4be77f", "node_type": "1", "metadata": {}, "hash": "3715418787598ea5354fea2e482dca271e80d1ff36bf74f4f8750a852c807ee8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If your application has multiple implementations of the SdkHttpClient or\nSdkHttpAsyncClient interface, you must specify an implementation for the metadata client to\nuse as shown in the the section called \u201cConfigurable HTTP client\u201d section.\nNote\nFor most service clients, such as Amazon S3, the SDK for Java automatically adds\nimplementations of the SdkHttpClient or SdkHttpAsyncClient interface. If your\nmetadata client uses the same implementation, then Ec2MetadataClient#create()\nwill work. If you require a different implementation, you must specify it when you create\nthe metadata client.\nWork with Amazon EC2 instance metadata 363\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSend requests\nTo retrieve instance metadata, instantiate the EC2MetadataClient class and call the get method\nwith a path parameter that specifies the instance metadata category.\nThe following example prints the value associated with the ami-id key to the console.\nEc2MetadataClient client = Ec2MetadataClient.create();\nEc2MetadataResponse response = client.get(\"/latest/meta-data/ami-id\");\nSystem.out.println(response.asString());\nclient.close(); // Closes the internal resources used by the Ec2MetadataClient class.\nIf the path isn't valid, the get method throws an exception.\nReuse the same client instance for multiple requests, but call close on the client when it is no\nlonger needed to release resources. After the close method is called, the client instance can't be\nused anymore.\nParse responses\nEC2 instance metadata can be output in different formats. Plain text and JSON are the most\ncommonly used formats. The metadata clients offer ways to work with those formats.\nAs the following example shows, use the asString method to get the data as a Java string. You\ncan also use the asList method to separate a plain text response that returns multiple lines.\nEc2MetadataClient client = Ec2MetadataClient.create();\nEc2MetadataResponse response = client.get(\"/latest/meta-data/\");\nString fullResponse = response.asString();\nList splits = response.asList();\nIf the response is in JSON, use the Ec2MetadataResponse#asDocument method to parse the\nJSON response into a Document instance as shown in the following code snippet.\nDocument fullResponse = response.asDocument();\nAn exception will be thrown if the format of the metadata is not in JSON. If the response is\nsuccessfully parsed, you can use the document API to inspect the response in more detail. Consult\nthe instance metadata category chart to learn which metadata categories deliver JSON-formatted\nresponses.\nWork with Amazon EC2 instance metadata 364\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConfigure a metadata client\nRetries\nYou can configure a metadata client with a retry mechanism. If you do, then the client can\nautomatically retry requests that fail for unexpected reasons. By default, the client retries three\ntimes on a failed request with an exponential backoff time between attempts.\nIf your use case requires a different retry mechanism, you can customize the client using the\nretryPolicy method on its builder. For example, the following example shows a synchronous\nclient configured with a fixed delay of two seconds between attempts and five retry attempts.\nBackoffStrategy fixedBackoffStrategy =\nFixedDelayBackoffStrategy.create(Duration.ofSeconds(2));\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.retryPolicy(retryPolicyBuilder ->\nretryPolicyBuilder.numRetries(5)\n.backoffStrategy(fixedBackoffStrategy))\n.build();\nThere are several BackoffStrategies that you can use with a metadata client.\nYou can also disable the retry mechanism entirely, as the following snippet shows.\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.retryPolicy(Ec2MetadataRetryPolicy.none())\n.build();\nUsing Ec2MetadataRetryPolicy#none() disables the default retry policy so that the metadata\nclient attempts no retries.\nIP version\nBy default, a metadata client uses the IPV4 endpoint at http://169.254.169.254. To change\nthe client to use the IPV6 version, use either the endpointMode or the endpoint method of the\nbuilder. An exception results if both methods are called on the builder.\nThe following examples show both IPV6 options.\nWork with Amazon EC2 instance metadata 365\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.endpointMode(EndpointMode.IPV6)\n.build();\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.endpoint(URI.create(\"http://[fd00:ec2::254]\"))\n.build();\nKey features\nAsynchronous client\nTo use the non-blocking version of the client, instantiate an instance of the\nEc2MetadataAsyncClient class. The code in the following example creates an asynchronous\nclient with default settings and uses the get method to retrieve the value for the ami-id key.", "mimetype": "text/plain", "start_char_idx": 619452, "end_char_idx": 624271, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d3e85526-3917-4338-a29a-26974d4be77f": {"__data__": {"id_": "d3e85526-3917-4338-a29a-26974d4be77f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "12bd2db6-d9e7-4822-b422-9125a30b642d", "node_type": "1", "metadata": {}, "hash": "1ad99a7cc9e7ce7ecd7a58bc80da9088760785af85518d683f8575322b593cb1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "30213cf9-6501-42c0-b453-497ae86a167c", "node_type": "1", "metadata": {}, "hash": "00f5d02bff5f765d7d129c357191e7f9446af56b9591a8f0b12cdc2ffa66bb3d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "To change\nthe client to use the IPV6 version, use either the endpointMode or the endpoint method of the\nbuilder. An exception results if both methods are called on the builder.\nThe following examples show both IPV6 options.\nWork with Amazon EC2 instance metadata 365\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.endpointMode(EndpointMode.IPV6)\n.build();\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.endpoint(URI.create(\"http://[fd00:ec2::254]\"))\n.build();\nKey features\nAsynchronous client\nTo use the non-blocking version of the client, instantiate an instance of the\nEc2MetadataAsyncClient class. The code in the following example creates an asynchronous\nclient with default settings and uses the get method to retrieve the value for the ami-id key.\nEc2MetadataAsyncClient asyncClient = Ec2MetadataAsyncClient.create();\nCompletableFuture response = asyncClient.get(\"/latest/meta-data/\nami-id\");\nThe java.util.concurrent.CompletableFuture returned by the get method completes\nwhen the response returns. The following example prints the ami-id metadata to the console.\nresponse.thenAccept(metadata -> System.out.println(metadata.asString()));\nConfigurable HTTP client\nThe builder for each metadata client has a httpClient method that you can use to supply a\ncustomized HTTP client.\nThe following example shows code for a custom UrlConnectionHttpClient instance.\nSdkHttpClient httpClient =\nUrlConnectionHttpClient.builder()\n.socketTimeout(Duration.ofMinutes(5))\n.proxyConfiguration(proxy ->\nproxy.endpoint(URI.create(\"http://proxy.example.net:8888\"))))\nWork with Amazon EC2 instance metadata 366\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nEc2MetadataClient metaDataClient =\nEc2MetadataClient.builder()\n.httpClient(httpClient)\n.build();\n// Use the metaDataClient instance.\nmetaDataClient.close(); // Close the instance when no longer needed.\nThe following example shows code for a custom NettyNioAsyncHttpClient instance with an\nasynchronous metadata client.\nSdkAsyncHttpClient httpAsyncClient =\nNettyNioAsyncHttpClient.builder()\n.connectionTimeout(Duration.ofMinutes(5))\n.maxConcurrency(100)\n.build();\nEc2MetadataAsyncClient asyncMetaDataClient =\nEc2MetadataAsyncClient.builder()\n.httpClient(httpAsyncClient)\n.build();\n// Use the asyncMetaDataClient instance.\nasyncMetaDataClient.close(); // Close the instance when no longer needed.\nThe the section called \u201cHTTP clients\u201d topic in this guide provides details on how to configure the\nHTTP clients that are available in the SDK for Java.\nToken caching\nBecause the metadata clients use IMDSv2, all requests are associated with a session. A session\nis defined by a token that has an expiration, which the metadata client manages for you. Every\nmetadata request automatically reuses the token until it expires.\nBy default, a token lasts for six hours (21,600 seconds). We recommend that you keep the default\ntime-to-live value, unless your specific use case requires advanced configuration.\nIf needed, configure the duration by using the tokenTtl builder method. For example, the code in\nthe following snippet creates a client with a session duration of five minutes.\nEc2MetadataClient client =\nEc2MetadataClient.builder()\n.tokenTtl(Duration.ofMinutes(5))\nWork with Amazon EC2 instance metadata 367\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nIf you omit calling the tokenTtl method on the builder, the default duration of 21,600 is used\ninstead.\nWork with IAM\nThis section provides examples of programming AWS Identity and Access Management (IAM) by\nusing the AWS SDK for Java 2.x.\nAWS Identity and Access Management (IAM) enables you to securely control access to AWS services\nand resources for your users. Using IAM, you can create and manage AWS users and groups, and\nuse permissions to allow and deny their access to AWS resources. For a complete guide to IAM, visit\nthe IAM User Guide.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\n\u2022 Manage IAM access keys\n\u2022 Manage IAM Users\n\u2022 Create IAM policies with the AWS SDK for Java 2.x\n\u2022 Work with IAM policies\n\u2022 Work with IAM server certificates\nManage IAM access keys\nCreate an access key\nTo create an IAM access key, call the IamClient\u2019s createAccessKey method with a\nCreateAccessKeyRequest object.\nNote\nYou must set the region to AWS_GLOBAL for IamClient calls to work because IAM is a\nglobal service.", "mimetype": "text/plain", "start_char_idx": 623447, "end_char_idx": 628095, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "30213cf9-6501-42c0-b453-497ae86a167c": {"__data__": {"id_": "30213cf9-6501-42c0-b453-497ae86a167c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d3e85526-3917-4338-a29a-26974d4be77f", "node_type": "1", "metadata": {}, "hash": "3715418787598ea5354fea2e482dca271e80d1ff36bf74f4f8750a852c807ee8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a262f90b-3ba1-4d62-bf47-a9b100e9b3ef", "node_type": "1", "metadata": {}, "hash": "95e2ca13e9baafa1e4caa8f60b097266f9021b12d26f42470d012d486d96aad4", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Using IAM, you can create and manage AWS users and groups, and\nuse permissions to allow and deny their access to AWS resources. For a complete guide to IAM, visit\nthe IAM User Guide.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\n\u2022 Manage IAM access keys\n\u2022 Manage IAM Users\n\u2022 Create IAM policies with the AWS SDK for Java 2.x\n\u2022 Work with IAM policies\n\u2022 Work with IAM server certificates\nManage IAM access keys\nCreate an access key\nTo create an IAM access key, call the IamClient\u2019s createAccessKey method with a\nCreateAccessKeyRequest object.\nNote\nYou must set the region to AWS_GLOBAL for IamClient calls to work because IAM is a\nglobal service.\nIAM 368\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest;\nimport software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static String createIAMAccessKey(IamClient iam,String user) {\ntry {\nCreateAccessKeyRequest request = CreateAccessKeyRequest.builder()\n.userName(user).build();\nCreateAccessKeyResponse response = iam.createAccessKey(request);\nString keyId = response.accessKey().accessKeyId();\nreturn keyId;\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nList access keys\nTo list the access keys for a given user, create a ListAccessKeysRequest object that contains the\nuser name to list keys for, and pass it to the IamClient\u2019s listAccessKeys method.\nNote\nIf you do not supply a user name to listAccessKeys, it will attempt to list access keys\nassociated with the AWS account that signed the request.\nImports\nManage IAM access keys 369\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.iam.model.AccessKeyMetadata;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.ListAccessKeysRequest;\nimport software.amazon.awssdk.services.iam.model.ListAccessKeysResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nCode\npublic static void listKeys( IamClient iam,String userName ){\ntry {\nboolean done = false;\nString newMarker = null;\nwhile (!done) {\nListAccessKeysResponse response;\nif(newMarker == null) {\nListAccessKeysRequest request = ListAccessKeysRequest.builder()\n.userName(userName).build();\nresponse = iam.listAccessKeys(request);\n} else {\nListAccessKeysRequest request = ListAccessKeysRequest.builder()\n.userName(userName)\n.marker(newMarker).build();\nresponse = iam.listAccessKeys(request);\n}\nfor (AccessKeyMetadata metadata :\nresponse.accessKeyMetadata()) {\nSystem.out.format(\"Retrieved access key %s\",\nmetadata.accessKeyId());\n}\nif (!response.isTruncated()) {\ndone = true;\n} else {\nnewMarker = response.marker();\n}\n}\n} catch (IamException e) {\nManage IAM access keys 370\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nThe results of listAccessKeys are paged (with a default maximum of 100 records per\ncall). You can call isTruncated on the returned ListAccessKeysResponse object to\nsee if the query returned fewer results then are available. If so, then call marker on the\nListAccessKeysResponse and use it when creating a new request. Use that new request in the\nnext invocation of listAccessKeys.\nSee the complete example on GitHub.\nRetrieve an access key\u2019s last used time\nTo get the time an access key was last used, call the IamClient\u2019s\ngetAccessKeyLastUsed method with the access key\u2019s ID (which can be passed in using a\nGetAccessKeyLastUsedRequest object.\nYou can then use the returned GetAccessKeyLastUsedResponse object to retrieve the key\u2019s last\nused time.", "mimetype": "text/plain", "start_char_idx": 627233, "end_char_idx": 631382, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a262f90b-3ba1-4d62-bf47-a9b100e9b3ef": {"__data__": {"id_": "a262f90b-3ba1-4d62-bf47-a9b100e9b3ef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "30213cf9-6501-42c0-b453-497ae86a167c", "node_type": "1", "metadata": {}, "hash": "00f5d02bff5f765d7d129c357191e7f9446af56b9591a8f0b12cdc2ffa66bb3d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6287483c-f8f8-42c3-9475-ea87df4a103f", "node_type": "1", "metadata": {}, "hash": "76bacb6960d881a708114ef51868267742c0ebae42df0e9a9c464a33e7431289", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "You can call isTruncated on the returned ListAccessKeysResponse object to\nsee if the query returned fewer results then are available. If so, then call marker on the\nListAccessKeysResponse and use it when creating a new request. Use that new request in the\nnext invocation of listAccessKeys.\nSee the complete example on GitHub.\nRetrieve an access key\u2019s last used time\nTo get the time an access key was last used, call the IamClient\u2019s\ngetAccessKeyLastUsed method with the access key\u2019s ID (which can be passed in using a\nGetAccessKeyLastUsedRequest object.\nYou can then use the returned GetAccessKeyLastUsedResponse object to retrieve the key\u2019s last\nused time.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.GetAccessKeyLastUsedRequest;\nimport software.amazon.awssdk.services.iam.model.GetAccessKeyLastUsedResponse;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void getAccessKeyLastUsed(IamClient iam, String accessId ){\ntry {\nGetAccessKeyLastUsedRequest request = GetAccessKeyLastUsedRequest.builder()\n.accessKeyId(accessId).build();\nGetAccessKeyLastUsedResponse response = iam.getAccessKeyLastUsed(request);\nManage IAM access keys 371\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Access key was last used at: \" +\nresponse.accessKeyLastUsed().lastUsedDate());\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done\");\n}\nSee the complete example on GitHub.\nActivate or deactivate access keys\nYou can activate or deactivate an access key by creating an UpdateAccessKeyRequest object,\nproviding the access key ID, optionally the user name, and the desired status, then passing the\nrequest object to the IamClient\u2019s updateAccessKey method.\nImports\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.StatusType;\nimport software.amazon.awssdk.services.iam.model.UpdateAccessKeyRequest;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nCode\npublic static void updateKey(IamClient iam, String username, String accessId,\nString status ) {\ntry {\nif (status.toLowerCase().equalsIgnoreCase(\"active\")) {\nstatusType = StatusType.ACTIVE;\n} else if (status.toLowerCase().equalsIgnoreCase(\"inactive\")) {\nstatusType = StatusType.INACTIVE;\n} else {\nstatusType = StatusType.UNKNOWN_TO_SDK_VERSION;\n}\nUpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder()\n.accessKeyId(accessId)\n.userName(username)\nManage IAM access keys 372\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.status(statusType)\n.build();\niam.updateAccessKey(request);\nSystem.out.printf(\n\"Successfully updated the status of access key %s to\" +\n\"status %s for user %s\", accessId, status, username);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nDelete an access key\nTo permanently delete an access key, call the IamClient\u2019s deleteKey method, providing it with\na DeleteAccessKeyRequest containing the access key\u2019s ID and username.\nNote\nOnce deleted, a key can no longer be retrieved or used. To temporarily deactivate a key so\nthat it can be activated again later, use updateAccessKey method instead.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void deleteKey(IamClient iam ,String username, String accessKey ) {\ntry {\nDeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()\nManage IAM access keys 373\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.accessKeyId(accessKey)\n.userName(username)\n.build();\niam.deleteAccessKey(request);\nSystem.out.println(\"Successfully deleted access key \" + accessKey +\n\" from user \" + username);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.", "mimetype": "text/plain", "start_char_idx": 630725, "end_char_idx": 634933, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6287483c-f8f8-42c3-9475-ea87df4a103f": {"__data__": {"id_": "6287483c-f8f8-42c3-9475-ea87df4a103f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a262f90b-3ba1-4d62-bf47-a9b100e9b3ef", "node_type": "1", "metadata": {}, "hash": "95e2ca13e9baafa1e4caa8f60b097266f9021b12d26f42470d012d486d96aad4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e4400356-b71d-4fef-88ab-fc4dadb84e6e", "node_type": "1", "metadata": {}, "hash": "49b2ae47f77cc35423d2cc69337174077e88af918e30e1f71cf8a0f664d5a5e9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Imports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void deleteKey(IamClient iam ,String username, String accessKey ) {\ntry {\nDeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()\nManage IAM access keys 373\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.accessKeyId(accessKey)\n.userName(username)\n.build();\niam.deleteAccessKey(request);\nSystem.out.println(\"Successfully deleted access key \" + accessKey +\n\" from user \" + username);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 CreateAccessKey in the IAM API Reference\n\u2022 ListAccessKeys in the IAM API Reference\n\u2022 GetAccessKeyLastUsed in the IAM API Reference\n\u2022 UpdateAccessKey in the IAM API Reference\n\u2022 DeleteAccessKey in the IAM API Reference\nManage IAM Users\nCreate a User\nCreate a new IAM user by providing the user name to the IamClient\u2019s createUser method using a\nCreateUserRequest object containing the user name.\nImports\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.services.iam.model.CreateUserRequest;\nimport software.amazon.awssdk.services.iam.model.CreateUserResponse;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nManage IAM Users 374\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.iam.waiters.IamWaiter;\nimport software.amazon.awssdk.services.iam.model.GetUserRequest;\nimport software.amazon.awssdk.services.iam.model.GetUserResponse;\nCode\npublic static String createIAMUser(IamClient iam, String username ) {\ntry {\n// Create an IamWaiter object\nIamWaiter iamWaiter = iam.waiter();\nCreateUserRequest request = CreateUserRequest.builder()\n.userName(username)\n.build();\nCreateUserResponse response = iam.createUser(request);\n// Wait until the user is created\nGetUserRequest userRequest = GetUserRequest.builder()\n.userName(response.user().userName())\n.build();\nWaiterResponse waitUntilUserExists =\niamWaiter.waitUntilUserExists(userRequest);\nwaitUntilUserExists.matched().response().ifPresent(System.out::println);\nreturn response.user().userName();\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nList Users\nTo list the IAM users for your account, create a new ListUsersRequest and pass it to the IamClient\u2019s\nlistUsers method. You can retrieve the list of users by calling users on the returned\nListUsersResponse object.\nManage IAM Users 375\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe list of users returned by listUsers is paged. You can check to see there are more results to\nretrieve by calling the response object\u2019s isTruncated method. If it returns true, then call the\nresponse object\u2019s marker() method. Use the marker value to create a new request object. Then\ncall the listUsers method again with the new request.\nImports\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.ListUsersRequest;\nimport software.amazon.awssdk.services.iam.model.ListUsersResponse;\nimport software.amazon.awssdk.services.iam.model.User;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nCode\npublic static void listAllUsers(IamClient iam ) {\ntry {\nboolean done = false;\nString newMarker = null;\nwhile(!done) {\nListUsersResponse response;\nif (newMarker == null) {\nListUsersRequest request = ListUsersRequest.builder().build();\nresponse = iam.listUsers(request);\n} else {\nListUsersRequest request = ListUsersRequest.builder()\n.marker(newMarker).build();\nresponse = iam.listUsers(request);\n}\nfor(User user : response.users()) {\nSystem.out.format(\"\\n Retrieved user %s\", user.userName());\n}\nif(!response.isTruncated()) {\ndone = true;\n} else {\nnewMarker = response.marker();\nManage IAM Users 376\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.", "mimetype": "text/plain", "start_char_idx": 634133, "end_char_idx": 638558, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e4400356-b71d-4fef-88ab-fc4dadb84e6e": {"__data__": {"id_": "e4400356-b71d-4fef-88ab-fc4dadb84e6e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6287483c-f8f8-42c3-9475-ea87df4a103f", "node_type": "1", "metadata": {}, "hash": "76bacb6960d881a708114ef51868267742c0ebae42df0e9a9c464a33e7431289", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b24224fd-cf67-49b0-bfe6-ad8ca23bf4d9", "node_type": "1", "metadata": {}, "hash": "f4f418fc4de4d1ecd4cfbb51514a866bd1478ecc4c540d16b673b9c0cc9e6ad3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Update a User\nTo update a user, call the IamClient object\u2019s updateUser method, which takes a\nUpdateUserRequest object that you can use to change the user\u2019s name or path.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.UpdateUserRequest;\nCode\npublic static void updateIAMUser(IamClient iam, String curName,String newName ) {\ntry {\nUpdateUserRequest request = UpdateUserRequest.builder()\n.userName(curName)\n.newUserName(newName)\n.build();\niam.updateUser(request);\nSystem.out.printf(\"Successfully updated user to username %s\",\nnewName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nManage IAM Users 377\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDelete a User\nTo delete a user, call the IamClient\u2019s deleteUser request with a UpdateUserRequest object set\nwith the user name to delete.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.DeleteUserRequest;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void deleteIAMUser(IamClient iam, String userName) {\ntry {\nDeleteUserRequest request = DeleteUserRequest.builder()\n.userName(userName)\n.build();\niam.deleteUser(request);\nSystem.out.println(\"Successfully deleted IAM user \" + userName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore Information\n\u2022 IAM Users in the IAM User Guide\n\u2022 Managing IAM Users in the IAM User Guide\n\u2022 CreateUser in the IAM API Reference\n\u2022 ListUsers in the IAM API Reference\n\u2022 UpdateUser in the IAM API Reference\n\u2022 DeleteUser in the IAM API Reference\nManage IAM Users 378\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate IAM policies with the AWS SDK for Java 2.x\nThe IAM Policy Builder API is a library that you can use to build IAM policies in Java and upload\nthem to AWS Identity and Access Management (IAM).\nInstead of building an IAM policy by manually assembling a JSON string or by reading a file, the\nAPI provides a client-side, object-oriented approach to generate the JSON string. When you read an\nexisting IAM policy in JSON format, the API converts it to an IamPolicy instance for handling.\nThe IAM Policy Builder API became available with version 2.20.105 of the SDK, so use that version\nor a later one in your Maven build file. The latest version number of the SDK is listed on Maven\ncentral.\nThe following snippet shows an example dependency block for a Maven pom.xml file. This allows\nyou to use the IAM Policy Builder API in your project.\n\nsoftware.amazon.awssdk\niam-policy-builder\n2.27.21\n\nCreate an IamPolicy\nThis section shows several examples of how to build policies by using the IAM Policy Builder API.\nIn each of the following examples, start with the IamPolicy.Builder and add one or more\nstatements by using the addStatement method. Following this pattern, the IamStatement.Builder\nhas methods to add the effect, actions, resources, and conditions to the statement.\nExample: Create a time-based policy\nThe following example creates an identity-based policy that permits the Amazon DynamoDB\nGetItem action between two points in time.\npublic String timeBasedPolicyExample() {\nIamPolicy policy = IamPolicy.builder()\n.addStatement(b -> b\n.effect(IamEffect.ALLOW)\n.addAction(\"dynamodb:GetItem\")\n.addResource(IamResource.ALL)\nCreate IAM policies 379\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.addCondition(b1 -> b1\n.operator(IamConditionOperator.DATE_GREATER_THAN)\n.key(\"aws:CurrentTime\")\n.value(\"2020-04-01T00:00:00Z\"))\n.addCondition(b1 -> b1\n.operator(IamConditionOperator.DATE_LESS_THAN)\n.key(\"aws:CurrentTime\")\n.value(\"2020-06-30T23:59:59Z\")))\n.build();\n// Use an IamPolicyWriter to write out the JSON string to a more readable\nformat.\nreturn policy.toJson(IamPolicyWriter.builder()\n.prettyPrint(true)\n.build());\n}\nJSON output\nThe last statement in the previous example returns the following JSON string.\nRead more about this example in the AWS Identity and Access Management User Guide.", "mimetype": "text/plain", "start_char_idx": 638559, "end_char_idx": 642963, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b24224fd-cf67-49b0-bfe6-ad8ca23bf4d9": {"__data__": {"id_": "b24224fd-cf67-49b0-bfe6-ad8ca23bf4d9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e4400356-b71d-4fef-88ab-fc4dadb84e6e", "node_type": "1", "metadata": {}, "hash": "49b2ae47f77cc35423d2cc69337174077e88af918e30e1f71cf8a0f664d5a5e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0c1a1c91-e431-4aa2-9ac6-bccbb830fbd6", "node_type": "1", "metadata": {}, "hash": "a7bc745b1a7b24caf5d59314afed19f66cb78e5d9419f251d4c2533a9163eb85", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return policy.toJson(IamPolicyWriter.builder()\n.prettyPrint(true)\n.build());\n}\nJSON output\nThe last statement in the previous example returns the following JSON string.\nRead more about this example in the AWS Identity and Access Management User Guide.\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Allow\",\n\"Action\" : \"dynamodb:GetItem\",\n\"Resource\" : \"*\",\n\"Condition\" : {\n\"DateGreaterThan\" : {\n\"aws:CurrentTime\" : \"2020-04-01T00:00:00Z\"\n},\n\"DateLessThan\" : {\n\"aws:CurrentTime\" : \"2020-06-30T23:59:59Z\"\n}\n}\n}\nExample: Specify multiple conditions\nThe following example shows how you can create an identity-based policy that allows access to\nspecific DynamoDB attributes. The policy contains two conditions.\nCreate IAM policies 380\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String multipleConditionsExample() {\nIamPolicy policy = IamPolicy.builder()\n.addStatement(b -> b\n.effect(IamEffect.ALLOW)\n.addAction(\"dynamodb:GetItem\")\n.addAction(\"dynamodb:BatchGetItem\")\n.addAction(\"dynamodb:Query\")\n.addAction(\"dynamodb:PutItem\")\n.addAction(\"dynamodb:UpdateItem\")\n.addAction(\"dynamodb:DeleteItem\")\n.addAction(\"dynamodb:BatchWriteItem\")\n.addResource(\"arn:aws:dynamodb:*:*:table/table-name\")\n.addConditions(IamConditionOperator.STRING_EQUALS.addPrefix(\"ForAllValues:\"),\n\"dynamodb:Attributes\",\nList.of(\"column-name1\", \"column-name2\", \"column-\nname3\"))\n.addCondition(b1 ->\nb1.operator(IamConditionOperator.STRING_EQUALS.addSuffix(\"IfExists\"))\n.key(\"dynamodb:Select\")\n.value(\"SPECIFIC_ATTRIBUTES\")))\n.build();\nreturn policy.toJson(IamPolicyWriter.builder()\n.prettyPrint(true).build());\n}\nJSON output\nThe last statement in the previous example returns the following JSON string.\nRead more about this example in the AWS Identity and Access Management User Guide.\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Allow\",\n\"Action\" : [ \"dynamodb:GetItem\", \"dynamodb:BatchGetItem\", \"dynamodb:Query\",\n\"dynamodb:PutItem\", \"dynamodb:UpdateItem\", \"dynamodb:DeleteItem\",\n\"dynamodb:BatchWriteItem\" ],\n\"Resource\" : \"arn:aws:dynamodb:*:*:table/table-name\",\n\"Condition\" : {\n\"ForAllValues:StringEquals\" : {\nCreate IAM policies 381\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"dynamodb:Attributes\" : [ \"column-name1\", \"column-name2\", \"column-name3\" ]\n},\n\"StringEqualsIfExists\" : {\n\"dynamodb:Select\" : \"SPECIFIC_ATTRIBUTES\"\n}\n}\n}\nExample: Specify principals\nThe following example shows how to create a resource-based policy that denies access to a bucket\nfor all principals except for those specified in the condition.\npublic String specifyPrincipalsExample() {\nIamPolicy policy = IamPolicy.builder()\n.addStatement(b -> b\n.effect(IamEffect.DENY)\n.addAction(\"s3:*\")\n.addPrincipal(IamPrincipal.ALL)\n.addResource(\"arn:aws:s3:::BUCKETNAME/*\")\n.addResource(\"arn:aws:s3:::BUCKETNAME\")\n.addCondition(b1 -> b1\n.operator(IamConditionOperator.ARN_NOT_EQUALS)\n.key(\"aws:PrincipalArn\")\n.value(\"arn:aws:iam::444455556666:user/user-name\")))\n.build();\nreturn policy.toJson(IamPolicyWriter.builder()\n.prettyPrint(true).build());\n}\nJSON output\nThe last statement in the previous example returns the following JSON string.\nRead more about this example in the AWS Identity and Access Management User Guide.\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Deny\",\n\"Principal\" : \"*\",\n\"Action\" : \"s3:*\",\nCreate IAM policies 382\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"Resource\" : [ \"arn:aws:s3:::BUCKETNAME/*\", \"arn:aws:s3:::BUCKETNAME\" ],\n\"Condition\" : {\n\"ArnNotEquals\" : {\n\"aws:PrincipalArn\" : \"arn:aws:iam::444455556666:user/user-name\"\n}\n}\n}\n}\nExample: Allow cross-account access\nThe following example shows how to allow another AWS account to upload objects to your bucket\nwhile retaining full owner control of the uploaded objects.", "mimetype": "text/plain", "start_char_idx": 642712, "end_char_idx": 646457, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0c1a1c91-e431-4aa2-9ac6-bccbb830fbd6": {"__data__": {"id_": "0c1a1c91-e431-4aa2-9ac6-bccbb830fbd6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b24224fd-cf67-49b0-bfe6-ad8ca23bf4d9", "node_type": "1", "metadata": {}, "hash": "f4f418fc4de4d1ecd4cfbb51514a866bd1478ecc4c540d16b673b9c0cc9e6ad3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b1cf77dc-e69c-417e-8920-f7bfbce96ffa", "node_type": "1", "metadata": {}, "hash": "6ddce18cde3de647abec59b66051b4490ec15e250f282b57b0c07b06d780978f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Read more about this example in the AWS Identity and Access Management User Guide.\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Deny\",\n\"Principal\" : \"*\",\n\"Action\" : \"s3:*\",\nCreate IAM policies 382\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"Resource\" : [ \"arn:aws:s3:::BUCKETNAME/*\", \"arn:aws:s3:::BUCKETNAME\" ],\n\"Condition\" : {\n\"ArnNotEquals\" : {\n\"aws:PrincipalArn\" : \"arn:aws:iam::444455556666:user/user-name\"\n}\n}\n}\n}\nExample: Allow cross-account access\nThe following example shows how to allow another AWS account to upload objects to your bucket\nwhile retaining full owner control of the uploaded objects.\npublic String allowCrossAccountAccessExample() {\nIamPolicy policy = IamPolicy.builder()\n.addStatement(b -> b\n.effect(IamEffect.ALLOW)\n.addPrincipal(IamPrincipalType.AWS, \"111122223333\")\n.addAction(\"s3:PutObject\")\n.addResource(\"arn:aws:s3:::amzn-s3-demo-bucket/*\")\n.addCondition(b1 -> b1\n.operator(IamConditionOperator.STRING_EQUALS)\n.key(\"s3:x-amz-acl\")\n.value(\"bucket-owner-full-control\")))\n.build();\nreturn policy.toJson(IamPolicyWriter.builder()\n.prettyPrint(true).build());\n}\nJSON output\nThe last statement in the previous example returns the following JSON string.\nRead more about this example in the Amazon Simple Storage Service User Guide.\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Allow\",\n\"Principal\" : {\n\"AWS\" : \"111122223333\"\n},\nCreate IAM policies 383\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"Action\" : \"s3:PutObject\",\n\"Resource\" : \"arn:aws:s3:::amzn-s3-demo-bucket/*\",\n\"Condition\" : {\n\"StringEquals\" : {\n\"s3:x-amz-acl\" : \"bucket-owner-full-control\"\n}\n}\n}\n}\nUse an IamPolicy with IAM\nAfter you have created a IamPolicy instance, you use an IamClient to work with the IAM\nservice.\nThe following example builds a policy that allows an IAM identity to write items to a DynamoDB\ntable in the account that is specified with the accountID parameter. The policy is then uploaded\nto IAM as a JSON string.\npublic String createAndUploadPolicyExample(IamClient iam, String accountID, String\npolicyName) {\n// Build the policy.\nIamPolicy policy =\nIamPolicy.builder() // 'version' defaults to \"2012-10-17\".\n.addStatement(IamStatement.builder()\n.effect(IamEffect.ALLOW)\n.addAction(\"dynamodb:PutItem\")\n.addResource(\"arn:aws:dynamodb:us-east-1:\" + accountID\n+ \":table/exampleTableName\")\n.build())\n.build();\n// Upload the policy.\niam.createPolicy(r ->\nr.policyName(policyName).policyDocument(policy.toJson()));\nreturn policy.toJson(IamPolicyWriter.builder().prettyPrint(true).build());\n}\nThe next example builds on the previous example. The code downloads the policy and uses it as\nthe basis for a new policy by copying and altering the statement. The new policy is then uploaded.\npublic String createNewBasedOnExistingPolicyExample(IamClient iam, String\naccountID, String policyName, String newPolicyName) {\nCreate IAM policies 384\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString policyArn = \"arn:aws:iam::\" + accountID + \":policy/\" + policyName;\nGetPolicyResponse getPolicyResponse = iam.getPolicy(r ->\nr.policyArn(policyArn));\nString policyVersion = getPolicyResponse.policy().defaultVersionId();\nGetPolicyVersionResponse getPolicyVersionResponse =\niam.getPolicyVersion(r ->\nr.policyArn(policyArn).versionId(policyVersion));\n// Create an IamPolicy instance from the JSON string returned from IAM.\nString decodedPolicy =\nURLDecoder.decode(getPolicyVersionResponse.policyVersion().document(),\nStandardCharsets.UTF_8);\nIamPolicy policy = IamPolicy.fromJson(decodedPolicy);\n/*\nAll IamPolicy components are immutable, so use the copy method that\ncreates a new instance that\ncan be altered in the same method call.\nAdd the ability to get an item from DynamoDB as an additional action.\n*/\nIamStatement newStatement = policy.statements().get(0).copy(s ->\ns.addAction(\"dynamodb:GetItem\"));\n// Create a new statement that replaces the original statement.\nIamPolicy newPolicy = policy.copy(p ->\np.statements(Arrays.asList(newStatement)));\n// Upload the new policy. IAM now has both policies.", "mimetype": "text/plain", "start_char_idx": 645827, "end_char_idx": 649874, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b1cf77dc-e69c-417e-8920-f7bfbce96ffa": {"__data__": {"id_": "b1cf77dc-e69c-417e-8920-f7bfbce96ffa", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0c1a1c91-e431-4aa2-9ac6-bccbb830fbd6", "node_type": "1", "metadata": {}, "hash": "a7bc745b1a7b24caf5d59314afed19f66cb78e5d9419f251d4c2533a9163eb85", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c6346d5-4acb-4b98-acb1-5863237f99a7", "node_type": "1", "metadata": {}, "hash": "cb6bb76c4c98248d532619f39abfff2b3889b265e47cbf8bb05215574a60bb5b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "String decodedPolicy =\nURLDecoder.decode(getPolicyVersionResponse.policyVersion().document(),\nStandardCharsets.UTF_8);\nIamPolicy policy = IamPolicy.fromJson(decodedPolicy);\n/*\nAll IamPolicy components are immutable, so use the copy method that\ncreates a new instance that\ncan be altered in the same method call.\nAdd the ability to get an item from DynamoDB as an additional action.\n*/\nIamStatement newStatement = policy.statements().get(0).copy(s ->\ns.addAction(\"dynamodb:GetItem\"));\n// Create a new statement that replaces the original statement.\nIamPolicy newPolicy = policy.copy(p ->\np.statements(Arrays.asList(newStatement)));\n// Upload the new policy. IAM now has both policies.\niam.createPolicy(r -> r.policyName(newPolicyName)\n.policyDocument(newPolicy.toJson()));\nreturn newPolicy.toJson(IamPolicyWriter.builder().prettyPrint(true).build());\n}\nIamClient\nThe previous examples use an IamClient argument that is created as shown in the following\nsnippet.\nIamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build();\nCreate IAM policies 385\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPolicies in JSON\nThe examples return the following JSON strings.\nFirst example\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Allow\",\n\"Action\" : \"dynamodb:PutItem\",\n\"Resource\" : \"arn:aws:dynamodb:us-east-1:111122223333:table/exampleTableName\"\n}\n}\nSecond example\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : {\n\"Effect\" : \"Allow\",\n\"Action\" : [ \"dynamodb:PutItem\", \"dynamodb:GetItem\" ],\n\"Resource\" : \"arn:aws:dynamodb:us-east-1:111122223333:table/exampleTableName\"\n}\n}\nWork with IAM policies\nCreate a policy\nTo create a new policy, provide the policy\u2019s name and a JSON-formatted policy document in a\nCreatePolicyRequest to the IamClient\u2019s createPolicy method.\nImports\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.services.iam.model.CreatePolicyRequest;\nimport software.amazon.awssdk.services.iam.model.CreatePolicyResponse;\nimport software.amazon.awssdk.services.iam.model.GetPolicyRequest;\nimport software.amazon.awssdk.services.iam.model.GetPolicyResponse;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.waiters.IamWaiter;\nWork with IAM policies 386\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\npublic static String createIAMPolicy(IamClient iam, String policyName ) {\ntry {\n// Create an IamWaiter object\nIamWaiter iamWaiter = iam.waiter();\nCreatePolicyRequest request = CreatePolicyRequest.builder()\n.policyName(policyName)\n.policyDocument(PolicyDocument).build();\nCreatePolicyResponse response = iam.createPolicy(request);\n// Wait until the policy is created\nGetPolicyRequest polRequest = GetPolicyRequest.builder()\n.policyArn(response.policy().arn())\n.build();\nWaiterResponse waitUntilPolicyExists =\niamWaiter.waitUntilPolicyExists(polRequest);\nwaitUntilPolicyExists.matched().response().ifPresent(System.out::println);\nreturn response.policy().arn();\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\" ;\n}\nSee the complete example on GitHub.\nGet a policy\nTo retrieve an existing policy, call the IamClient\u2019s getPolicy method, providing the policy\u2019s ARN\nwithin a GetPolicyRequest object.\nImports\nimport software.amazon.awssdk.services.iam.model.GetPolicyRequest;\nimport software.amazon.awssdk.services.iam.model.GetPolicyResponse;\nimport software.amazon.awssdk.regions.Region;\nWork with IAM policies 387\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void getIAMPolicy(IamClient iam, String policyArn) {\ntry {\nGetPolicyRequest request = GetPolicyRequest.builder()\n.policyArn(policyArn).build();\nGetPolicyResponse response = iam.getPolicy(request);\nSystem.out.format(\"Successfully retrieved policy %s\",\nresponse.policy().policyName());\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.", "mimetype": "text/plain", "start_char_idx": 649191, "end_char_idx": 653418, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4c6346d5-4acb-4b98-acb1-5863237f99a7": {"__data__": {"id_": "4c6346d5-4acb-4b98-acb1-5863237f99a7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b1cf77dc-e69c-417e-8920-f7bfbce96ffa", "node_type": "1", "metadata": {}, "hash": "6ddce18cde3de647abec59b66051b4490ec15e250f282b57b0c07b06d780978f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "23e96c96-2997-4a45-89b5-9aea4012578f", "node_type": "1", "metadata": {}, "hash": "61e1e087e14f8a87eb56bb6e200b29dd80aae4332e6b0e00950f95e10f836bcd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Imports\nimport software.amazon.awssdk.services.iam.model.GetPolicyRequest;\nimport software.amazon.awssdk.services.iam.model.GetPolicyResponse;\nimport software.amazon.awssdk.regions.Region;\nWork with IAM policies 387\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void getIAMPolicy(IamClient iam, String policyArn) {\ntry {\nGetPolicyRequest request = GetPolicyRequest.builder()\n.policyArn(policyArn).build();\nGetPolicyResponse response = iam.getPolicy(request);\nSystem.out.format(\"Successfully retrieved policy %s\",\nresponse.policy().policyName());\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nAttach a role policy\nYou can attach a policy to an IAM role by calling the IamClient\u2019s attachRolePolicy method,\nproviding it with the role name and policy ARN in an AttachRolePolicyRequest.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;\nimport software.amazon.awssdk.services.iam.model.AttachedPolicy;\nimport software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;\nimport software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;\nimport java.util.List;\nCode\npublic static void attachIAMRolePolicy(IamClient iam, String roleName, String\npolicyArn ) {\nWork with IAM policies 388\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nListAttachedRolePoliciesRequest request =\nListAttachedRolePoliciesRequest.builder()\n.roleName(roleName)\n.build();\nListAttachedRolePoliciesResponse response =\niam.listAttachedRolePolicies(request);\nList attachedPolicies = response.attachedPolicies();\n// Ensure that the policy is not attached to this role\nString polArn = \"\";\nfor (AttachedPolicy policy: attachedPolicies) {\npolArn = policy.policyArn();\nif (polArn.compareTo(policyArn)==0) {\nSystem.out.println(roleName +\n\" policy is already attached to this role.\");\nreturn;\n}\n}\nAttachRolePolicyRequest attachRequest =\nAttachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(policyArn)\n.build();\niam.attachRolePolicy(attachRequest);\nSystem.out.println(\"Successfully attached policy \" + policyArn +\n\" to role \" + roleName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done\");\n}\nSee the complete example on GitHub.\nWork with IAM policies 389\nAWS SDK for Java 2.x Developer Guide for version 2.x\nList attached role policies\nList attached policies on a role by calling the IamClient\u2019s listAttachedRolePolicies method.\nIt takes a ListAttachedRolePoliciesRequest object that contains the role name to list the policies for.\nCall getAttachedPolicies on the returned ListAttachedRolePoliciesResponse object to get the\nlist of attached policies. Results may be truncated; if the ListAttachedRolePoliciesResponse\nobject\u2019s isTruncated method returns true, call the ListAttachedRolePoliciesResponse\nobject\u2019s marker method. Use the marker returned to create a new request and use it to call\nlistAttachedRolePolicies again to get the next batch of results.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;\nimport software.amazon.awssdk.services.iam.model.AttachedPolicy;\nimport software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;\nimport software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;\nimport java.util.List;\nCode\npublic static void attachIAMRolePolicy(IamClient iam, String roleName, String\npolicyArn ) {\ntry {\nListAttachedRolePoliciesRequest request =\nListAttachedRolePoliciesRequest.builder()\n.roleName(roleName)\n.build();\nListAttachedRolePoliciesResponse response =\niam.listAttachedRolePolicies(request);\nList attachedPolicies = response.attachedPolicies();\n// Ensure that the policy is not attached to this role\nString polArn = \"\";\nfor (AttachedPolicy policy: attachedPolicies) {\nWork with IAM policies 390\nAWS SDK for Java 2.x Developer Guide for version 2.x\npolArn = policy.policyArn();\nif (polArn.compareTo(policyArn)==0) {\nSystem.out.println(roleName +\n\" policy is already attached to this role.", "mimetype": "text/plain", "start_char_idx": 652591, "end_char_idx": 657193, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "23e96c96-2997-4a45-89b5-9aea4012578f": {"__data__": {"id_": "23e96c96-2997-4a45-89b5-9aea4012578f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c6346d5-4acb-4b98-acb1-5863237f99a7", "node_type": "1", "metadata": {}, "hash": "cb6bb76c4c98248d532619f39abfff2b3889b265e47cbf8bb05215574a60bb5b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ce4d6666-099e-4d1f-9022-08491108c4d8", "node_type": "1", "metadata": {}, "hash": "74670f7b7aa784f23fe113eb26bc31c79b1a5456518b4e2119ae9512b7c422ca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nreturn;\n}\n}\nAttachRolePolicyRequest attachRequest =\nAttachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(policyArn)\n.build();\niam.attachRolePolicy(attachRequest);\nSystem.out.println(\"Successfully attached policy \" + policyArn +\n\" to role \" + roleName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done\");\n}\nSee the complete example on GitHub.\nDetach a role policy\nTo detach a policy from a role, call the IamClient\u2019s detachRolePolicy method, providing it with\nthe role name and policy ARN in a DetachRolePolicyRequest.\nImports\nimport software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\nWork with IAM policies 391\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void detachPolicy(IamClient iam, String roleName, String policyArn )\n{\ntry {\nDetachRolePolicyRequest request = DetachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(policyArn)\n.build();\niam.detachRolePolicy(request);\nSystem.out.println(\"Successfully detached policy \" + policyArn +\n\" from role \" + roleName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Overview of IAM Policies in the IAM User Guide.\n\u2022 AWS IAM Policy Reference in the IAM User Guide.\n\u2022 CreatePolicy in the IAM API Reference\n\u2022 GetPolicy in the IAM API Reference\n\u2022 AttachRolePolicy in the IAM API Reference\n\u2022 ListAttachedRolePolicies in the IAM API Reference\n\u2022 DetachRolePolicy in the IAM API Reference\nWork with IAM server certificates\nTo enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server\ncertificate. You can use a server certificate provided by AWS Certificate Manager or one that you\nobtained from an external provider.\nWe recommend that you use ACM to provision, manage, and deploy your server certificates. With\nACM you can request a certificate, deploy it to your AWS resources, and let ACM handle certificate\nWork with IAM server certificates 392\nAWS SDK for Java 2.x Developer Guide for version 2.x\nrenewals for you. Certificates provided by ACM are free. For more information about ACM, see the\nAWS Certificate Manager User Guide.\nGet a server certificate\nYou can retrieve a server certificate by calling the IamClient\u2019s getServerCertificate method,\npassing it a GetServerCertificateRequest with the certificate\u2019s name.\nImports\nimport software.amazon.awssdk.services.iam.model.GetServerCertificateRequest;\nimport software.amazon.awssdk.services.iam.model.GetServerCertificateResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void getCertificate(IamClient iam,String certName ) {\ntry {\nGetServerCertificateRequest request = GetServerCertificateRequest.builder()\n.serverCertificateName(certName)\n.build();\nGetServerCertificateResponse response = iam.getServerCertificate(request);\nSystem.out.format(\"Successfully retrieved certificate with body %s\",\nresponse.serverCertificate().certificateBody());\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nList server certificates\nTo list your server certificates, call the IamClient\u2019s listServerCertificates method with a\nListServerCertificatesRequest. It returns a ListServerCertificatesResponse.\nWork with IAM server certificates 393\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCall the returned ListServerCertificateResponse object\u2019s\nserverCertificateMetadataList method to get a list of ServerCertificateMetadata objects\nthat you can use to get information about each certificate.\nResults may be truncated; if the ListServerCertificateResponse object\u2019s isTruncated\nmethod returns true, call the ListServerCertificatesResponse object\u2019s marker\nmethod and use the marker to create a new request. Use the new request to call\nlistServerCertificates again to get the next batch of results.", "mimetype": "text/plain", "start_char_idx": 657193, "end_char_idx": 661459, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ce4d6666-099e-4d1f-9022-08491108c4d8": {"__data__": {"id_": "ce4d6666-099e-4d1f-9022-08491108c4d8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "23e96c96-2997-4a45-89b5-9aea4012578f", "node_type": "1", "metadata": {}, "hash": "61e1e087e14f8a87eb56bb6e200b29dd80aae4332e6b0e00950f95e10f836bcd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "988ab430-82e6-4145-8762-bf3154002d93", "node_type": "1", "metadata": {}, "hash": "6f9c0352d330a9c74c5dcd2c44b2fb980e672307721880db613f1ee825ad628a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "List server certificates\nTo list your server certificates, call the IamClient\u2019s listServerCertificates method with a\nListServerCertificatesRequest. It returns a ListServerCertificatesResponse.\nWork with IAM server certificates 393\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCall the returned ListServerCertificateResponse object\u2019s\nserverCertificateMetadataList method to get a list of ServerCertificateMetadata objects\nthat you can use to get information about each certificate.\nResults may be truncated; if the ListServerCertificateResponse object\u2019s isTruncated\nmethod returns true, call the ListServerCertificatesResponse object\u2019s marker\nmethod and use the marker to create a new request. Use the new request to call\nlistServerCertificates again to get the next batch of results.\nImports\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.ListServerCertificatesRequest;\nimport software.amazon.awssdk.services.iam.model.ListServerCertificatesResponse;\nimport software.amazon.awssdk.services.iam.model.ServerCertificateMetadata;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nCode\npublic static void listCertificates(IamClient iam) {\ntry {\nboolean done = false;\nString newMarker = null;\nwhile(!done) {\nListServerCertificatesResponse response;\nif (newMarker == null) {\nListServerCertificatesRequest request =\nListServerCertificatesRequest.builder().build();\nresponse = iam.listServerCertificates(request);\n} else {\nListServerCertificatesRequest request =\nListServerCertificatesRequest.builder()\n.marker(newMarker).build();\nresponse = iam.listServerCertificates(request);\n}\nfor(ServerCertificateMetadata metadata :\nresponse.serverCertificateMetadataList()) {\nWork with IAM server certificates 394\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.printf(\"Retrieved server certificate %s\",\nmetadata.serverCertificateName());\n}\nif(!response.isTruncated()) {\ndone = true;\n} else {\nnewMarker = response.marker();\n}\n}\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nUpdate a server certificate\nYou can update a server certificate\u2019s name or path by calling the IamClient\u2019s\nupdateServerCertificate method. It takes a UpdateServerCertificateRequest object set with\nthe server certificate\u2019s current name and either a new name or new path to use.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nimport software.amazon.awssdk.services.iam.model.UpdateServerCertificateRequest;\nimport software.amazon.awssdk.services.iam.model.UpdateServerCertificateResponse;\nCode\npublic static void updateCertificate(IamClient iam, String curName, String newName)\n{\ntry {\nUpdateServerCertificateRequest request =\nUpdateServerCertificateRequest.builder()\n.serverCertificateName(curName)\nWork with IAM server certificates 395\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.newServerCertificateName(newName)\n.build();\nUpdateServerCertificateResponse response =\niam.updateServerCertificate(request);\nSystem.out.printf(\"Successfully updated server certificate to name %s\",\nnewName);\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nDelete a server certificate\nTo delete a server certificate, call the IamClient\u2019s deleteServerCertificate method with a\nDeleteServerCertificateRequest containing the certificate\u2019s name.\nImports\nimport software.amazon.awssdk.services.iam.model.DeleteServerCertificateRequest;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.iam.IamClient;\nimport software.amazon.awssdk.services.iam.model.IamException;\nCode\npublic static void deleteCert(IamClient iam,String certName ) {\ntry {\nDeleteServerCertificateRequest request =\nDeleteServerCertificateRequest.builder()\n.serverCertificateName(certName)\n.build();\niam.deleteServerCertificate(request);\nSystem.out.println(\"Successfully deleted server certificate \" +\ncertName);\nWork with IAM server certificates 396\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (IamException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 Working with Server Certificates in the IAM User Guide\n\u2022 GetServerCertificate in the IAM API Reference\n\u2022 ListServerCertificates in the IAM API Reference\n\u2022 UpdateServerCertificate in the IAM API Reference\n\u2022 DeleteServerCertificate in the IAM API Reference\n\u2022 AWS Certificate Manager User Guide\nWork with Kinesis\nThis section provides examples of programming Amazon Kinesis using the AWS SDK for Java 2.x.\nFor more information about Kinesis, see the Amazon Kinesis Developer Guide.\nThe following examples include only the code needed to demonstrate each technique.", "mimetype": "text/plain", "start_char_idx": 660668, "end_char_idx": 665675, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "988ab430-82e6-4145-8762-bf3154002d93": {"__data__": {"id_": "988ab430-82e6-4145-8762-bf3154002d93", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ce4d6666-099e-4d1f-9022-08491108c4d8", "node_type": "1", "metadata": {}, "hash": "74670f7b7aa784f23fe113eb26bc31c79b1a5456518b4e2119ae9512b7c422ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2d75a828-d3f5-4bd8-9f60-613e1fff1497", "node_type": "1", "metadata": {}, "hash": "25eb6c2e98554e804b8cb54f5eb9f014488b1d0b1d5cb2d7e0e65d6f93417c4a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "More information\n\u2022 Working with Server Certificates in the IAM User Guide\n\u2022 GetServerCertificate in the IAM API Reference\n\u2022 ListServerCertificates in the IAM API Reference\n\u2022 UpdateServerCertificate in the IAM API Reference\n\u2022 DeleteServerCertificate in the IAM API Reference\n\u2022 AWS Certificate Manager User Guide\nWork with Kinesis\nThis section provides examples of programming Amazon Kinesis using the AWS SDK for Java 2.x.\nFor more information about Kinesis, see the Amazon Kinesis Developer Guide.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\n\u2022 Subscribe to Amazon Kinesis Data Streams\nSubscribe to Amazon Kinesis Data Streams\nThe following examples show you how to retrieve and process data from Amazon Kinesis Data\nStreams using the subscribeToShard method. Kinesis Data Streams now employs the enhanced\nfanout feature and a low-latency HTTP/2 data retrieval API, making it easier for developers to run\nmultiple low-latency, high-performance applications on the same Kinesis Data Stream.\nKinesis 397\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSet up\nFirst, create an asynchronous Kinesis client and a SubscribeToShardRequest object. These objects\nare used in each of the following examples to subscribe to Kinesis events.\nImports\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport org.reactivestreams.Subscriber;\nimport org.reactivestreams.Subscription;\nimport software.amazon.awssdk.core.async.SdkPublisher;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.kinesis.KinesisAsyncClient;\nimport software.amazon.awssdk.services.kinesis.model.ShardIteratorType;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;\nCode\nRegion region = Region.US_EAST_1;\nKinesisAsyncClient client = KinesisAsyncClient.builder()\n.region(region)\n.build();\nSubscribeToShardRequest request = SubscribeToShardRequest.builder()\n.consumerARN(CONSUMER_ARN)\n.shardId(\"arn:aws:kinesis:us-east-1:111122223333:stream/\nStockTradeStream\")\n.startingPosition(s -> s.type(ShardIteratorType.LATEST)).build();\nUse the builder interface\nYou can use the builder method to simplify the creation of the\nSubscribeToShardResponseHandler.\nUsing the builder, you can set each lifecycle callback with a method call instead of implementing\nthe full interface.\nSubscribe to Amazon Kinesis Data Streams 398\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\nprivate static CompletableFuture responseHandlerBuilder(KinesisAsyncClient\nclient, SubscribeToShardRequest request) {\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.onComplete(() -> System.out.println(\"All records stream\nsuccessfully\"))\n// Must supply some type of subscriber\n.subscriber(e -> System.out.println(\"Received event - \" + e))\n.build();\nreturn client.subscribeToShard(request, responseHandler);\n}\nFor more control of the publisher, you can use the publisherTransformer method to customize\nthe publisher.\nCode\nprivate static CompletableFuture\nresponseHandlerBuilderPublisherTransformer(KinesisAsyncClient client,\nSubscribeToShardRequest request) {\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.publisherTransformer(p -> p.filter(e -> e instanceof\nSubscribeToShardEvent).limit(100))\n.subscriber(e -> System.out.println(\"Received event - \" + e))\n.build();\nreturn client.subscribeToShard(request, responseHandler);\n}\nSee the complete example on GitHub.\nUse a custom response handler\nFor full control of the subscriber and publisher, implement the\nSubscribeToShardResponseHandler interface.\nSubscribe to Amazon Kinesis Data Streams 399\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn this example, you implement the onEventStream method, which allows you full access to the\npublisher. This demonstrates how to transform the publisher to event records for printing by the\nsubscriber.", "mimetype": "text/plain", "start_char_idx": 665095, "end_char_idx": 669733, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2d75a828-d3f5-4bd8-9f60-613e1fff1497": {"__data__": {"id_": "2d75a828-d3f5-4bd8-9f60-613e1fff1497", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "988ab430-82e6-4145-8762-bf3154002d93", "node_type": "1", "metadata": {}, "hash": "6f9c0352d330a9c74c5dcd2c44b2fb980e672307721880db613f1ee825ad628a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c65207fe-5fdd-4a35-a87b-88b2aeca62ca", "node_type": "1", "metadata": {}, "hash": "39e706bf449efab39cb396511906cb7cbfe550578054d684b7274938c3c0708b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use a custom response handler\nFor full control of the subscriber and publisher, implement the\nSubscribeToShardResponseHandler interface.\nSubscribe to Amazon Kinesis Data Streams 399\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn this example, you implement the onEventStream method, which allows you full access to the\npublisher. This demonstrates how to transform the publisher to event records for printing by the\nsubscriber.\nCode\nprivate static CompletableFuture\nresponseHandlerBuilderClassic(KinesisAsyncClient client, SubscribeToShardRequest\nrequest) {\nSubscribeToShardResponseHandler responseHandler = new\nSubscribeToShardResponseHandler() {\n@Override\npublic void responseReceived(SubscribeToShardResponse response) {\nSystem.out.println(\"Receieved initial response\");\n}\n@Override\npublic void onEventStream(SdkPublisher\npublisher) {\npublisher\n// Filter to only SubscribeToShardEvents\n.filter(SubscribeToShardEvent.class)\n// Flat map into a publisher of just records\n.flatMapIterable(SubscribeToShardEvent::records)\n// Limit to 1000 total records\n.limit(1000)\n// Batch records into lists of 25\n.buffer(25)\n// Print out each record batch\n.subscribe(batch -> System.out.println(\"Record Batch - \" +\nbatch));\n}\n@Override\npublic void complete() {\nSystem.out.println(\"All records stream successfully\");\n}\n@Override\npublic void exceptionOccurred(Throwable throwable) {\nSystem.err.println(\"Error during stream - \" + throwable.getMessage());\n}\nSubscribe to Amazon Kinesis Data Streams 400\nAWS SDK for Java 2.x Developer Guide for version 2.x\n};\nreturn client.subscribeToShard(request, responseHandler);\n}\nSee the complete example on GitHub.\nUse the visitor interface\nYou can use a Visitor object to subscribe to specific events you\u2019re interested in watching.\nCode\nprivate static CompletableFuture\nresponseHandlerBuilderVisitorBuilder(KinesisAsyncClient client,\nSubscribeToShardRequest request) {\nSubscribeToShardResponseHandler.Visitor visitor =\nSubscribeToShardResponseHandler.Visitor\n.builder()\n.onSubscribeToShardEvent(e -> System.out.println(\"Received subscribe to\nshard event \" + e))\n.build();\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.subscriber(visitor)\n.build();\nreturn client.subscribeToShard(request, responseHandler);\n}\nSee the complete example on GitHub.\nUse a custom subscriber\nYou can also implement your own custom subscriber to subscribe to the stream.\nThis code snippet shows an example subscriber.\nCode\nprivate static class MySubscriber implements\nSubscriber {\nSubscribe to Amazon Kinesis Data Streams 401\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate Subscription subscription;\nprivate AtomicInteger eventCount = new AtomicInteger(0);\n@Override\npublic void onSubscribe(Subscription subscription) {\nthis.subscription = subscription;\nthis.subscription.request(1);\n}\n@Override\npublic void onNext(SubscribeToShardEventStream shardSubscriptionEventStream) {\nSystem.out.println(\"Received event \" + shardSubscriptionEventStream);\nif (eventCount.incrementAndGet() >= 100) {\n// You can cancel the subscription at any time if you wish to stop\nreceiving events.\nsubscription.cancel();\n}\nsubscription.request(1);\n}\n@Override\npublic void onError(Throwable throwable) {\nSystem.err.println(\"Error occurred while stream - \" +\nthrowable.getMessage());\n}\n@Override\npublic void onComplete() {\nSystem.out.println(\"Finished streaming all events\");\n}\n}\nYou can pass the custom subscriber to the subscribe method as shown in the following code\nsnippet.\nCode\nprivate static CompletableFuture\nresponseHandlerBuilderSubscriber(KinesisAsyncClient client, SubscribeToShardRequest\nrequest) {\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\nSubscribe to Amazon Kinesis Data Streams 402\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.subscriber(MySubscriber::new)\n.build();\nreturn client.subscribeToShard(request, responseHandler);\n}\nSee the complete example on GitHub.\nWrite data records into a Kinesis data stream\nYou can use the KinesisClient object to write data records into a Kinesis data stream by using the\nputRecords method. To successfully invoke this method, create a PutRecordsRequest object. You\npass the name of the data stream to the streamName method. Also you must pass the data by\nusing the putRecords method (as shown in the following code example).", "mimetype": "text/plain", "start_char_idx": 669297, "end_char_idx": 673906, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c65207fe-5fdd-4a35-a87b-88b2aeca62ca": {"__data__": {"id_": "c65207fe-5fdd-4a35-a87b-88b2aeca62ca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2d75a828-d3f5-4bd8-9f60-613e1fff1497", "node_type": "1", "metadata": {}, "hash": "25eb6c2e98554e804b8cb54f5eb9f014488b1d0b1d5cb2d7e0e65d6f93417c4a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "62a2eaff-45f1-4665-975f-17a47d36f9c5", "node_type": "1", "metadata": {}, "hash": "f8c1c09f16d3e17db57923977e99fb6f39168383ba56df116057af350611fdfd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Write data records into a Kinesis data stream\nYou can use the KinesisClient object to write data records into a Kinesis data stream by using the\nputRecords method. To successfully invoke this method, create a PutRecordsRequest object. You\npass the name of the data stream to the streamName method. Also you must pass the data by\nusing the putRecords method (as shown in the following code example).\nImports\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.kinesis.KinesisClient;\nimport software.amazon.awssdk.services.kinesis.model.PutRecordRequest;\nimport software.amazon.awssdk.services.kinesis.model.KinesisException;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse;\nIn the following Java code example, notice that StockTrade object is used as the data to write\nto the Kinesis data stream. Before running this example, ensure that you have created the data\nstream.\nCode\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.kinesis.KinesisClient;\nimport software.amazon.awssdk.services.kinesis.model.PutRecordRequest;\nimport software.amazon.awssdk.services.kinesis.model.KinesisException;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse;\n/**\n* Before running this Java V2 code example, set up your development\nSubscribe to Amazon Kinesis Data Streams 403\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class StockTradesWriter {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nstreamName - The Amazon Kinesis data stream to which records are\nwritten (for example, StockTradeStream)\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString streamName = args[0];\nRegion region = Region.US_EAST_1;\nKinesisClient kinesisClient = KinesisClient.builder()\n.region(region)\n.build();\n// Ensure that the Kinesis Stream is valid.\nvalidateStream(kinesisClient, streamName);\nsetStockData(kinesisClient, streamName);\nkinesisClient.close();\n}\npublic static void setStockData(KinesisClient kinesisClient, String streamName) {\ntry {\n// Repeatedly send stock trades with a 100 milliseconds wait in between.\nStockTradeGenerator stockTradeGenerator = new StockTradeGenerator();\n// Put in 50 Records for this example.\nint index = 50;\nfor (int x = 0; x < index; x++) {\nStockTrade trade = stockTradeGenerator.getRandomTrade();\nSubscribe to Amazon Kinesis Data Streams 404\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsendStockTrade(trade, kinesisClient, streamName);\nThread.sleep(100);\n}\n} catch (KinesisException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done\");\n}\nprivate static void sendStockTrade(StockTrade trade, KinesisClient kinesisClient,\nString streamName) {\nbyte[] bytes = trade.toJsonAsBytes();\n// The bytes could be null if there is an issue with the JSON serialization by\n// the Jackson JSON library.\nif (bytes == null) {\nSystem.out.println(\"Could not get JSON bytes for stock trade\");\nreturn;\n}\nSystem.out.println(\"Putting trade: \" + trade);\nPutRecordRequest request = PutRecordRequest.builder()\n.partitionKey(trade.getTickerSymbol()) // We use the ticker symbol as\nthe partition key, explained in\n// the Supplemental Information\nsection below.\n.streamName(streamName)\n.data(SdkBytes.fromByteArray(bytes))\n.build();\ntry {\nkinesisClient.putRecord(request);\n} catch (KinesisException e) {\nSystem.err.println(e.getMessage());\n}\n}\nprivate static void validateStream(KinesisClient kinesisClient, String streamName)\n{\ntry {\nDescribeStreamRequest describeStreamRequest =\nDescribeStreamRequest.builder()\nSubscribe to Amazon Kinesis Data Streams 405\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.streamName(streamName)\n.build();\nDescribeStreamResponse describeStreamResponse =\nkinesisClient.describeStream(describeStreamRequest);\nif (!\ndescribeStreamResponse.streamDescription().streamStatus().toString().equals(\"ACTIVE\"))\n{\nSystem.err.println(\"Stream \" + streamName + \" is not active. Please\nwait a few moments and try again.", "mimetype": "text/plain", "start_char_idx": 673508, "end_char_idx": 678038, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "62a2eaff-45f1-4665-975f-17a47d36f9c5": {"__data__": {"id_": "62a2eaff-45f1-4665-975f-17a47d36f9c5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c65207fe-5fdd-4a35-a87b-88b2aeca62ca", "node_type": "1", "metadata": {}, "hash": "39e706bf449efab39cb396511906cb7cbfe550578054d684b7274938c3c0708b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c98f4122-59d8-44c1-9323-a9e97dd9a1a3", "node_type": "1", "metadata": {}, "hash": "23b81c7a6089bc48e9b0c5fd2d09eff105e1a6a6f2b44a5b7a733b62d11e36ae", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".streamName(streamName)\n.data(SdkBytes.fromByteArray(bytes))\n.build();\ntry {\nkinesisClient.putRecord(request);\n} catch (KinesisException e) {\nSystem.err.println(e.getMessage());\n}\n}\nprivate static void validateStream(KinesisClient kinesisClient, String streamName)\n{\ntry {\nDescribeStreamRequest describeStreamRequest =\nDescribeStreamRequest.builder()\nSubscribe to Amazon Kinesis Data Streams 405\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.streamName(streamName)\n.build();\nDescribeStreamResponse describeStreamResponse =\nkinesisClient.describeStream(describeStreamRequest);\nif (!\ndescribeStreamResponse.streamDescription().streamStatus().toString().equals(\"ACTIVE\"))\n{\nSystem.err.println(\"Stream \" + streamName + \" is not active. Please\nwait a few moments and try again.\");\nSystem.exit(1);\n}\n} catch (KinesisException e) {\nSystem.err.println(\"Error found while describing the stream \" +\nstreamName);\nSystem.err.println(e);\nSystem.exit(1);\n}\n}\n}\nSee the complete example on GitHub.\nUse a third-party library\nYou can use other third-party libraries instead of implementing a custom subscriber. This example\ndemonstrates using the RxJava implementation, but you can use any library that implements the\nReactive Streams interfaces. See the RxJava wiki page on Github for more information on that\nlibrary.\nTo use the library, add it as a dependency. If you\u2019re using Maven, the example shows the POM\nsnippet to use.\nPOM Entry\n\nio.reactivex.rxjava2\nrxjava\n2.2.21\n\nSubscribe to Amazon Kinesis Data Streams 406\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport java.net.URI;\nimport java.util.concurrent.CompletableFuture;\nimport io.reactivex.Flowable;\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.core.async.SdkPublisher;\nimport software.amazon.awssdk.http.Protocol;\nimport software.amazon.awssdk.http.SdkHttpConfigurationOption;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.kinesis.KinesisAsyncClient;\nimport software.amazon.awssdk.services.kinesis.model.ShardIteratorType;\nimport software.amazon.awssdk.services.kinesis.model.StartingPosition;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;\nimport software.amazon.awssdk.utils.AttributeMap;\nThis example uses RxJava in the onEventStream lifecycle method. This gives you full access to the\npublisher, which can be used to create an Rx Flowable.\nCode\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.onEventStream(p -> Flowable.fromPublisher(p)\n.ofType(SubscribeToShardEvent.class)\n.flatMapIterable(SubscribeToShardEvent::records)\n.limit(1000)\n.buffer(25)\n.subscribe(e -> System.out.println(\"Record\nbatch = \" + e)))\n.build();\nYou can also use the publisherTransformer method with the Flowable publisher. You must\nadapt the Flowable publisher to an SdkPublisher, as shown in the following example.\nSubscribe to Amazon Kinesis Data Streams 407\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\nSubscribeToShardResponseHandler responseHandler =\nSubscribeToShardResponseHandler\n.builder()\n.onError(t -> System.err.println(\"Error during stream - \" +\nt.getMessage()))\n.publisherTransformer(p ->\nSdkPublisher.adapt(Flowable.fromPublisher(p).limit(100)))\n.build();\nSee the complete example on GitHub.\nMore information\n\u2022 SubscribeToShardEvent in the Amazon Kinesis API Reference\n\u2022 SubscribeToShard in the Amazon Kinesis API Reference\nInvoke, list, and delete AWS Lambda functions\nThis section provides examples of programming with the Lambda service client by using the AWS\nSDK for Java 2.x.\nTopics\n\u2022 Invoke a Lambda function\n\u2022 List Lambda functions\n\u2022 Delete a Lambda function\nInvoke a Lambda function\nYou can invoke a Lambda function by creating a LambdaClient object and invoking its invoke\nmethod. Create an InvokeRequest object to specify additional information such as the\nfunction name and the payload to pass to the Lambda function. Function names appear as\narn:aws:lambda:us-east-1:123456789012:function:HelloFunction. You can retrieve the value by\nlooking at the function in the AWS Management Console.\nTo pass payload data to a function, create a SdkBytes object that contains information.", "mimetype": "text/plain", "start_char_idx": 677258, "end_char_idx": 681898, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c98f4122-59d8-44c1-9323-a9e97dd9a1a3": {"__data__": {"id_": "c98f4122-59d8-44c1-9323-a9e97dd9a1a3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "62a2eaff-45f1-4665-975f-17a47d36f9c5", "node_type": "1", "metadata": {}, "hash": "f8c1c09f16d3e17db57923977e99fb6f39168383ba56df116057af350611fdfd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "305aedb7-b2b7-413f-ae2a-99e49fbb2b07", "node_type": "1", "metadata": {}, "hash": "5a783b4a385a83b310496d23dd5d271e67720c390dac58d287e008c1059c18e2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "More information\n\u2022 SubscribeToShardEvent in the Amazon Kinesis API Reference\n\u2022 SubscribeToShard in the Amazon Kinesis API Reference\nInvoke, list, and delete AWS Lambda functions\nThis section provides examples of programming with the Lambda service client by using the AWS\nSDK for Java 2.x.\nTopics\n\u2022 Invoke a Lambda function\n\u2022 List Lambda functions\n\u2022 Delete a Lambda function\nInvoke a Lambda function\nYou can invoke a Lambda function by creating a LambdaClient object and invoking its invoke\nmethod. Create an InvokeRequest object to specify additional information such as the\nfunction name and the payload to pass to the Lambda function. Function names appear as\narn:aws:lambda:us-east-1:123456789012:function:HelloFunction. You can retrieve the value by\nlooking at the function in the AWS Management Console.\nTo pass payload data to a function, create a SdkBytes object that contains information. For\nexample, in the following code example, notice the JSON data passed to the Lambda function.\nLambda 408\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.services.lambda.LambdaClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.lambda.model.InvokeRequest;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.services.lambda.model.InvokeResponse;\nimport software.amazon.awssdk.services.lambda.model.LambdaException;\nCode\nThe following code example demonstrates how to invoke a Lambda function.\npublic static void invokeFunction(LambdaClient awsLambda, String functionName) {\nInvokeResponse res = null ;\ntry {\n//Need a SdkBytes instance for the payload\nString json = \"{\\\"Hello \\\":\\\"Paris\\\"}\";\nSdkBytes payload = SdkBytes.fromUtf8String(json) ;\n//Setup an InvokeRequest\nInvokeRequest request = InvokeRequest.builder()\n.functionName(functionName)\n.payload(payload)\n.build();\nres = awsLambda.invoke(request);\nString value = res.payload().asUtf8String() ;\nSystem.out.println(value);\n} catch(LambdaException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nList Lambda functions\nBuild a LambdaClient object and invoke its listFunctions method. This method returns a\nListFunctionsResponse object. You can invoke this object\u2019s functions method to return a\nList Lambda functions 409\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlist of FunctionConfiguration objects. You can iterate through the list to retrieve information\nabout the functions. For example, the following Java code example shows how to get each function\nname.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.lambda.LambdaClient;\nimport software.amazon.awssdk.services.lambda.model.LambdaException;\nimport software.amazon.awssdk.services.lambda.model.ListFunctionsResponse;\nimport software.amazon.awssdk.services.lambda.model.FunctionConfiguration;\nimport java.util.List;\nCode\nThe following Java code example demonstrates how to retrieve a list of function names.\npublic static void listFunctions(LambdaClient awsLambda) {\ntry {\nListFunctionsResponse functionResult = awsLambda.listFunctions();\nList list = functionResult.functions();\nfor (FunctionConfiguration config: list) {\nSystem.out.println(\"The function name is \"+config.functionName());\n}\n} catch(LambdaException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nDelete a Lambda function\nBuild a LambdaClient object and invoke its deleteFunction method. Create a\nDeleteFunctionRequest object and pass it to the deleteFunction method. This object\ncontains information such as the name of the function to delete. Function names appear as\narn:aws:lambda:us-east-1:123456789012:function:HelloFunction. You can retrieve the value by\nlooking at the function in the AWS Management Console.\nDelete a Lambda function 410\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.services.lambda.LambdaClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;\nimport software.amazon.awssdk.services.lambda.model.LambdaException;\nCode\nThe following Java code demonstrates how to delete a Lambda function.\npublic static void deleteLambdaFunction(LambdaClient awsLambda, String\nfunctionName ) {\ntry {\nDeleteFunctionRequest request = DeleteFunctionRequest.builder()\n.functionName(functionName)\n.build();\nawsLambda.deleteFunction(request);\nSystem.out.println(\"The \"+functionName +\" function was deleted\");\n} catch(LambdaException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nWork with Amazon S3\nThis section provides background information for working with Amazon S3 by using the AWS SDK\nfor Java 2.x.", "mimetype": "text/plain", "start_char_idx": 681001, "end_char_idx": 685834, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "305aedb7-b2b7-413f-ae2a-99e49fbb2b07": {"__data__": {"id_": "305aedb7-b2b7-413f-ae2a-99e49fbb2b07", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c98f4122-59d8-44c1-9323-a9e97dd9a1a3", "node_type": "1", "metadata": {}, "hash": "23b81c7a6089bc48e9b0c5fd2d09eff105e1a6a6f2b44a5b7a733b62d11e36ae", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "76ca33e3-2af5-4f40-846f-1facfdbb64b1", "node_type": "1", "metadata": {}, "hash": "1b8f649e86e18677f420232f2ee9f2de85754524092a2d1cd4cec2104e9156e9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Delete a Lambda function 410\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.services.lambda.LambdaClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;\nimport software.amazon.awssdk.services.lambda.model.LambdaException;\nCode\nThe following Java code demonstrates how to delete a Lambda function.\npublic static void deleteLambdaFunction(LambdaClient awsLambda, String\nfunctionName ) {\ntry {\nDeleteFunctionRequest request = DeleteFunctionRequest.builder()\n.functionName(functionName)\n.build();\nawsLambda.deleteFunction(request);\nSystem.out.println(\"The \"+functionName +\" function was deleted\");\n} catch(LambdaException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nWork with Amazon S3\nThis section provides background information for working with Amazon S3 by using the AWS SDK\nfor Java 2.x. This section compliments the Amazon S3 Java v2 examples presented in the Code\nexamples section of this guide.\nS3 clients in the AWS SDK for Java 2.x\nThe AWS SDK for Java 2.x provides different types of S3 clients. The following table shows the\ndifferences and can help you decide what is best for your use cases.\nAmazon S3 411\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDifferent flavors of Amazon S3 clients\nS3 Client Short description When to use Limitation/drawback\nAWS CRT-based S3 \u2022 Provides the same \u2022 Your applicati \u2022 Supports fewer\nclient asynchronous on transfers configuration\nAPI operations large objects (> settings than the\nInterface: S3AsyncCl\nas the Java-base 8MB) and you Java-based S3\nient\nd S3 async client want maximized clients.\nbut with greater performance.\nBuilder: S3CrtAsyn \u2022 Requires an\nperformance.\ncClientBuilder \u2022 You want to upload additional\n\u2022 Requires the aws- objects with dependency.\ncrt dependency. unknown content\nlength.\n\u2022 Supports\nautomatic parallel \u2022 You want enhanced\ntransfers (multipar connection\nt). pooling and DNS\nload balancing,\nwhich improves\nSee the section called\nthroughput and\n\u201cUse a performant S3\nperformance.\nclient\u201d.\n\u2022 You want improved\ntransfer reliabili\nty in the event of\na network failure.\nIndividual failed\nparts are retried\nwithout restarting\nthe transfer from\nthe beginning.\nJava-based S3 async \u2022 Provides an \u2022 Your application Less performant than\nclient with multipart asynchronous API. transfers large the AWS CRT-based\nenabled objects and you S3 client.\n\u2022 Supports\nwant improved\nautomatic parallel\nInterface: S3AsyncCl\nperformance.\ntransfers (multipar\nient\nt) when you enable\nS3 clients in the SDK 412\nAWS SDK for Java 2.x Developer Guide for version 2.x\nS3 Client Short description When to use Limitation/drawback\nBuilder: S3AsyncCl multipart at \u2022 you want to\nientBuilder creation time. upload object with\nunknown content\nlength.\nSee the section called\n\u201cConfigure parallel \u2022 You want improved\ntransfer support\u201d. transfer reliabili\nty in the event of\na network failure.\nIndividual failed\nparts are retried\nwithout restarting\nthe transfer from\nthe beginning.\n\u2022 You need configura\ntion options that\nare not available\nwith the AWS CRT-\nbased S3 client.\nJava-based S3 \u2022 Provides an \u2022 You are transferr No performance\nasync client without asynchronous API. ing objects that are optimization.\nmultipart enabled less than 8MB.\n\u2022 You want an\nInterface: S3AsyncCl\nasynchronous API.\nient\nBuilder: S3AsyncCl\nientBuilder\nJava-based S3 sync \u2022 Provides a \u2022 You are transferr No performance\nclient synchronous API. ing objects that are optimization.\nless than 8MB.\nInterface: S3Client\n\u2022 You want a\nBuilder: S3ClientB synchronous API.\nuilder\nS3 clients in the SDK 413\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nFrom version 2.18.x and onward, the AWS SDK for Java 2.x uses virtual hosted-style\naddressing when including an endpoint override. This applies as long as the bucket name is\na valid DNS label.\nCall the forcePathStyle method with true in your client builder to force the client to\nuse path-style addressing for buckets.\nThe following example shows a service client configured with an endpoint override and\nusing path-style addressing.", "mimetype": "text/plain", "start_char_idx": 684875, "end_char_idx": 689052, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "76ca33e3-2af5-4f40-846f-1facfdbb64b1": {"__data__": {"id_": "76ca33e3-2af5-4f40-846f-1facfdbb64b1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "305aedb7-b2b7-413f-ae2a-99e49fbb2b07", "node_type": "1", "metadata": {}, "hash": "5a783b4a385a83b310496d23dd5d271e67720c390dac58d287e008c1059c18e2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7dcc506a-b552-4a21-86bd-1fca06baabba", "node_type": "1", "metadata": {}, "hash": "7ce0b1f172dbbd4cf94b985a5b216a1514e00cb2c5152f0653f5033b562cd760", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 You want an\nInterface: S3AsyncCl\nasynchronous API.\nient\nBuilder: S3AsyncCl\nientBuilder\nJava-based S3 sync \u2022 Provides a \u2022 You are transferr No performance\nclient synchronous API. ing objects that are optimization.\nless than 8MB.\nInterface: S3Client\n\u2022 You want a\nBuilder: S3ClientB synchronous API.\nuilder\nS3 clients in the SDK 413\nAWS SDK for Java 2.x Developer Guide for version 2.x\nNote\nFrom version 2.18.x and onward, the AWS SDK for Java 2.x uses virtual hosted-style\naddressing when including an endpoint override. This applies as long as the bucket name is\na valid DNS label.\nCall the forcePathStyle method with true in your client builder to force the client to\nuse path-style addressing for buckets.\nThe following example shows a service client configured with an endpoint override and\nusing path-style addressing.\nS3Client client = S3Client.builder()\n.region(Region.US_WEST_2)\n.endpointOverride(URI.create(\"https://s3.us-\nwest-2.amazonaws.com\"))\n.forcePathStyle(true)\n.build();\nTopics\n\u2022 Use access points or Multi-Region Access Points\n\u2022 Work with Amazon S3 pre-signed URLs\n\u2022 Cross-Region access for Amazon S3\n\u2022 Amazon S3 checksums with AWS SDK for Java\n\u2022 Use a performant S3 client: AWS CRT-based S3 client\n\u2022 Configure the Java-based S3 async client to use parallel transfers\n\u2022 Transfer files and directories with the Amazon S3 Transfer Manager\n\u2022 Work with S3 Event Notifications\nUse access points or Multi-Region Access Points\nAfter Amazon S3 access points or Multi-Region Access Points are set up, you can call object\nmethods, such as putObject and getObject and provide the access point identifier instead of a\nbucket name.\nUse access points or Multi-Region Access Points 414\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFor example, if an access point ARN identifier is arn:aws:s3:us-\nwest-2:123456789012:accesspoint/test, you can use the following snippet to call the\nputObject method.\nPath path = Paths.get(URI.create(\"file:///temp/file.txt\"));\ns3Client.putObject(builder -> builder\n.key(\"myKey\")\n.bucket(\"arn:aws:s3:us-west-2:123456789012:accesspoint/test\")\n, path);\nIn place of the ARN string, you can also use the bucket-style alias of the access point for the\nbucket parameter.\nTo use Multi-Region Access Point, replace the bucket parameter with the Multi-Region Access\nPoint ARN that has the following format.\narn:aws:s3::account-id:accesspoint/MultiRegionAccessPoint_alias\nAdd the following Maven dependency to work with Multi-Region Access Points using the SDK for\nJava. Search maven central for the latest version.\n\nsoftware.amazon.awssdk\nauth-crt\nVERSION\n\nWork with Amazon S3 pre-signed URLs\nPre-signed URLs provide temporary access to private S3 objects without requiring users to have\nAWS credentials or permissions.\nFor example, assume Alice has access to an S3 object, and she wants to temporarily share access to\nthat object with Bob. Alice can generate a pre-signed GET request to share with Bob so that he can\ndownload the object without requiring access to Alice\u2019s credentials. You can generate pre-signed\nURLs for HTTP GET and for HTTP PUT requests.\nGenerate a pre-signed URL for an object, then download it (GET request)\nThe following example consists of two parts.\nPre-signed URLs 415\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Part 1: Alice generates the pre-signed URL for an object.\n\u2022 Part 2: Bob downloads the object by using the pre-signed URL.\nPart 1: Generate the URL\nAlice already has an object in an S3 bucket. She uses the following code to generate a URL string\nthat Bob can use in a subsequent GET request.", "mimetype": "text/plain", "start_char_idx": 688229, "end_char_idx": 691891, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7dcc506a-b552-4a21-86bd-1fca06baabba": {"__data__": {"id_": "7dcc506a-b552-4a21-86bd-1fca06baabba", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "76ca33e3-2af5-4f40-846f-1facfdbb64b1", "node_type": "1", "metadata": {}, "hash": "1b8f649e86e18677f420232f2ee9f2de85754524092a2d1cd4cec2104e9156e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aef1e9a9-128a-4d21-aacc-a306439ea1b7", "node_type": "1", "metadata": {}, "hash": "28984dad5736fc22f405b081662338e6e1b7e0e9d687f58cbd38e7e1e5b77360", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "For example, assume Alice has access to an S3 object, and she wants to temporarily share access to\nthat object with Bob. Alice can generate a pre-signed GET request to share with Bob so that he can\ndownload the object without requiring access to Alice\u2019s credentials. You can generate pre-signed\nURLs for HTTP GET and for HTTP PUT requests.\nGenerate a pre-signed URL for an object, then download it (GET request)\nThe following example consists of two parts.\nPre-signed URLs 415\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Part 1: Alice generates the pre-signed URL for an object.\n\u2022 Part 2: Bob downloads the object by using the pre-signed URL.\nPart 1: Generate the URL\nAlice already has an object in an S3 bucket. She uses the following code to generate a URL string\nthat Bob can use in a subsequent GET request.\nImports\nimport com.example.s3.util.PresignUrlUtils;\nimport org.slf4j.Logger;\nimport software.amazon.awssdk.http.HttpExecuteRequest;\nimport software.amazon.awssdk.http.HttpExecuteResponse;\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.SdkHttpMethod;\nimport software.amazon.awssdk.http.SdkHttpRequest;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport software.amazon.awssdk.services.s3.model.GetObjectRequest;\nimport software.amazon.awssdk.services.s3.model.S3Exception;\nimport software.amazon.awssdk.services.s3.presigner.S3Presigner;\nimport software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;\nimport software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;\nimport software.amazon.awssdk.utils.IoUtils;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.file.Paths;\nimport java.time.Duration;\nimport java.util.UUID;\n/* Create a pre-signed URL to download an object in a subsequent GET request. */\nPre-signed URLs 416\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String createPresignedGetUrl(String bucketName, String keyName) {\ntry (S3Presigner presigner = S3Presigner.create()) {\nGetObjectRequest objectRequest = GetObjectRequest.builder()\n.bucket(bucketName)\n.key(keyName)\n.build();\nGetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()\n.signatureDuration(Duration.ofMinutes(10)) // The URL will expire\nin 10 minutes.\n.getObjectRequest(objectRequest)\n.build();\nPresignedGetObjectRequest presignedRequest =\npresigner.presignGetObject(presignRequest);\nlogger.info(\"Presigned URL: [{}]\", presignedRequest.url().toString());\nlogger.info(\"HTTP method: [{}]\", presignedRequest.httpRequest().method());\nreturn presignedRequest.url().toExternalForm();\n}\n}\nPart 2: Download the object\nBob uses one of the following three code options to download the object. Alternatively, he could\nuse a browser to perform the GET request.\nUse JDK HttpURLConnection (since v1.1)\n/* Use the JDK HttpURLConnection (since v1.1) class to do the download. */\npublic byte[] useHttpUrlConnectionToGet(String presignedUrlString) {\nByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //\nCapture the response body to a byte array.\ntry {\nURL presignedUrl = new URL(presignedUrlString);\nHttpURLConnection connection = (HttpURLConnection)\npresignedUrl.openConnection();\nconnection.setRequestMethod(\"GET\");\n// Download the result of executing the request.\ntry (InputStream content = connection.getInputStream()) {\nIoUtils.copy(content, byteArrayOutputStream);\nPre-signed URLs 417\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nlogger.info(\"HTTP response code is \" + connection.getResponseCode());\n} catch (S3Exception | IOException e) {\nlogger.error(e.getMessage(), e);\n}\nreturn byteArrayOutputStream.toByteArray();\n}\nUse JDK HttpClient (since v11)\n/* Use the JDK HttpClient (since v11) class to do the download. */\npublic byte[] useHttpClientToGet(String presignedUrlString) {\nByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //\nCapture the response body to a byte array.", "mimetype": "text/plain", "start_char_idx": 691069, "end_char_idx": 695347, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "aef1e9a9-128a-4d21-aacc-a306439ea1b7": {"__data__": {"id_": "aef1e9a9-128a-4d21-aacc-a306439ea1b7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7dcc506a-b552-4a21-86bd-1fca06baabba", "node_type": "1", "metadata": {}, "hash": "7ce0b1f172dbbd4cf94b985a5b216a1514e00cb2c5152f0653f5033b562cd760", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9ecdfac6-de60-4bb4-a019-99016c52823c", "node_type": "1", "metadata": {}, "hash": "87e849ccb37f4382998181be18fbdb1546ab69fa4187c5f89869116d29279a38", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "try {\nURL presignedUrl = new URL(presignedUrlString);\nHttpURLConnection connection = (HttpURLConnection)\npresignedUrl.openConnection();\nconnection.setRequestMethod(\"GET\");\n// Download the result of executing the request.\ntry (InputStream content = connection.getInputStream()) {\nIoUtils.copy(content, byteArrayOutputStream);\nPre-signed URLs 417\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nlogger.info(\"HTTP response code is \" + connection.getResponseCode());\n} catch (S3Exception | IOException e) {\nlogger.error(e.getMessage(), e);\n}\nreturn byteArrayOutputStream.toByteArray();\n}\nUse JDK HttpClient (since v11)\n/* Use the JDK HttpClient (since v11) class to do the download. */\npublic byte[] useHttpClientToGet(String presignedUrlString) {\nByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //\nCapture the response body to a byte array.\nHttpRequest.Builder requestBuilder = HttpRequest.newBuilder();\nHttpClient httpClient = HttpClient.newHttpClient();\ntry {\nURL presignedUrl = new URL(presignedUrlString);\nHttpResponse response = httpClient.send(requestBuilder\n.uri(presignedUrl.toURI())\n.GET()\n.build(),\nHttpResponse.BodyHandlers.ofInputStream());\nIoUtils.copy(response.body(), byteArrayOutputStream);\nlogger.info(\"HTTP response code is \" + response.statusCode());\n} catch (URISyntaxException | InterruptedException | IOException e) {\nlogger.error(e.getMessage(), e);\n}\nreturn byteArrayOutputStream.toByteArray();\n}\nUse SdkHttpClient from the SDK for Java\n/* Use the AWS SDK for Java SdkHttpClient class to do the download. */\npublic byte[] useSdkHttpClientToPut(String presignedUrlString) {\nByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //\nCapture the response body to a byte array.\nPre-signed URLs 418\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nURL presignedUrl = new URL(presignedUrlString);\nSdkHttpRequest request = SdkHttpRequest.builder()\n.method(SdkHttpMethod.GET)\n.uri(presignedUrl.toURI())\n.build();\nHttpExecuteRequest executeRequest = HttpExecuteRequest.builder()\n.request(request)\n.build();\ntry (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) {\nHttpExecuteResponse response =\nsdkHttpClient.prepareRequest(executeRequest).call();\nresponse.responseBody().ifPresentOrElse(\nabortableInputStream -> {\ntry {\nIoUtils.copy(abortableInputStream,\nbyteArrayOutputStream);\n} catch (IOException e) {\nthrow new RuntimeException(e);\n}\n},\n() -> logger.error(\"No response body.\"));\nlogger.info(\"HTTP Response code is {}\",\nresponse.httpResponse().statusCode());\n}\n} catch (URISyntaxException | IOException e) {\nlogger.error(e.getMessage(), e);\n}\nreturn byteArrayOutputStream.toByteArray();\n}\nSee the complete example and test on GitHub.\nGenerate a pre-signed URL for an upload, then upload a file (PUT request)\nThe following example consists of two parts.\n\u2022 Part 1: Alice generates the pre-signed URL to upload an object.\n\u2022 Part 2: Bob uploads a file by using the pre-signed URL.\nPre-signed URLs 419\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPart 1: Generate the URL\nAlice already has an S3 bucket. She uses the following code to generate a URL string that Bob can\nuse in a subsequent PUT request.", "mimetype": "text/plain", "start_char_idx": 694476, "end_char_idx": 697681, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9ecdfac6-de60-4bb4-a019-99016c52823c": {"__data__": {"id_": "9ecdfac6-de60-4bb4-a019-99016c52823c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aef1e9a9-128a-4d21-aacc-a306439ea1b7", "node_type": "1", "metadata": {}, "hash": "28984dad5736fc22f405b081662338e6e1b7e0e9d687f58cbd38e7e1e5b77360", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ea5e7b8f-3a47-4279-8783-267b5ee603ef", "node_type": "1", "metadata": {}, "hash": "9cd074ec7350aa590baae0f732b780977cd838b4f3669cca933e5fe2e76f54e5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"));\nlogger.info(\"HTTP Response code is {}\",\nresponse.httpResponse().statusCode());\n}\n} catch (URISyntaxException | IOException e) {\nlogger.error(e.getMessage(), e);\n}\nreturn byteArrayOutputStream.toByteArray();\n}\nSee the complete example and test on GitHub.\nGenerate a pre-signed URL for an upload, then upload a file (PUT request)\nThe following example consists of two parts.\n\u2022 Part 1: Alice generates the pre-signed URL to upload an object.\n\u2022 Part 2: Bob uploads a file by using the pre-signed URL.\nPre-signed URLs 419\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPart 1: Generate the URL\nAlice already has an S3 bucket. She uses the following code to generate a URL string that Bob can\nuse in a subsequent PUT request.\nImports\nimport com.example.s3.util.PresignUrlUtils;\nimport org.slf4j.Logger;\nimport software.amazon.awssdk.core.internal.sync.FileContentStreamProvider;\nimport software.amazon.awssdk.http.HttpExecuteRequest;\nimport software.amazon.awssdk.http.HttpExecuteResponse;\nimport software.amazon.awssdk.http.SdkHttpClient;\nimport software.amazon.awssdk.http.SdkHttpMethod;\nimport software.amazon.awssdk.http.SdkHttpRequest;\nimport software.amazon.awssdk.http.apache.ApacheHttpClient;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport software.amazon.awssdk.services.s3.model.PutObjectRequest;\nimport software.amazon.awssdk.services.s3.model.S3Exception;\nimport software.amazon.awssdk.services.s3.presigner.S3Presigner;\nimport software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;\nimport software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.UUID;\n/* Create a presigned URL to use in a subsequent PUT request */\nPre-signed URLs 420\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String createPresignedUrl(String bucketName, String keyName, Map metadata) {\ntry (S3Presigner presigner = S3Presigner.create()) {\nPutObjectRequest objectRequest = PutObjectRequest.builder()\n.bucket(bucketName)\n.key(keyName)\n.metadata(metadata)\n.build();\nPutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()\n.signatureDuration(Duration.ofMinutes(10)) // The URL expires in\n10 minutes.\n.putObjectRequest(objectRequest)\n.build();\nPresignedPutObjectRequest presignedRequest =\npresigner.presignPutObject(presignRequest);\nString myURL = presignedRequest.url().toString();\nlogger.info(\"Presigned URL to upload a file to: [{}]\", myURL);\nlogger.info(\"HTTP method: [{}]\", presignedRequest.httpRequest().method());\nreturn presignedRequest.url().toExternalForm();\n}\n}\nPart 2: Upload a file object\nBob uses one of the following three code options to upload a file.\nUse JDK HttpURLConnection (since v1.1)\n/* Use the JDK HttpURLConnection (since v1.1) class to do the upload. */\npublic void useHttpUrlConnectionToPut(String presignedUrlString, File fileToPut,\nMap metadata) {\nlogger.info(\"Begin [{}] upload\", fileToPut.toString());\ntry {\nURL presignedUrl = new URL(presignedUrlString);\nHttpURLConnection connection = (HttpURLConnection)\npresignedUrl.openConnection();\nconnection.setDoOutput(true);\nmetadata.forEach((k, v) -> connection.setRequestProperty(\"x-amz-meta-\" + k,\nv));\nPre-signed URLs 421\nAWS SDK for Java 2.x Developer Guide for version 2.x\nconnection.setRequestMethod(\"PUT\");\nOutputStream out = connection.getOutputStream();\ntry (RandomAccessFile file = new RandomAccessFile(fileToPut, \"r\");\nFileChannel inChannel = file.getChannel()) {\nByteBuffer buffer = ByteBuffer.allocate(8192); //Buffer size is 8k\nwhile (inChannel.read(buffer) > 0) {\nbuffer.flip();\nfor (int i = 0; i < buffer.limit(); i++) {\nout.write(buffer.get());\n}\nbuffer.clear();\n}\n} catch (IOException e) {\nlogger.error(e.getMessage(), e);\n}\nout.close();\nconnection.getResponseCode();\nlogger.info(\"HTTP response code is \" + connection.getResponseCode());\n} catch (S3Exception | IOException e) {\nlogger.error(e.getMessage(), e);\n}\n}\nUse JDK HttpClient (since v11)\n/* Use the JDK HttpClient (since v11) class to do the upload.", "mimetype": "text/plain", "start_char_idx": 696951, "end_char_idx": 701449, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ea5e7b8f-3a47-4279-8783-267b5ee603ef": {"__data__": {"id_": "ea5e7b8f-3a47-4279-8783-267b5ee603ef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9ecdfac6-de60-4bb4-a019-99016c52823c", "node_type": "1", "metadata": {}, "hash": "87e849ccb37f4382998181be18fbdb1546ab69fa4187c5f89869116d29279a38", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b3f54b0-4dfa-41bd-b608-3e5541e632bc", "node_type": "1", "metadata": {}, "hash": "1f235126a6d1340ea552d1e58bd84800a988b623b7901357504a41e1f8c81f85", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*/\npublic void useHttpClientToPut(String presignedUrlString, File fileToPut,\nMap metadata) {\nlogger.info(\"Begin [{}] upload\", fileToPut.toString());\nHttpRequest.Builder requestBuilder = HttpRequest.newBuilder();\nmetadata.forEach((k, v) -> requestBuilder.header(\"x-amz-meta-\" + k, v));\nHttpClient httpClient = HttpClient.newHttpClient();\ntry {\nfinal HttpResponse response = httpClient.send(requestBuilder\n.uri(new URL(presignedUrlString).toURI())\n.PUT(HttpRequest.BodyPublishers.ofFile(Path.of(fileToPut.toURI())))\nPre-signed URLs 422\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build(),\nHttpResponse.BodyHandlers.discarding());\nlogger.info(\"HTTP response code is \" + response.statusCode());\n} catch (URISyntaxException | InterruptedException | IOException e) {\nlogger.error(e.getMessage(), e);\n}\n}\nUse SdkHttpClient from the SDK for Java\n/* Use the AWS SDK for Java V2 SdkHttpClient class to do the upload. */\npublic void useSdkHttpClientToPut(String presignedUrlString, File fileToPut,\nMap metadata) {\nlogger.info(\"Begin [{}] upload\", fileToPut.toString());\ntry {\nURL presignedUrl = new URL(presignedUrlString);\nSdkHttpRequest.Builder requestBuilder = SdkHttpRequest.builder()\n.method(SdkHttpMethod.PUT)\n.uri(presignedUrl.toURI());\n// Add headers\nmetadata.forEach((k, v) -> requestBuilder.putHeader(\"x-amz-meta-\" + k, v));\n// Finish building the request.\nSdkHttpRequest request = requestBuilder.build();\nHttpExecuteRequest executeRequest = HttpExecuteRequest.builder()\n.request(request)\n.contentStreamProvider(new\nFileContentStreamProvider(fileToPut.toPath()))\n.build();\ntry (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) {\nHttpExecuteResponse response =\nsdkHttpClient.prepareRequest(executeRequest).call();\nlogger.info(\"Response code: {}\", response.httpResponse().statusCode());\n}\n} catch (URISyntaxException | IOException e) {\nlogger.error(e.getMessage(), e);\n}\n}\nPre-signed URLs 423\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSee the complete example and test on GitHub.\nCross-Region access for Amazon S3\nWhen you work with Amazon Simple Storage Service (Amazon S3) buckets, you usually know the\nAWS Region for the bucket. The Region you work with is determined when you create the S3 client.\nHowever, sometimes you might need to work with a specific bucket, but you don't know if it's\nlocated in the same Region that's set for the S3 client.\nInstead of making more calls to determine the bucket Region, you can use the SDK to enable access\nto S3 buckets across different Regions.\nSetup\nSupport for cross-Region access became available with version 2.20.111 of the SDK. Use this\nversion or a later one in your Maven build file for the s3 dependency as shown in the following\nsnippet.\n\nsoftware.amazon.awssdk\ns3\n2.27.21\n\nNext, when you create your S3 client, enable cross-Region access as shown in the snippet. By\ndefault, access is not enabled.\nS3AsyncClient client = S3AsyncClient.builder()\n.crossRegionAccessEnabled(true)\n.build();\nHow the SDK provides cross-Region access\nWhen you reference an existing bucket in a request, such as when you use the putObject method,\nthe SDK initiates a request to the Region configured for the client.\nIf the bucket does not exist in that specific Region, the error response includes the actual Region\nwhere the bucket resides. The SDK then uses the correct Region in a second request.\nTo optimize future requests to the same bucket, the SDK caches this Region mapping in the client.\nCross-Region access 424\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConsiderations\nWhen you enable cross-Region bucket access, be aware that the first API call might result in\nincreased latency if the bucket isn't in the client's configured Region. However, subsequent calls\nbenefit from cached Region information, resulting in improved performance.\nWhen you enable cross-Region access, access to the bucket is not affected. The user must be\nauthorized to access the bucket in whatever Region it resides.\nAmazon S3 checksums with AWS SDK for Java\nAmazon Simple Storage Service (Amazon S3) provides the ability to specify a checksum when you\nupload an object. When you specify a checksum, it is stored with the object and can be validated\nwhen the object is downloaded.\nChecksums provide an additional layer of data integrity when you transfer files. With checksums,\nyou can verify data consistency by confirming that the received file matches the original file.", "mimetype": "text/plain", "start_char_idx": 701450, "end_char_idx": 706002, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2b3f54b0-4dfa-41bd-b608-3e5541e632bc": {"__data__": {"id_": "2b3f54b0-4dfa-41bd-b608-3e5541e632bc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ea5e7b8f-3a47-4279-8783-267b5ee603ef", "node_type": "1", "metadata": {}, "hash": "9cd074ec7350aa590baae0f732b780977cd838b4f3669cca933e5fe2e76f54e5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aa9e65b0-40e2-46cf-a575-9e3a0e24c178", "node_type": "1", "metadata": {}, "hash": "9701b76467d226b3a28f24510f6ca63ace30fd44655e530dd445668eb4ae92fc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "However, subsequent calls\nbenefit from cached Region information, resulting in improved performance.\nWhen you enable cross-Region access, access to the bucket is not affected. The user must be\nauthorized to access the bucket in whatever Region it resides.\nAmazon S3 checksums with AWS SDK for Java\nAmazon Simple Storage Service (Amazon S3) provides the ability to specify a checksum when you\nupload an object. When you specify a checksum, it is stored with the object and can be validated\nwhen the object is downloaded.\nChecksums provide an additional layer of data integrity when you transfer files. With checksums,\nyou can verify data consistency by confirming that the received file matches the original file. For\nmore information about checksums with Amazon S3, see the Amazon Simple Storage Service User\nGuide.\nAmazon S3 currently supports four checksum algorithms: SHA-1, SHA-256, CRC-32, and CRC-32C.\nYou have the flexibility to choose the algorithm that best fits your needs and let the SDK calculate\nthe checksum. Alternatively, you can specify their own pre-computed checksum value by using one\nof the four supported algorithms.\nWe discuss checksums in two request phases: uploading an object and downloading an object.\nUpload an object\nYou upload objects to Amazon S3 by using the putObject method of the S3Client. Use the\nchecksumAlgorithm method of the builder for the PutObjectRequest to enable checksum\ncomputation and specify the algorithm. Valid values for the algorithm are CRC32, CRC32C, SHA1,\nand SHA256.\nThe following code snippet shows a request to upload an object with a CRC-32 checksum. When\nthe SDK sends the request, it calculates the CRC-32 checksum and uploads the object. Amazon S3\nstores the checksum with the object.\npublic void putObjectWithChecksum() {\ns3Client.putObject(b -> b\n.bucket(bucketName)\nChecksums 425\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.key(key)\n.checksumAlgorithm(ChecksumAlgorithm.CRC32),\nRequestBody.fromString(\"This is a test\"));\n}\nIf the checksum that the SDK calculates doesn't match the checksum that Amazon S3 calculates\nwhen it receives the request, an error is returned.\nUse a pre-calculated checksum value\nA pre-calculated checksum value provided with the request disables automatic computation by the\nSDK and uses the provided value instead.\nThe following example shows a request with a pre-calculated SHA-256 checksum.\npublic void putObjectWithPrecalculatedChecksum(String filePath) {\nString checksum = calculateChecksum(filePath, \"SHA-256\");\ns3Client.putObject((b -> b\n.bucket(bucketName)\n.key(key)\n.checksumSHA256(checksum)),\nRequestBody.fromFile(Paths.get(filePath)));\n}\nIf Amazon S3 determines the checksum value is incorrect for the specified algorithm, the service\nreturns an error response.\nMultipart uploads\nYou can also use checksums with multipart uploads. The SDK for Java 2.x provides two options to\nuse checksums with multipart uploads. The first option uses the S3TransferManager.\nThe following transfer manager example specifies the SHA1 algorithm for the upload.\npublic void multipartUploadWithChecksumTm(String filePath) {\nS3TransferManager transferManager = S3TransferManager.create();\nUploadFileRequest uploadFileRequest = UploadFileRequest.builder()\n.putObjectRequest(b -> b\n.bucket(bucketName)\n.key(key)\n.checksumAlgorithm(ChecksumAlgorithm.SHA1))\n.source(Paths.get(filePath))\nChecksums 426\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nFileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);\nfileUpload.completionFuture().join();\ntransferManager.close();\n}\nThe second option uses the S3Client API (or the S3AsyncClient API) to perform the multipart\nupload. If you specify a checksum with this approach, you must specify the algorithm to use on the\ninitiation of the upload. You must also specify the algorithm for each part request and provide the\nchecksum calculated for each part after it is uploaded.\npublic void multipartUploadWithChecksumS3Client(String filePath) {\nChecksumAlgorithm algorithm = ChecksumAlgorithm.CRC32;\n// Initiate the multipart upload.\nCreateMultipartUploadResponse createMultipartUploadResponse =\ns3Client.createMultipartUpload(b -> b\n.bucket(bucketName)\n.key(key)\n.checksumAlgorithm(algorithm)); // Checksum specified on initiation.\nString uploadId = createMultipartUploadResponse.uploadId();\n// Upload the parts of the file.", "mimetype": "text/plain", "start_char_idx": 705290, "end_char_idx": 709672, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "aa9e65b0-40e2-46cf-a575-9e3a0e24c178": {"__data__": {"id_": "aa9e65b0-40e2-46cf-a575-9e3a0e24c178", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b3f54b0-4dfa-41bd-b608-3e5541e632bc", "node_type": "1", "metadata": {}, "hash": "1f235126a6d1340ea552d1e58bd84800a988b623b7901357504a41e1f8c81f85", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0e4581fd-7f44-435b-9965-81ddde6c1df9", "node_type": "1", "metadata": {}, "hash": "807a4c2df89c6bf6fcd55a7062c8b068d49901717166c28ec4e487c48de4d8a9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "If you specify a checksum with this approach, you must specify the algorithm to use on the\ninitiation of the upload. You must also specify the algorithm for each part request and provide the\nchecksum calculated for each part after it is uploaded.\npublic void multipartUploadWithChecksumS3Client(String filePath) {\nChecksumAlgorithm algorithm = ChecksumAlgorithm.CRC32;\n// Initiate the multipart upload.\nCreateMultipartUploadResponse createMultipartUploadResponse =\ns3Client.createMultipartUpload(b -> b\n.bucket(bucketName)\n.key(key)\n.checksumAlgorithm(algorithm)); // Checksum specified on initiation.\nString uploadId = createMultipartUploadResponse.uploadId();\n// Upload the parts of the file.\nint partNumber = 1;\nList completedParts = new ArrayList<>();\nByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5); // 5 MB byte buffer\ntry (RandomAccessFile file = new RandomAccessFile(filePath, \"r\")) {\nlong fileSize = file.length();\nlong position = 0;\nwhile (position < fileSize) {\nfile.seek(position);\nlong read = file.getChannel().read(bb);\nbb.flip(); // Swap position and limit before reading from the buffer.\nUploadPartRequest uploadPartRequest = UploadPartRequest.builder()\n.bucket(bucketName)\n.key(key)\n.uploadId(uploadId)\n.checksumAlgorithm(algorithm) // Checksum specified on each part.\n.partNumber(partNumber)\n.build();\nChecksums 427\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUploadPartResponse partResponse = s3Client.uploadPart(\nuploadPartRequest,\nRequestBody.fromByteBuffer(bb));\nCompletedPart part = CompletedPart.builder()\n.partNumber(partNumber)\n.checksumCRC32(partResponse.checksumCRC32()) // Provide the\ncalculated checksum.\n.eTag(partResponse.eTag())\n.build();\ncompletedParts.add(part);\nbb.clear();\nposition += read;\npartNumber++;\n}\n} catch (IOException e) {\nSystem.err.println(e.getMessage());\n}\n// Complete the multipart upload.\ns3Client.completeMultipartUpload(b -> b\n.bucket(bucketName)\n.key(key)\n.uploadId(uploadId)\n.multipartUpload(CompletedMultipartUpload.builder().parts(completedParts).build()));\n}\nCode for the complete examples and tests are in the GitHub code examples repository.\nDownload an object\nWhen you use the getObject method to download an object, the SDK automatically validates the\nchecksum when the checksumMode method of the builder for the GetObjectRequest is set to\nChecksumMode.ENABLED.\nThe request in the following snippet directs the SDK to validate the checksum in the response by\ncalculating the checksum and comparing the values.\npublic GetObjectResponse getObjectWithChecksum() {\nreturn s3Client.getObject(b -> b\n.bucket(bucketName)\nChecksums 428\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.key(key)\n.checksumMode(ChecksumMode.ENABLED))\n.response();\n}\nIf the object wasn't uploaded with a checksum, no validation takes place.\nAn object in Amazon S3 can have multiple checksums, but only one checksum is validated on\ndownload. The following precedence\u2014 based on the efficiency of the checksum algorithm\u2014\ndetermines which checksum the SDK validates:\n1. CRC-32C\n2. CRC-32\n3. SHA-1\n4. SHA-256\nFor example, if a response contains both CRC-32 and SHA-256 checksums, only the CRC-32\nchecksum is validated.\nUse a performant S3 client: AWS CRT-based S3 client\nThe AWS CRT-based S3 client\u2014built on top of the AWS Common Runtime (CRT)\u2014is an alternative\nS3 asynchronous client. It transfers objects to and from Amazon Simple Storage Service (Amazon\nS3) with enhanced performance and reliability by automatically using Amazon S3's multipart\nupload API and byte-range fetches.\nThe AWS CRT-based S3 client improves transfer reliability in case there is a network failure.\nReliability is improved by retrying individual failed parts of a file transfer without restarting the\ntransfer from the beginning.\nIn addition, the AWS CRT-based S3 client offers enhanced connection pooling and Domain Name\nSystem (DNS) load balancing, which also improves throughput.\nYou can use the AWS CRT-based S3 client in place of the SDK's standard S3 asynchronous client\nand take advantage of its improved throughput right away.\nAWS CRT-based components in the SDK\nThe AWS CRT-based S3 client, described in this topic, and the AWS CRT-based HTTP client are\ndifferent components in the SDK.\nUse a performant S3 client 429\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe AWS CRT-based S3 client is an implementation of the S3AsyncClient interface and is used for\nworking with the Amazon S3 service. It is an alternative to the Java-based implementation of the\nS3AsyncClient interface and offers several benefits.", "mimetype": "text/plain", "start_char_idx": 708978, "end_char_idx": 713545, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0e4581fd-7f44-435b-9965-81ddde6c1df9": {"__data__": {"id_": "0e4581fd-7f44-435b-9965-81ddde6c1df9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aa9e65b0-40e2-46cf-a575-9e3a0e24c178", "node_type": "1", "metadata": {}, "hash": "9701b76467d226b3a28f24510f6ca63ace30fd44655e530dd445668eb4ae92fc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "545a6fda-cdcd-466c-a552-9fabafff40d4", "node_type": "1", "metadata": {}, "hash": "69cda44197ecea1ae751b424bfdeb3b1381a701b1d1d51aa42d4e3ba9156eb3b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Reliability is improved by retrying individual failed parts of a file transfer without restarting the\ntransfer from the beginning.\nIn addition, the AWS CRT-based S3 client offers enhanced connection pooling and Domain Name\nSystem (DNS) load balancing, which also improves throughput.\nYou can use the AWS CRT-based S3 client in place of the SDK's standard S3 asynchronous client\nand take advantage of its improved throughput right away.\nAWS CRT-based components in the SDK\nThe AWS CRT-based S3 client, described in this topic, and the AWS CRT-based HTTP client are\ndifferent components in the SDK.\nUse a performant S3 client 429\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe AWS CRT-based S3 client is an implementation of the S3AsyncClient interface and is used for\nworking with the Amazon S3 service. It is an alternative to the Java-based implementation of the\nS3AsyncClient interface and offers several benefits.\nThe AWS CRT-based HTTP client is an implementation of the SdkAsyncHttpClient interface and\nis used for general HTTP communication. It is an alternative to the Netty implementation of the\nSdkAsyncHttpClient interface and offers several advantages.\nAlthough both components use libraries from the AWS Common Runtime, the AWS CRT-based\nS3 client uses the aws-c-s3 library and supports the S3 multipart upload API features. Since the\nAWS CRT-based HTTP client is meant for general purpose use, it does not support the S3 multipart\nupload API features.\nAdd dependencies to use the AWS CRT-based S3 client\nTo use the AWS CRT-based S3 client, add the following two dependencies to your Maven project\nfile. The example shows the minimum versions to use. Search the Maven central repository for the\nmost recent versions of the s3 and aws-crt artifacts.\n\nsoftware.amazon.awssdk\ns3\n2.27.21\n\n\nsoftware.amazon.awssdk.crt\naws-crt\n0.30.11\n\nCreate an instance of the AWS CRT-based S3 client\nCreate an instance of the AWS CRT-based S3 client with default settings as shown in the following\ncode snippet.\nS3AsyncClient s3AsyncClient = S3AsyncClient.crtCreate();\nTo configure the client, use the AWS CRT client builder. You can switch from the standard S3\nasynchronous client to AWS CRT-based client by changing the builder method.\nUse a performant S3 client 430\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nS3AsyncClient s3AsyncClient =\nS3AsyncClient.crtBuilder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_WEST_2)\n.targetThroughputInGbps(20.0)\n.minimumPartSizeInBytes(8 * 1025 * 1024L)\n.build();\nNote\nSome of the settings in the standard builder might not be currently supported in the AWS\nCRT client builder. Get the standard builder by calling S3AsyncClient#builder().\nUse the AWS CRT-based S3 client\nUse the AWS CRT-based S3 client to call Amazon S3 API operations. The following example\ndemonstrates the PutObject and GetObject operations available through the AWS SDK for Java.\nimport software.amazon.awssdk.core.async.AsyncRequestBody;\nimport software.amazon.awssdk.core.async.AsyncResponseTransformer;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nimport software.amazon.awssdk.services.s3.model.GetObjectResponse;\nimport software.amazon.awssdk.services.s3.model.PutObjectResponse;\nS3AsyncClient s3Client = S3AsyncClient.crtCreate();\n// Upload a local file to Amazon S3.\nPutObjectResponse putObjectResponse =\ns3Client.putObject(req -> req.bucket()\n.key(),\nAsyncRequestBody.fromFile(Paths.get()))\n.join();\n// Download an object from Amazon S3 to a local file.\nUse a performant S3 client 431\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetObjectResponse getObjectResponse =\ns3Client.getObject(req -> req.bucket()\n.key(),\nAsyncResponseTransformer.toFile(Paths.get()))\n.join();\nConfiguration limitations\nThe AWS CRT-based S3 client and Java-based S3 async client provide comparable features, with\nthe AWS CRT-based S3 client offering a performance edge. However, the AWS CRT-based S3 client\nlacks configuration settings that the Java-based S3 async client has.", "mimetype": "text/plain", "start_char_idx": 712619, "end_char_idx": 717075, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "545a6fda-cdcd-466c-a552-9fabafff40d4": {"__data__": {"id_": "545a6fda-cdcd-466c-a552-9fabafff40d4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0e4581fd-7f44-435b-9965-81ddde6c1df9", "node_type": "1", "metadata": {}, "hash": "807a4c2df89c6bf6fcd55a7062c8b068d49901717166c28ec4e487c48de4d8a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e4b6629f-bda7-42ff-b788-1da8afc1be3e", "node_type": "1", "metadata": {}, "hash": "1851e07fdd624f4a6e1cd609a8ea597c7ce73330053ee6ddeb7d9f2fc016b0fe", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "PutObjectResponse putObjectResponse =\ns3Client.putObject(req -> req.bucket()\n.key(),\nAsyncRequestBody.fromFile(Paths.get()))\n.join();\n// Download an object from Amazon S3 to a local file.\nUse a performant S3 client 431\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetObjectResponse getObjectResponse =\ns3Client.getObject(req -> req.bucket()\n.key(),\nAsyncResponseTransformer.toFile(Paths.get()))\n.join();\nConfiguration limitations\nThe AWS CRT-based S3 client and Java-based S3 async client provide comparable features, with\nthe AWS CRT-based S3 client offering a performance edge. However, the AWS CRT-based S3 client\nlacks configuration settings that the Java-based S3 async client has. These settings include:\n\u2022 Client-level configuration: API call attempt timeout, compression execution interceptors, metric\npublishers, custom execution attributes, custom advanced options, custom scheduled executor\nservice, custom headers\n\u2022 Request-level configuration: custom signers, credentials providers, API call attempt timeout\nFor a full listing of the configuration differences, see the API reference.\nJava-based S3 async client AWS CRT-based S3 client\nClient-level configurations Client-level configurations\n\u2022 ClientOverrideConfiguration.Builder \u2022 S3CrtAsyncClientBuilder\nRequest-level configurations No request-level configurations\n\u2022 RequestOverrideConfiguration.Builder\n\u2022 AwsRequestOverrideConfiguration.Builder\nConfigure the Java-based S3 async client to use parallel transfers\nSince version 2.27.5, the standard Java-based S3 async client supports automatic parallel transfers\n(multipart uploads and downloads). You configure support for parallel transfers when you create\nthe Java-based S3 async client.\nThis section shows how to enable parallel transfers and how to customize the configuration.\nConfigure parallel transfer support 432\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate an instance of S3AsyncClient\nWhen you create an S3AsyncClient instance without calling any of the multipart* methods on\nthe builder, parallel transfers are not enabled. Each of following statements create a Java-based S3\nasync client without support for multipart uploads and downloads.\nCreate without multipart support\nExample\nimport software.amazon.awssdk.auth.credentials.ProcessCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nS3AsyncClient s3Client = S3AsyncClient.create();\nS3AsyncClient s3Client2 = S3AsyncClient.builder().build();\nS3AsyncClient s3Client3 = S3AsyncClient.builder()\n.credentialsProvider(ProcessCredentialsProvider.builder().build())\n.region(Region.EU_NORTH_1)\n.build();\nCreate with multipart support\nTo enable parallel transfers with default settings, call the multipartEnabled on the builder and\npass in true as shown in the following example.\nExample\nS3AsyncClient s3AsyncClient2 = S3AsyncClient.builder()\n.multipartEnabled(true)\n.build();\nThe default value is 8 MiB for thresholdInBytes and minimumPartSizeInBytes settings.\nIf you customize the multipart settings, parallel transfers are automatically enabled as shown in\nthe following.\nExample\nimport software.amazon.awssdk.services.s3.S3AsyncClient;\nConfigure parallel transfer support 433\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport static software.amazon.awssdk.transfer.s3.SizeConstant.MB;\nS3AsyncClient s3AsyncClient2 = S3AsyncClient.builder()\n.multipartConfiguration(b -> b\n.thresholdInBytes(16 * MB)\n.minimumPartSizeInBytes(10 * MB))\n.build();\nTransfer files and directories with the Amazon S3 Transfer Manager\nThe Amazon S3 Transfer Manager is an open source, high level file transfer utility for the AWS SDK\nfor Java 2.x. Use it to transfer files and directories to and from Amazon Simple Storage Service\n(Amazon S3).\nWhen built on top of the AWS CRT-based S3 client or the standard Java-based S3 async client with\nmultipart enabled, the S3 Transfer Manager can take advantage of performance improvements\nsuch as the multipart upload API and byte-range fetches.\nWith the S3 Transfer Manager, you can also monitor a transfer's progress in real time and pause the\ntransfer for later execution.\nGet started\nAdd dependencies to your build file\nTo use the S3 Transfer Manager with enhanced multipart performance, configure your build file\nwith necessary dependencies.", "mimetype": "text/plain", "start_char_idx": 716313, "end_char_idx": 720725, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e4b6629f-bda7-42ff-b788-1da8afc1be3e": {"__data__": {"id_": "e4b6629f-bda7-42ff-b788-1da8afc1be3e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "545a6fda-cdcd-466c-a552-9fabafff40d4", "node_type": "1", "metadata": {}, "hash": "69cda44197ecea1ae751b424bfdeb3b1381a701b1d1d51aa42d4e3ba9156eb3b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9a0dfcc2-09ae-4210-9b70-d570f75aa118", "node_type": "1", "metadata": {}, "hash": "d57bb314d68ffcf2a9350c20b6c61e8a762fc5e35b810cc2dfa409754054b3a8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use it to transfer files and directories to and from Amazon Simple Storage Service\n(Amazon S3).\nWhen built on top of the AWS CRT-based S3 client or the standard Java-based S3 async client with\nmultipart enabled, the S3 Transfer Manager can take advantage of performance improvements\nsuch as the multipart upload API and byte-range fetches.\nWith the S3 Transfer Manager, you can also monitor a transfer's progress in real time and pause the\ntransfer for later execution.\nGet started\nAdd dependencies to your build file\nTo use the S3 Transfer Manager with enhanced multipart performance, configure your build file\nwith necessary dependencies.\nUse the AWS CRT-based S3 client\n\n\n\nsoftware.amazon.awssdk\nbom\n1\n2.27.21 \npom\nimport\n\n\nTransfer files and directories 434\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\n\n\nsoftware.amazon.awssdk\ns3-transfer-manager\n\n\nsoftware.amazon.awssdk.crt\naws-crt\n2\n0.29.143 \n\n\n1 2\nLatest version. Latest version.\nUse the Java-based S3 async client\n\n\n\nsoftware.amazon.awssdk\nbom\n1\n2.27.21 \npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ns3-transfer-manager\n\n\n1\nLatest version.\nCreate an instance of the S3 Transfer Manager\nTo enable parallel transfer, you must pass in a AWS CRT-based S3 client OR a Java-based S3 async\nclient with multipart enabled. The following examples shows how to configure a S3 Transfer\nManager with custom settings.\nTransfer files and directories 435\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUse the AWS CRT-based S3 client\nS3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.targetThroughputInGbps(20.0)\n.minimumPartSizeInBytes(8 * MB)\n.build();\nS3TransferManager transferManager = S3TransferManager.builder()\n.s3Client(s3AsyncClient)\n.build();\nUse the Java-based S3 async client\nIf the aws-crt dependency is not included in the build file, the S3 Transfer Manager is built on\ntop of the standard Java-based S3 async client used in the SDK for Java 2.x.\nCustom configuration of S3 client - requires multipart enabled\nS3AsyncClient s3AsyncClient = S3AsyncClient.builder()\n.multipartEnabled(true)\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.targetThroughputInGbps(20.0)\n.minimumPartSizeInBytes(8 * MB)\n.build();\nS3TransferManager transferManager = S3TransferManager.builder()\n.s3Client(s3AsyncClient)\n.build();\nNo configuration of S3 client - multipart support automatically enabled\nS3TransferManager transferManager = S3TransferManager.create();\nUpload a file to an S3 bucket\nThe following example shows a file upload example along with the optional use of a\nLoggingTransferListener, which logs the progress of the upload.\nTransfer files and directories 436\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo upload a file to Amazon S3 using the S3 Transfer Manager, pass an UploadFileRequest\nobject to the S3TransferManager's uploadFile method.\nThe FileUpload object returned from the uploadFile method represents the upload process.\nAfter the request finishes, the CompletedFileUpload object contains information about the upload.", "mimetype": "text/plain", "start_char_idx": 720085, "end_char_idx": 723880, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9a0dfcc2-09ae-4210-9b70-d570f75aa118": {"__data__": {"id_": "9a0dfcc2-09ae-4210-9b70-d570f75aa118", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e4b6629f-bda7-42ff-b788-1da8afc1be3e", "node_type": "1", "metadata": {}, "hash": "1851e07fdd624f4a6e1cd609a8ea597c7ce73330053ee6ddeb7d9f2fc016b0fe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "032e2def-ac57-4483-ad24-704767e7826f", "node_type": "1", "metadata": {}, "hash": "505a4243ea19d7424e63bc1a8cbeb6781d2a3e5d2667c7e3a63fe3de56c23646", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Transfer files and directories 436\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo upload a file to Amazon S3 using the S3 Transfer Manager, pass an UploadFileRequest\nobject to the S3TransferManager's uploadFile method.\nThe FileUpload object returned from the uploadFile method represents the upload process.\nAfter the request finishes, the CompletedFileUpload object contains information about the upload.\npublic String uploadFile(S3TransferManager transferManager, String bucketName,\nString key, URI filePathURI) {\nUploadFileRequest uploadFileRequest = UploadFileRequest.builder()\n.putObjectRequest(b -> b.bucket(bucketName).key(key))\n.source(Paths.get(filePathURI))\n.build();\nFileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);\nCompletedFileUpload uploadResult = fileUpload.completionFuture().join();\nreturn uploadResult.response().eTag();\n}\nImports\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.transfer.s3.S3TransferManager;\nimport software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;\nimport software.amazon.awssdk.transfer.s3.model.FileUpload;\nimport software.amazon.awssdk.transfer.s3.model.UploadFileRequest;\nimport software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.nio.file.Paths;\nimport java.util.UUID;\nDownload a file from an S3 bucket\nThe following example shows a download example along with the optional use of a\nLoggingTransferListener, which logs the progress of the download.\nTo download an object from an S3 bucket using the S3 Transfer Manager, build a\nDownloadFileRequest object and pass it to the downloadFile method.\nTransfer files and directories 437\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe FileDownload object returned by the S3TransferManager's downloadFile method\nrepresents the file transfer. After the download completes, the CompletedFileDownload contains\naccess to information about the download.\npublic Long downloadFile(S3TransferManager transferManager, String bucketName,\nString key, String downloadedFileWithPath) {\nDownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()\n.getObjectRequest(b -> b.bucket(bucketName).key(key))\n.destination(Paths.get(downloadedFileWithPath))\n.build();\nFileDownload downloadFile = transferManager.downloadFile(downloadFileRequest);\nCompletedFileDownload downloadResult = downloadFile.completionFuture().join();\nlogger.info(\"Content length [{}]\", downloadResult.response().contentLength());\nreturn downloadResult.response().contentLength();\n}\nImports\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.transfer.s3.S3TransferManager;\nimport software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;\nimport software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;\nimport software.amazon.awssdk.transfer.s3.model.FileDownload;\nimport software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.UUID;\nCopy an Amazon S3 object to another bucket\nThe following example shows how to copy an object with the S3 Transfer Manager.\nTransfer files and directories 438\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo begin the copy of an object from an S3 bucket to another bucket, create a basic\nCopyObjectRequest instance.\nNext, wrap the basic CopyObjectRequest in a CopyRequest that can be used by the S3 Transfer\nManager.\nThe Copy object returned by the S3TransferManager's copy method represents the copy\nprocess. After the copy process completes, the CompletedCopy object contains details about the\nresponse.\npublic String copyObject(S3TransferManager transferManager, String bucketName,\nString key, String destinationBucket, String destinationKey) {\nCopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()\n.sourceBucket(bucketName)\n.sourceKey(key)\n.destinationBucket(destinationBucket)\n.destinationKey(destinationKey)\n.build();\nCopyRequest copyRequest = CopyRequest.builder()\n.copyObjectRequest(copyObjectRequest)\n.build();\nCopy copy = transferManager.copy(copyRequest);\nCompletedCopy completedCopy = copy.completionFuture().join();\nreturn completedCopy.response().copyObjectResult().eTag();\n}\nNote\nTo perform a cross-Region copy with the S3 Transfer Manager, enable\ncrossRegionAccessEnabled on the AWS CRT-based S3 client builder as shown in the\nfollowing snippet.", "mimetype": "text/plain", "start_char_idx": 723466, "end_char_idx": 728120, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "032e2def-ac57-4483-ad24-704767e7826f": {"__data__": {"id_": "032e2def-ac57-4483-ad24-704767e7826f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9a0dfcc2-09ae-4210-9b70-d570f75aa118", "node_type": "1", "metadata": {}, "hash": "d57bb314d68ffcf2a9350c20b6c61e8a762fc5e35b810cc2dfa409754054b3a8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a6394455-dc90-4d99-903b-f61c187cb1b5", "node_type": "1", "metadata": {}, "hash": "54be2abbb2b16eb7a5de84757548f41b70a6ff5f2d93c2a86a16d42c39239d9d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The Copy object returned by the S3TransferManager's copy method represents the copy\nprocess. After the copy process completes, the CompletedCopy object contains details about the\nresponse.\npublic String copyObject(S3TransferManager transferManager, String bucketName,\nString key, String destinationBucket, String destinationKey) {\nCopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()\n.sourceBucket(bucketName)\n.sourceKey(key)\n.destinationBucket(destinationBucket)\n.destinationKey(destinationKey)\n.build();\nCopyRequest copyRequest = CopyRequest.builder()\n.copyObjectRequest(copyObjectRequest)\n.build();\nCopy copy = transferManager.copy(copyRequest);\nCompletedCopy completedCopy = copy.completionFuture().join();\nreturn completedCopy.response().copyObjectResult().eTag();\n}\nNote\nTo perform a cross-Region copy with the S3 Transfer Manager, enable\ncrossRegionAccessEnabled on the AWS CRT-based S3 client builder as shown in the\nfollowing snippet.\nS3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder()\n.crossRegionAccessEnabled(true)\n.build();\nS3TransferManager transferManager = S3TransferManager.builder()\n.s3Client(s3AsyncClient)\nTransfer files and directories 439\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nImports\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.s3.model.CopyObjectRequest;\nimport software.amazon.awssdk.transfer.s3.S3TransferManager;\nimport software.amazon.awssdk.transfer.s3.model.CompletedCopy;\nimport software.amazon.awssdk.transfer.s3.model.Copy;\nimport software.amazon.awssdk.transfer.s3.model.CopyRequest;\nimport java.util.UUID;\nUpload a local directory to an S3 bucket\nThe following example demonstrates how you can upload a local directory to S3.\nStart by calling the uploadDirectory method of the S3TransferManager instance, passing in an\nUploadDirectoryRequest.\nThe DirectoryUpload object represents the upload process, which generates a\nCompletedDirectoryUpload when the request completes. The CompleteDirectoryUpload object\ncontains information about the results of the transfer, including which files failed to transfer.\npublic Integer uploadDirectory(S3TransferManager transferManager,\nURI sourceDirectory, String bucketName) {\nDirectoryUpload directoryUpload =\ntransferManager.uploadDirectory(UploadDirectoryRequest.builder()\n.source(Paths.get(sourceDirectory))\n.bucket(bucketName)\n.build());\nCompletedDirectoryUpload completedDirectoryUpload =\ndirectoryUpload.completionFuture().join();\ncompletedDirectoryUpload.failedTransfers()\n.forEach(fail -> logger.warn(\"Object [{}] failed to transfer\",\nfail.toString()));\nreturn completedDirectoryUpload.failedTransfers().size();\nTransfer files and directories 440\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nImports\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.s3.model.ObjectIdentifier;\nimport software.amazon.awssdk.transfer.s3.S3TransferManager;\nimport software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;\nimport software.amazon.awssdk.transfer.s3.model.DirectoryUpload;\nimport software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.nio.file.Paths;\nimport java.util.UUID;\nDownload S3 bucket objects to a local directory\nYou can download the objects in an S3 bucket to a local directory as shown in the following\nexample.\nTo download the objects in an S3 bucket to a local directory, begin by calling the\ndownloadDirectory method of the Transfer Manager, passing in a DownloadDirectoryRequest.\nThe DirectoryDownload object represents the download process, which generates a\nCompletedDirectoryDownload when the request completes. The CompleteDirectoryDownload\nobject contains information about the results of the transfer, including which files failed to\ntransfer.", "mimetype": "text/plain", "start_char_idx": 727164, "end_char_idx": 731117, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a6394455-dc90-4d99-903b-f61c187cb1b5": {"__data__": {"id_": "a6394455-dc90-4d99-903b-f61c187cb1b5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "032e2def-ac57-4483-ad24-704767e7826f", "node_type": "1", "metadata": {}, "hash": "505a4243ea19d7424e63bc1a8cbeb6781d2a3e5d2667c7e3a63fe3de56c23646", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1715c75c-23e9-4159-afee-a3f390a45650", "node_type": "1", "metadata": {}, "hash": "28ce83f8e090effbc78ab654aca06bd404cfde7f7e31ec01c430749f36c6fd44", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "To download the objects in an S3 bucket to a local directory, begin by calling the\ndownloadDirectory method of the Transfer Manager, passing in a DownloadDirectoryRequest.\nThe DirectoryDownload object represents the download process, which generates a\nCompletedDirectoryDownload when the request completes. The CompleteDirectoryDownload\nobject contains information about the results of the transfer, including which files failed to\ntransfer.\npublic Integer downloadObjectsToDirectory(S3TransferManager transferManager,\nURI destinationPathURI, String bucketName) {\nDirectoryDownload directoryDownload =\ntransferManager.downloadDirectory(DownloadDirectoryRequest.builder()\n.destination(Paths.get(destinationPathURI))\n.bucket(bucketName)\n.build());\nCompletedDirectoryDownload completedDirectoryDownload =\ndirectoryDownload.completionFuture().join();\ncompletedDirectoryDownload.failedTransfers()\nTransfer files and directories 441\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.forEach(fail -> logger.warn(\"Object [{}] failed to transfer\",\nfail.toString()));\nreturn completedDirectoryDownload.failedTransfers().size();\n}\nImports\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.s3.model.ObjectIdentifier;\nimport software.amazon.awssdk.transfer.s3.S3TransferManager;\nimport software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;\nimport software.amazon.awssdk.transfer.s3.model.DirectoryDownload;\nimport software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.stream.Collectors;\nSee complete examples\nGitHub contains the complete code for all examples on this page.\nWork with S3 Event Notifications\nTo help you monitor activity in your buckets, Amazon S3 can send notifications when certain\nevents happen. The Amazon S3 User Guide provides information on the notifications that a bucket\ncan send out.\nYou can set up a bucket to send events to four possible destinations using the SDK for Java:\n\u2022 Amazon Simple Notification Service topics\n\u2022 Amazon Simple Queue Service queues\n\u2022 AWS Lambda functions\nS3 Event Notifications 442\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Amazon EventBridge\nWhen you setup up a bucket to send events to EventBridge, you have the ability to configure an\nEventBridge rule to fanout the same event to multiple destinations. When you configure your\nbucket to send directly to one of the first three destinations, only one destination type can be\nspecified for each event.\nIn the next section, you'll see how to configure a bucket using the SDK for Java to send S3 Event\nNotifications in two ways: directly to an Amazon SQS queue and to EventBridge.\nThe last section shows you how to use the S3 Event Notifications API to work with notifications in\nan object-oriented way.\nConfigure a bucket to send directly to a destination\nThe following example configures a bucket to send notifications when object create events or object\ntagging events occur against a bucket.\nstatic void processS3Events(String bucketName, String queueArn) {\n// Configure the bucket to send Object Created and Object Tagging notifications to\nan existing SQS queue.\ns3Client.putBucketNotificationConfiguration(b -> b\n.notificationConfiguration(ncb -> ncb\n.queueConfigurations(qcb -> qcb\n.events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING)\n.queueArn(queueArn)))\n.bucket(bucketName)\n);\n}\nThe code shown above sets up one queue to receive two types of events. Conveniently, the\nqueueConfigurations method allows you to set multiple queue destinations if needed. Also,\nin the notificationConfiguration method you can set additional destinations, such as one\nor more Amazon SNS topics or one or more Lambda functions. The following snippet shows an\nexample with two queues and three types of destinations.\ns3Client.putBucketNotificationConfiguration(b -> b\n.notificationConfiguration(ncb -> ncb\n.queueConfigurations(qcb -> qcb\n.events(Event.S3_OBJECT_CREATED,\nEvent.S3_OBJECT_TAGGING)\nS3 Event Notifications 443\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.queueArn(queueArn),\nqcb2 -> qcb2.<...>)\n.topicConfigurations(tcb -> tcb.<...>)\n.lambdaFunctionConfigurations(lfcb -> lfcb.<...>))\n.bucket(bucketName)\n);\nThe Code Examples GitHub repository contains the complete example to send S3 event\nnotifications directly to a queue.\nConfigure a bucket to send to EventBridge\nThe following example configures a bucket to send notifications to EventBridge.\npublic static String setBucketNotificationToEventBridge(String bucketName) {\n// Enable bucket to emit S3 Event notifications to EventBridge.", "mimetype": "text/plain", "start_char_idx": 730676, "end_char_idx": 735565, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1715c75c-23e9-4159-afee-a3f390a45650": {"__data__": {"id_": "1715c75c-23e9-4159-afee-a3f390a45650", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a6394455-dc90-4d99-903b-f61c187cb1b5", "node_type": "1", "metadata": {}, "hash": "54be2abbb2b16eb7a5de84757548f41b70a6ff5f2d93c2a86a16d42c39239d9d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5d22b188-7eb0-4210-963c-e00829c9886d", "node_type": "1", "metadata": {}, "hash": "488037455587c8a66a11094b1428a4311d5d891a23f9b5c1f2343a5a64bffbf2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The following snippet shows an\nexample with two queues and three types of destinations.\ns3Client.putBucketNotificationConfiguration(b -> b\n.notificationConfiguration(ncb -> ncb\n.queueConfigurations(qcb -> qcb\n.events(Event.S3_OBJECT_CREATED,\nEvent.S3_OBJECT_TAGGING)\nS3 Event Notifications 443\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.queueArn(queueArn),\nqcb2 -> qcb2.<...>)\n.topicConfigurations(tcb -> tcb.<...>)\n.lambdaFunctionConfigurations(lfcb -> lfcb.<...>))\n.bucket(bucketName)\n);\nThe Code Examples GitHub repository contains the complete example to send S3 event\nnotifications directly to a queue.\nConfigure a bucket to send to EventBridge\nThe following example configures a bucket to send notifications to EventBridge.\npublic static String setBucketNotificationToEventBridge(String bucketName) {\n// Enable bucket to emit S3 Event notifications to EventBridge.\ns3Client.putBucketNotificationConfiguration(b -> b\n.bucket(bucketName)\n.notificationConfiguration(b1 -> b1\n.eventBridgeConfiguration(SdkBuilder::build))\n.build());\nWhen you configure a bucket to send events to EventBridge, you simply indicate the EventBridge\ndestination, not the types of events nor the ultimate destination that EventBridge will dispatch to.\nYou configure the ultimate targets and event types by using the Java SDK's EventBridge client.\nThe following code shows how to configure EventBridge to fan out object created events to a topic\nand a queue.\npublic static String configureEventBridge(String topicArn, String queueArn) {\ntry {\n// Create an EventBridge rule to route Object Created notifications.\nPutRuleRequest putRuleRequest = PutRuleRequest.builder()\n.name(RULE_NAME)\n.eventPattern(\"\"\"\n{\n\"source\": [\"aws.s3\"],\n\"detail-type\": [\"Object Created\"],\n\"detail\": {\n\"bucket\": {\n\"name\": [\"%s\"]\nS3 Event Notifications 444\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n}\n\"\"\".formatted(bucketName))\n.build();\n// Add the rule to the default event bus.\nPutRuleResponse putRuleResponse = eventBridgeClient.putRule(putRuleRequest)\n.whenComplete((r, t) -> {\nif (t != null) {\nlogger.error(\"Error creating event bus rule: \" +\nt.getMessage(), t);\nthrow new RuntimeException(t.getCause().getMessage(), t);\n}\nlogger.info(\"Event bus rule creation request sent successfully.\nARN is: {}\", r.ruleArn());\n}).join();\n// Add the existing SNS topic and SQS queue as targets to the rule.\neventBridgeClient.putTargets(b -> b\n.eventBusName(\"default\")\n.rule(RULE_NAME)\n.targets(List.of (\nTarget.builder()\n.arn(queueArn)\n.id(\"Queue\")\n.build(),\nTarget.builder()\n.arn(topicArn)\n.id(\"Topic\")\n.build())\n)\n).join();\nreturn putRuleResponse.ruleArn();\n} catch (S3Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn null;\n}\nTo work with EventBridge in your Java code, add a dependency on the eventbridge artifact to\nyour Maven pom.xml file.\nS3 Event Notifications 445\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\nsoftware.amazon.awssdk\neventbridge\n\nThe Code Examples GitHub repository contains the complete example to send S3 event\nnotifications to EventBridge and then to a topic and queue.\nUse the S3 Event Notifications API to process events\nAfter a destination receives S3 notification events, you can process them in an object-oriented\nway by using the S3 Event Notifications API. You can use the S3 Event Notifications API to work\nwith event notifications that are dispatched directly to a target (as shown in the first example),\nbut not with notifications routed through EventBridge. S3 event notifications sent by buckets to\nEventBridge contain a different structure that the S3 Event Notifications API does not currently\nhandle.\nAdd dependency\nThe S3 Event Notifications API was released with version 2.25.11 of the SDK for Java 2.x.\nTo use the S3 Event Notifications API, add the required dependency element to your Maven\npom.xml as shown in the following snippet.\n\n\n\nsoftware.amazon.awssdk\nbom\n1\n2.X.X \npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ns3-event-notifications\n\n\nS3 Event Notifications 446\nAWS SDK for Java 2.x Developer Guide for version 2.x\n1\nLatest version.", "mimetype": "text/plain", "start_char_idx": 734684, "end_char_idx": 739143, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5d22b188-7eb0-4210-963c-e00829c9886d": {"__data__": {"id_": "5d22b188-7eb0-4210-963c-e00829c9886d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1715c75c-23e9-4159-afee-a3f390a45650", "node_type": "1", "metadata": {}, "hash": "28ce83f8e090effbc78ab654aca06bd404cfde7f7e31ec01c430749f36c6fd44", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b8655aa6-0570-4b68-936f-c1398ef4bc33", "node_type": "1", "metadata": {}, "hash": "141589d5dc50da22c034778e803a6e2041d4416b851ec1524cbf61b2446ec80e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Add dependency\nThe S3 Event Notifications API was released with version 2.25.11 of the SDK for Java 2.x.\nTo use the S3 Event Notifications API, add the required dependency element to your Maven\npom.xml as shown in the following snippet.\n\n\n\nsoftware.amazon.awssdk\nbom\n1\n2.X.X \npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\ns3-event-notifications\n\n\nS3 Event Notifications 446\nAWS SDK for Java 2.x Developer Guide for version 2.x\n1\nLatest version.\nUse the S3EventNotification class\nCreate an S3EventNotification instance from a JSON string\nTo convert a JSON string into an S3EventNotification object, use the static methods of the\nS3EventNotification class as shown in the following example.\nimport software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification\nimport software.amazon.awssdk.eventnotifications.s3.model.S3EventNotificationRecord\nimport software.amazon.awssdk.services.sqs.model.Message;\npublic class S3EventNotificationExample {\n...\nvoid receiveMessage(Message message) {\n// Message received from SQSClient.\nString sqsEventBody = message.body();\nS3EventNotification s3EventNotification =\nS3EventNotification.fromJson(sqsEventBody);\n// Use getRecords() to access all the records in the notification.\nList records = s3EventNotification.getRecords();\nS3EventNotificationRecord record = records.stream().findFirst();\n// Use getters on the record to access individual attributes.\nString awsRegion = record.getAwsRegion();\nString eventName = record.getEventName();\nString eventSource = record.getEventSource();\n}\n}\nIn this example, the fromJson method converts the JSON string into an S3EventNotification\nobject. Missing fields in the JSON string will result in null values in the corresponding Java object\nfields and any extra fields in the JSON will be ignored.\nOther APIs for an event notification record can be found in API reference for\nS3EventNotificationRecord.\nS3 Event Notifications 447\nAWS SDK for Java 2.x Developer Guide for version 2.x\nConvert an S3EventNotification instance to a JSON string\nUse the toJson (or toJsonPretty) method to convert an S3EventNotification object into a\nJSON string as shown in the following example.\nimport software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification\npublic class S3EventNotificationExample {\n...\nvoid toJsonString(S3EventNotification event) {\nString json = event.toJson();\nString jsonPretty = event.toJsonPretty();\nSystem.out.println(\"JSON: \" + json);\nSystem.out.println(\"Pretty JSON: \" + jsonPretty);\n}\n}\nFields for GlacierEventData, ReplicationEventData, IntelligentTieringEventData,\nand LifecycleEventData are excluded from the JSON if they are null. Other null fields will\nbe serialized as null.\nThe following shows example output of the toJsonPretty method for an S3 object tagging\nevent.\n{\n\"Records\" : [ {\n\"eventVersion\" : \"2.3\",\n\"eventSource\" : \"aws:s3\",\n\"awsRegion\" : \"us-east-1\",\n\"eventTime\" : \"2024-07-19T20:09:18.551Z\",\n\"eventName\" : \"ObjectTagging:Put\",\n\"userIdentity\" : {\n\"principalId\" : \"AWS:XXXXXXXXXXX\"\n},\n\"requestParameters\" : {\n\"sourceIPAddress\" : \"XXX.XX.XX.XX\"\n},\n\"responseElements\" : {\n\"x-amz-request-id\" : \"XXXXXXXXXXXX\",\nS3 Event Notifications 448\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"x-amz-id-2\" : \"XXXXXXXXXXXXX\"\n},\n\"s3\" : {\n\"s3SchemaVersion\" : \"1.0\",\n\"configurationId\" : \"XXXXXXXXXXXXX\",\n\"bucket\" : {\n\"name\" : \"DOC-EXAMPLE-BUCKET\",\n\"ownerIdentity\" : {\n\"principalId\" : \"XXXXXXXXXXX\"\n},\n\"arn\" : \"arn:aws:s3:::XXXXXXXXXX\"\n},\n\"object\" : {\n\"key\" : \"akey\",\n\"size\" : null,\n\"eTag\" : \"XXXXXXXXXX\",\n\"versionId\" : null,\n\"sequencer\" : null\n}\n}\n} ]\n}\nA complete example is available in GitHub that shows how to use the API to work with notifications\nreceived by an Amazon SQS queue.\nWork with Amazon Simple Notification Service\nWith Amazon Simple Notification Service, you can easily push real-time notification messages from\nyour applications to subscribers over multiple communication channels.", "mimetype": "text/plain", "start_char_idx": 738418, "end_char_idx": 742637, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b8655aa6-0570-4b68-936f-c1398ef4bc33": {"__data__": {"id_": "b8655aa6-0570-4b68-936f-c1398ef4bc33", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5d22b188-7eb0-4210-963c-e00829c9886d", "node_type": "1", "metadata": {}, "hash": "488037455587c8a66a11094b1428a4311d5d891a23f9b5c1f2343a5a64bffbf2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fc4d5e6d-70a2-4427-9760-aee7faf62840", "node_type": "1", "metadata": {}, "hash": "9dbd22c893a2ee5af7ed2b38df6ef8fd17852e484515aac112ce271ce00282a9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Work with Amazon Simple Notification Service\nWith Amazon Simple Notification Service, you can easily push real-time notification messages from\nyour applications to subscribers over multiple communication channels. This topic describes how to\nperform some of the basic functions of Amazon SNS.\nCreate a topic\nA topic is a logical grouping of communication channels that defines which systems to send a\nmessage to, for example, fanning out a message to AWS Lambda and an HTTP webhook. You send\nmessages to Amazon SNS, then they\u2019re distributed to the channels defined in the topic. This makes\nthe messages available to subscribers.\nTo create a topic, first build a CreateTopicRequest object, with the name of the topic set using\nthe name() method in the builder. Then, send the request object to Amazon SNS by using\nAmazon SNS 449\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthe createTopic() method of the SnsClient. You can capture the result of this request as a\nCreateTopicResponse object, as demonstrated in the following code snippet.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.CreateTopicRequest;\nimport software.amazon.awssdk.services.sns.model.CreateTopicResponse;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nCode\npublic static String createSNSTopic(SnsClient snsClient, String topicName ) {\nCreateTopicResponse result = null;\ntry {\nCreateTopicRequest request = CreateTopicRequest.builder()\n.name(topicName)\n.build();\nresult = snsClient.createTopic(request);\nreturn result.topicArn();\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nSee the complete example on GitHub.\nList your Amazon SNS topics\nTo retrieve a list of your existing Amazon SNS topics, build a ListTopicsRequest object. Then, send\nthe request object to Amazon SNS by using the listTopics() method of the SnsClient. You\ncan capture the result of this request as a ListTopicsResponse object.\nThe following code snippet prints out the HTTP status code of the request and a list of Amazon\nResource Names (ARNs) for your Amazon SNS topics.\nList your Amazon SNS topics 450\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.ListTopicsRequest;\nimport software.amazon.awssdk.services.sns.model.ListTopicsResponse;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nCode\npublic static void listSNSTopics(SnsClient snsClient) {\ntry {\nListTopicsRequest request = ListTopicsRequest.builder()\n.build();\nListTopicsResponse result = snsClient.listTopics(request);\nSystem.out.println(\"Status was \" + result.sdkHttpResponse().statusCode() +\n\"\\n\\nTopics\\n\\n\" + result.topics());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nSubscribe an endpoint to a topic\nAfter you create a topic, you can configure which communication channels will be endpoints for\nthat topic. Messages are distributed to these endpoints after Amazon SNS receives them.\nTo configure a communication channel as an endpoint for a topic, subscribe that endpoint to the\ntopic. To start, build a SubscribeRequest object. Specify the communication channel (for example,\nlambda or email) as the protocol(). Set the endpoint() to the relevant output location (for\nexample, the ARN of a Lambda function or an email address), and then set the ARN of the topic\nto which you want to subscribe as the topicArn(). Send the request object to Amazon SNS by\nusing the subscribe() method of the SnsClient. You can capture the result of this request as a\nSubscribeResponse object.\nSubscribe an endpoint to a topic 451\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following code snippet shows how to subscribe an email address to a topic.", "mimetype": "text/plain", "start_char_idx": 742424, "end_char_idx": 746451, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fc4d5e6d-70a2-4427-9760-aee7faf62840": {"__data__": {"id_": "fc4d5e6d-70a2-4427-9760-aee7faf62840", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b8655aa6-0570-4b68-936f-c1398ef4bc33", "node_type": "1", "metadata": {}, "hash": "141589d5dc50da22c034778e803a6e2041d4416b851ec1524cbf61b2446ec80e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5dcc43c5-1af3-4255-93bf-bc5764e96422", "node_type": "1", "metadata": {}, "hash": "ea010fc62e855f6f7643c7e1e817030ca872cf087f0b260ab52414d4ec2ee42a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Messages are distributed to these endpoints after Amazon SNS receives them.\nTo configure a communication channel as an endpoint for a topic, subscribe that endpoint to the\ntopic. To start, build a SubscribeRequest object. Specify the communication channel (for example,\nlambda or email) as the protocol(). Set the endpoint() to the relevant output location (for\nexample, the ARN of a Lambda function or an email address), and then set the ARN of the topic\nto which you want to subscribe as the topicArn(). Send the request object to Amazon SNS by\nusing the subscribe() method of the SnsClient. You can capture the result of this request as a\nSubscribeResponse object.\nSubscribe an endpoint to a topic 451\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following code snippet shows how to subscribe an email address to a topic.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nimport software.amazon.awssdk.services.sns.model.SubscribeRequest;\nimport software.amazon.awssdk.services.sns.model.SubscribeResponse;\nCode\npublic static void subEmail(SnsClient snsClient, String topicArn, String email) {\ntry {\nSubscribeRequest request = SubscribeRequest.builder()\n.protocol(\"email\")\n.endpoint(email)\n.returnSubscriptionArn(true)\n.topicArn(topicArn)\n.build();\nSubscribeResponse result = snsClient.subscribe(request);\nSystem.out.println(\"Subscription ARN: \" + result.subscriptionArn() + \"\\n\\n\nStatus is \" + result.sdkHttpResponse().statusCode());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nPublish a message to a topic\nAfter you have a topic and one or more endpoints configured for it, you can publish a message\nto it. To start, build a PublishRequest object. Specify the message() to send, and the ARN of\nthe topic (topicArn()) to send it to. Then, send the request object to Amazon SNS by using\nthe publish() method of the SnsClient. You can capture the result of this request as a\nPublishResponse object.\nPublish a message to a topic 452\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.PublishRequest;\nimport software.amazon.awssdk.services.sns.model.PublishResponse;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nCode\npublic static void pubTopic(SnsClient snsClient, String message, String topicArn) {\ntry {\nPublishRequest request = PublishRequest.builder()\n.message(message)\n.topicArn(topicArn)\n.build();\nPublishResponse result = snsClient.publish(request);\nSystem.out.println(result.messageId() + \" Message sent. Status is \" +\nresult.sdkHttpResponse().statusCode());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nUnsubscribe an endpoint from a topic\nYou can remove the communication channels configured as endpoints for a topic. After doing that,\nthe topic itself continues to exist and distribute messages to any other endpoints configured for\nthat topic.\nTo remove a communication channel as an endpoint for a topic, unsubscribe that endpoint from\nthe topic. To start, build an UnsubscribeRequest object and set the ARN of the topic you want to\nunsubscribe from as the subscriptionArn(). Then send the request object to SNS by using\nthe unsubscribe() method of the SnsClient. You can capture the result of this request as an\nUnsubscribeResponse object.\nUnsubscribe an endpoint from a topic 453\nAWS SDK for Java 2.x Developer Guide for version 2.x\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nimport software.amazon.awssdk.services.sns.model.UnsubscribeRequest;\nimport software.amazon.awssdk.services.sns.model.UnsubscribeResponse;\nCode\npublic static void unSub(SnsClient snsClient, String subscriptionArn) {\ntry {\nUnsubscribeRequest request = UnsubscribeRequest.builder()\n.subscriptionArn(subscriptionArn)\n.build();\nUnsubscribeResponse result = snsClient.unsubscribe(request);\nSystem.out.println(\"\\n\\nStatus was \" +\nresult.sdkHttpResponse().statusCode()\n+ \"\\n\\nSubscription was removed for \" + request.subscriptionArn());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.", "mimetype": "text/plain", "start_char_idx": 745615, "end_char_idx": 750202, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5dcc43c5-1af3-4255-93bf-bc5764e96422": {"__data__": {"id_": "5dcc43c5-1af3-4255-93bf-bc5764e96422", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fc4d5e6d-70a2-4427-9760-aee7faf62840", "node_type": "1", "metadata": {}, "hash": "9dbd22c893a2ee5af7ed2b38df6ef8fd17852e484515aac112ce271ce00282a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7340accf-7384-4a05-b5c6-6aeee6b4b50c", "node_type": "1", "metadata": {}, "hash": "3776677eda435cf3b556f86b3272cd7af5d1bc30bc38aef4f6171da59dafd5fd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Delete a topic\nTo delete an Amazon SNS topic, first build a DeleteTopicRequest object with the ARN of the topic\nset as the topicArn() method in the builder. Then send the request object to Amazon SNS by\nusing the deleteTopic() method of the SnsClient. You can capture the result of this request\nas a DeleteTopicResponse object, as demonstrated in the following code snippet.\nImports\nimport software.amazon.awssdk.regions.Region;\nDelete a topic 454\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.sns.SnsClient;\nimport software.amazon.awssdk.services.sns.model.DeleteTopicRequest;\nimport software.amazon.awssdk.services.sns.model.DeleteTopicResponse;\nimport software.amazon.awssdk.services.sns.model.SnsException;\nCode\npublic static void deleteSNSTopic(SnsClient snsClient, String topicArn ) {\ntry {\nDeleteTopicRequest request = DeleteTopicRequest.builder()\n.topicArn(topicArn)\n.build();\nDeleteTopicResponse result = snsClient.deleteTopic(request);\nSystem.out.println(\"\\n\\nStatus was \" +\nresult.sdkHttpResponse().statusCode());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nFor more information, see the Amazon Simple Notification Service Developer Guide.\nWork with Amazon Simple Queue Service\nThis section provides examples of programming Amazon Simple Queue Service using the AWS SDK\nfor Java 2.x.\nThe following examples include only the code needed to demonstrate each technique. The\ncomplete example code is available on GitHub. From there, you can download a single source file or\nclone the repository locally to get all the examples to build and run.\nTopics\n\u2022 Use automatic request batching for Amazon SQS with the AWS SDK for Java 2.x\n\u2022 Work with Amazon Simple Queue Service message queues\nAmazon SQS 455\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Send, receive, and delete Amazon Simple Queue Service messages\nUse automatic request batching for Amazon SQS with the AWS SDK for\nJava 2.x\nThe Automatic Request Batching API for Amazon SQS is a high-level library that provides an\nefficient way to batch and buffer requests for SQS operations. By using the batching API, you\nreduce the number of requests to SQS, which improves throughput and minimizes costs.\nBecause the batch API methods match the SqsAsyncClient methods\u2014sendMessage,\nchangeMessageVisibility, deleteMessage, receiveMessage\u2014you can use the batch API as\na drop-in replacement with minimal changes.\nThis topic gives you an overview of how to configure and work with the Automatic Request\nBatching API for Amazon SQS.\nCheck prerequisites\nYou need to use version 2.28.0 or later of the SDK for Java 2.x to have access to the batching API.\nYour Maven pom.xml should at least contain the following elements.\n\n\n\nsoftware.amazon.awssdk\nbom\n1\n2.28.23 \npom\nimport\n\n\n\n\n\nsoftware.amazon.awssdk\nsqs\n\n\n1\nLatest version\nUse automatic request batching 456\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a batch manager\nThe automatic request batching API is implemented by the SqsAsyncBatchManager interface. You\ncan create an instance of the manager a couple ways.\nDefault configuration by using SqsAsyncClient\nThe simplest way you can create a batch manager is to call the batchManager factory method on\nan existing SqsAsyncClient instance. The simple approach is shown in the following snippet.\nSqsAsyncClient asyncClient = SqsAsyncClient.create();\nSqsAsyncBatchManager sqsAsyncBatchManager = asyncClient.batchManager();\nWhen you use this approach, the SqsAsyncBatchManager instance uses the default values that\nare shown in the table in the the section called \u201cConfiguration settings\u201d section. Additionally, the\nSqsAsyncBatchManager instance uses the ExecutorService of the SqsAsyncClient instance\nthat it was created from.\nCustom configuration by using SqsAsyncBatchManager.Builder\nFor more advanced use cases, you can customize the batch manager using the\nSqsAsyncBatchManager.Builder. By using this approach to create a SqsAsyncBatchManager\ninstance, you can fine tune the batching behavior. The following snippet shows an example of how\nto use the builder to customize batching behavior.", "mimetype": "text/plain", "start_char_idx": 750203, "end_char_idx": 754701, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7340accf-7384-4a05-b5c6-6aeee6b4b50c": {"__data__": {"id_": "7340accf-7384-4a05-b5c6-6aeee6b4b50c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5dcc43c5-1af3-4255-93bf-bc5764e96422", "node_type": "1", "metadata": {}, "hash": "ea010fc62e855f6f7643c7e1e817030ca872cf087f0b260ab52414d4ec2ee42a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "77173165-39aa-4b8e-83cf-f775766917b2", "node_type": "1", "metadata": {}, "hash": "7ccc6bcee3b770cfc282d89bb3214631426b09f008df0929b96126e044f9e0dc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The simple approach is shown in the following snippet.\nSqsAsyncClient asyncClient = SqsAsyncClient.create();\nSqsAsyncBatchManager sqsAsyncBatchManager = asyncClient.batchManager();\nWhen you use this approach, the SqsAsyncBatchManager instance uses the default values that\nare shown in the table in the the section called \u201cConfiguration settings\u201d section. Additionally, the\nSqsAsyncBatchManager instance uses the ExecutorService of the SqsAsyncClient instance\nthat it was created from.\nCustom configuration by using SqsAsyncBatchManager.Builder\nFor more advanced use cases, you can customize the batch manager using the\nSqsAsyncBatchManager.Builder. By using this approach to create a SqsAsyncBatchManager\ninstance, you can fine tune the batching behavior. The following snippet shows an example of how\nto use the builder to customize batching behavior.\nSqsAsyncBatchManager batchManager = SqsAsyncBatchManager.builder()\n.client(SqsAsyncClient.create())\n.scheduledExecutor(Executors.newScheduledThreadPool(5))\n.overrideConfiguration(b -> b\n.receiveMessageMinWaitDuration(Duration.ofSeconds(10))\n.receiveMessageVisibilityTimeout(Duration.ofSeconds(1))\n.receiveMessageAttributeNames(Collections.singletonList(\"*\"))\n.receiveMessageSystemAttributeNames(Collections.singletonList(MessageSystemAttributeName.ALL)))\n.build();\nWhen you use this approach, you can adjust the settings on the BatchOverrideConfiguration\nobject that are shown in the table in the the section called \u201cConfiguration settings\u201d section. You\ncan also provide a custom ScheduledExecutorService for the batch manager by using this\napproach.\nUse automatic request batching 457\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSend messages\nTo send messages with the batch manager, use the SqsAsyncBatchManager#sendMessage\nmethod. The SDK buffers requests and sends them as a batch when the maxBatchSize or\nsendRequestFrequency values are reached.\nThe following example show a sendMessage request immediately following by another request. In\nthis case, the SDK sends both messages in a single batch.\n// Sending the first message\nCompletableFuture futureOne =\nsqsAsyncBatchManager.sendMessage(r -> r.messageBody(\"One\").queueUrl(\"queue\"));\n// Sending the second message\nCompletableFuture futureTwo =\nsqsAsyncBatchManager.sendMessage(r -> r.messageBody(\"Two\").queueUrl(\"queue\"));\n// Waiting for both futures to complete and retrieving the responses\nSendMessageResponse messageOne = futureOne.join();\nSendMessageResponse messageTwo = futureTwo.join();\nChange the message visibility timeout\nYou can change the visibility timeout of messages in a batch by using the\nSqsAsyncBatchManager#changeMessageVisibility method. The SDK buffers requests and\nsends them as a batch when the maxBatchSize or sendRequestFrequency values are reached.\nThe following example shows how to call the changeMessageVisibility method.\nCompletableFuture futureOne =\nsqsAsyncBatchManager.changeMessageVisibility(r ->\nr.receiptHandle(\"receiptHandle\")\n.queueUrl(\"queue\"));\nChangeMessageVisibilityResponse response = futureOne.join();\nDelete messages\nYou can delete messages in a batch using the SqsAsyncBatchManager#deleteMessage\nmethod. The SDK buffers requests and sends them as a batch when the maxBatchSize or\nsendRequestFrequency values are reached.\nThe following example shows how you can call the deleteMessage method.\nUse automatic request batching 458\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture futureOne =\nsqsAsyncBatchManager.deleteMessage(r ->\nr.receiptHandle(\"receiptHandle\")\n.queueUrl(\"queue\"));\nDeleteMessageResponse response = futureOne.join();\nReceive messages\nUse default settings\nWhen you poll the SqsAsyncBatchManager#receiveMessage method in your application, the\nbatch manager fetches messages from its internal buffer, which the SDK automatically updates in\nthe background.\nThe following example shows how to call the receiveMessage method.\nCompletableFuture responseFuture =\nsqsAsyncBatchManager.receiveMessage(r -> r.queueUrl(\"queueUrl\"));\nUse custom settings\nIf you want to customize the request further, for example by setting custom wait times and\nspecifying the number of messages to retrieve, you can customize the request as shown in the\nfollowing example.", "mimetype": "text/plain", "start_char_idx": 753849, "end_char_idx": 758218, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "77173165-39aa-4b8e-83cf-f775766917b2": {"__data__": {"id_": "77173165-39aa-4b8e-83cf-f775766917b2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7340accf-7384-4a05-b5c6-6aeee6b4b50c", "node_type": "1", "metadata": {}, "hash": "3776677eda435cf3b556f86b3272cd7af5d1bc30bc38aef4f6171da59dafd5fd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "827e424d-d993-45f9-b478-c1335e68ca4e", "node_type": "1", "metadata": {}, "hash": "0e71f3972b67532a8481a284125ac6a52821ac164c4a1b18ec945d46fa3b2979", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use automatic request batching 458\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture futureOne =\nsqsAsyncBatchManager.deleteMessage(r ->\nr.receiptHandle(\"receiptHandle\")\n.queueUrl(\"queue\"));\nDeleteMessageResponse response = futureOne.join();\nReceive messages\nUse default settings\nWhen you poll the SqsAsyncBatchManager#receiveMessage method in your application, the\nbatch manager fetches messages from its internal buffer, which the SDK automatically updates in\nthe background.\nThe following example shows how to call the receiveMessage method.\nCompletableFuture responseFuture =\nsqsAsyncBatchManager.receiveMessage(r -> r.queueUrl(\"queueUrl\"));\nUse custom settings\nIf you want to customize the request further, for example by setting custom wait times and\nspecifying the number of messages to retrieve, you can customize the request as shown in the\nfollowing example.\nCompletableFuture response =\nsqsAsyncBatchManager.receiveMessage(r ->\nr.queueUrl(\"queueUrl\")\n.waitTimeSeconds(5)\n.visibilityTimeout(20));\nNote\nIf you call receiveMessage with a ReceiveMessageRequest that includes any of\nthe following parameters, the SDK bypasses the batch manager and sends a regular\nasynchronous receiveMessage request:\n\u2022 messageAttributeNames\n\u2022 messageSystemAttributeNames\n\u2022 messageSystemAttributeNamesWithStrings\nUse automatic request batching 459\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 overrideConfiguration\nOverride configuration settings for SqsAsyncBatchManager\nYou can adjust the following settings when you create an SqsAsyncBatchManager instance. The\nfollowing list of settings are available on the BatchOverrideConfiguration.Builder.\nSetting Description Default value\nmaxBatchSize Maximum number of 10\nrequest per batch for each\nSendMessageBatchRe\nquest , ChangeMes\nsageVisibilityBatc\nhRequest , or DeleteMes\nsageBatchRequest . The\nmaximum value is 10.\nsendRequestFrequency Time before sending a batch, 200ms\nunless maxBatchSize is\nreached earlier. Higher values\nmay reduce requests but\nincrease latency.\nreceiveMessageVisi Visibility timeout for Queue's default\nbilityTimeout messages. If unset, the\nqueue's default is used.\nreceiveMessageMinW Minimum wait time for 50ms\naitDuration receiveMessage requests.\nAvoid setting to 0 to prevent\nCPU waste.\nreceiveMessageSyst List of system attribute None\nemAttributeNames names to request for\nreceiveMessage calls.\nUse automatic request batching 460\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSetting Description Default value\nreceiveMessageAttr List of attribute names to None\nibuteNames request for receiveMe\nssage calls.\nWork with Amazon Simple Queue Service message queues\nA message queue is the logical container used for sending messages reliably in Amazon Simple\nQueue Service. There are two types of queues: standard and first-in, first-out (FIFO). To learn more\nabout queues and the differences between these types, see the Amazon Simple Queue Service\nDeveloper Guide.\nThis topic describes how to create, list, delete, and get the URL of an Amazon Simple Queue\nService queue by using the AWS SDK for Java.\nThe sqsClient variable that is used in the following examples can be created from the following\nsnippet.\nSqsClient sqsClient = SqsClient.create();\nWhen you create an SqsClient by using the static create() method, the SDK configures\nthe Region by using the default region provider chain and the credentials by using the default\ncredentials provider chain.\nCreate a queue\nUse the SqsClient\u2019s createQueue method, and provide a CreateQueueRequest object that\ndescribes the queue parameters as shown in the following code snippet.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\nQueue operations 461\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateQueueRequest createQueueRequest = CreateQueueRequest.builder()\n.queueName(queueName)\n.build();\nsqsClient.createQueue(createQueueRequest);\nSee the complete sample on GitHub.\nList queues\nTo list the Amazon Simple Queue Service queues for your account, call the SqsClient\u2019s\nlistQueues method with a ListQueuesRequest object.\nWhen you use the form of the listQueues method that takes no parameters, the service returns\nall queues\u2014up to 1,000 queues.\nYou can supply a queue name prefix to the ListQueuesRequest object to limit the results to\nqueues that match that prefix as shown in the following code.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.", "mimetype": "text/plain", "start_char_idx": 757282, "end_char_idx": 762006, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "827e424d-d993-45f9-b478-c1335e68ca4e": {"__data__": {"id_": "827e424d-d993-45f9-b478-c1335e68ca4e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "77173165-39aa-4b8e-83cf-f775766917b2", "node_type": "1", "metadata": {}, "hash": "7ccc6bcee3b770cfc282d89bb3214631426b09f008df0929b96126e044f9e0dc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "75c7b6b3-8f00-40ef-8980-daced5ea1e29", "node_type": "1", "metadata": {}, "hash": "9e8b911c51a3033ab3f8d232c00dd7829a6195e202f5194fc99c6a417531f4d6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*;\nimport java.util.List;\nCode\nQueue operations 461\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateQueueRequest createQueueRequest = CreateQueueRequest.builder()\n.queueName(queueName)\n.build();\nsqsClient.createQueue(createQueueRequest);\nSee the complete sample on GitHub.\nList queues\nTo list the Amazon Simple Queue Service queues for your account, call the SqsClient\u2019s\nlistQueues method with a ListQueuesRequest object.\nWhen you use the form of the listQueues method that takes no parameters, the service returns\nall queues\u2014up to 1,000 queues.\nYou can supply a queue name prefix to the ListQueuesRequest object to limit the results to\nqueues that match that prefix as shown in the following code.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\nString prefix = \"que\";\ntry {\nListQueuesRequest listQueuesRequest =\nListQueuesRequest.builder().queueNamePrefix(prefix).build();\nListQueuesResponse listQueuesResponse =\nsqsClient.listQueues(listQueuesRequest);\nfor (String url : listQueuesResponse.queueUrls()) {\nSystem.out.println(url);\n}\n} catch (SqsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nQueue operations 462\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\nSee the complete sample on GitHub.\nGet the URL for a queue\nThe following code shows how to get the URL for a queue by calling the SqsClient\u2019s\ngetQueueUrl method with a GetQueueUrlRequest object.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\nGetQueueUrlResponse getQueueUrlResponse =\nsqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());\nString queueUrl = getQueueUrlResponse.queueUrl();\nreturn queueUrl;\nSee the complete sample on GitHub.\nDelete a queue\nProvide the queue\u2019s URL to the DeleteQueueRequest object. Then call the SqsClient\u2019s\ndeleteQueue method to delete a queue as shown in the following code.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\npublic static void deleteSQSQueue(SqsClient sqsClient, String queueName) {\nQueue operations 463\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nGetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()\n.queueName(queueName)\n.build();\nString queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();\nDeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()\n.queueUrl(queueUrl)\n.build();\nsqsClient.deleteQueue(deleteQueueRequest);\n} catch (SqsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete sample on GitHub.\nMore information\n\u2022 CreateQueue in the Amazon Simple Queue Service API Reference\n\u2022 GetQueueUrl in the Amazon Simple Queue Service API Reference\n\u2022 ListQueues in the Amazon Simple Queue Service API Reference\n\u2022 DeleteQueue in the Amazon Simple Queue Service API Reference\nSend, receive, and delete Amazon Simple Queue Service messages\nA message is a piece of data that can be sent and received by distributed components. Messages\nare always delivered using an SQS Queue.\nThe sqsClient variable that is used in the following examples can be created from the following\nsnippet.\nSqsClient sqsClient = SqsClient.create();\nMessage operations 464\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWhen you create an SqsClient by using the static create() method, the SDK configures\nthe Region by using the default region provider chain and the credentials by using the default\ncredentials provider chain.\nSend a message\nAdd a single message to an Amazon Simple Queue Service queue by calling the SqsClient client\nsendMessage method. Provide a SendMessageRequest object that contains the queue\u2019s URL,\nmessage body, and optional delay value (in seconds).\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\nsqsClient.sendMessage(SendMessageRequest.builder()\n.queueUrl(queueUrl)\n.messageBody(\"Hello world!\")", "mimetype": "text/plain", "start_char_idx": 761139, "end_char_idx": 765500, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "75c7b6b3-8f00-40ef-8980-daced5ea1e29": {"__data__": {"id_": "75c7b6b3-8f00-40ef-8980-daced5ea1e29", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "827e424d-d993-45f9-b478-c1335e68ca4e", "node_type": "1", "metadata": {}, "hash": "0e71f3972b67532a8481a284125ac6a52821ac164c4a1b18ec945d46fa3b2979", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f24a8807-5fed-44e7-b5e6-c555740fdeda", "node_type": "1", "metadata": {}, "hash": "1048ebe07900ddd345dff3f4bbba963258f7c9c329b0803732cc7c1b5a1f1b7b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SqsClient sqsClient = SqsClient.create();\nMessage operations 464\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWhen you create an SqsClient by using the static create() method, the SDK configures\nthe Region by using the default region provider chain and the credentials by using the default\ncredentials provider chain.\nSend a message\nAdd a single message to an Amazon Simple Queue Service queue by calling the SqsClient client\nsendMessage method. Provide a SendMessageRequest object that contains the queue\u2019s URL,\nmessage body, and optional delay value (in seconds).\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\nsqsClient.sendMessage(SendMessageRequest.builder()\n.queueUrl(queueUrl)\n.messageBody(\"Hello world!\")\n.delaySeconds(10)\n.build());\nsqsClient.sendMessage(sendMsgRequest);\nSend multiple messages in a request\nSend more than one message in a single request by using the SqsClient sendMessageBatch\nmethod. This method takes a SendMessageBatchRequest that contains the queue URL and a list of\nmessages to send. (Each message is a SendMessageBatchRequestEntry.) You can also delay sending\na specific message by setting a delay value on the message.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nMessage operations 465\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCode\nSendMessageBatchRequest sendMessageBatchRequest =\nSendMessageBatchRequest.builder()\n.queueUrl(queueUrl)\n.entries(SendMessageBatchRequestEntry.builder().id(\"id1\").messageBody(\"Hello from msg\n1\").build(),\nSendMessageBatchRequestEntry.builder().id(\"id2\").messageBody(\"msg\n2\").delaySeconds(10).build())\n.build();\nsqsClient.sendMessageBatch(sendMessageBatchRequest);\nSee the complete sample on GitHub.\nRetrieve Messages\nRetrieve any messages that are currently in the queue by calling the SqsClient receiveMessage\nmethod. This method takes a ReceiveMessageRequest that contains the queue URL. You can also\nspecify the maximum number of messages to return. Messages are returned as a list of Message\nobjects.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\ntry {\nReceiveMessageRequest receiveMessageRequest =\nReceiveMessageRequest.builder()\n.queueUrl(queueUrl)\n.maxNumberOfMessages(5)\n.build();\nList messages =\nsqsClient.receiveMessage(receiveMessageRequest).messages();\nreturn messages;\n} catch (SqsException e) {\nMessage operations 466\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn null;\nSee the complete sample on GitHub.\nDelete a message after receipt\nAfter receiving a message and processing its contents, delete the message from the queue by\nsending the message's receipt handle and queue URL to the SqsClient's deleteMessage\nmethod.\nImports\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\nCode\ntry {\nfor (Message message : messages) {\nDeleteMessageRequest deleteMessageRequest =\nDeleteMessageRequest.builder()\n.queueUrl(queueUrl)\n.receiptHandle(message.receiptHandle())\n.build();\nsqsClient.deleteMessage(deleteMessageRequest);\n}\nSee the complete sample on GitHub.\nMore Info\n\u2022 How Amazon Simple Queue Service Queues Work in the Amazon Simple Queue Service\nDeveloper Guide\n\u2022 SendMessage in the Amazon Simple Queue Service API Reference\n\u2022 SendMessageBatch in the Amazon Simple Queue Service API Reference\nMessage operations 467\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 ReceiveMessage in the Amazon Simple Queue Service API Reference\n\u2022 DeleteMessage in the Amazon Simple Queue Service API Reference\nWork with Amazon Transcribe\nThe following example shows how bidirectional streaming works using Amazon Transcribe.\nBidirectional streaming implies that there\u2019s both a stream of data going to the service and being\nreceived back in real time. The example uses Amazon Transcribe streaming transcription to send an\naudio stream and receive a stream of transcribed text back in real time.\nSee Streaming Transcription in the Amazon Transcribe Developer Guide to learn more about this\nfeature.\nSee Getting Started in the Amazon Transcribe Developer Guide to get started using Amazon\nTranscribe.\nSet up the microphone\nThis code uses the javax.sound.sampled package to stream audio from an input device.", "mimetype": "text/plain", "start_char_idx": 764639, "end_char_idx": 769373, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f24a8807-5fed-44e7-b5e6-c555740fdeda": {"__data__": {"id_": "f24a8807-5fed-44e7-b5e6-c555740fdeda", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "75c7b6b3-8f00-40ef-8980-daced5ea1e29", "node_type": "1", "metadata": {}, "hash": "9e8b911c51a3033ab3f8d232c00dd7829a6195e202f5194fc99c6a417531f4d6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "885992aa-525c-4d3a-9b3f-04c6c3f6b0d3", "node_type": "1", "metadata": {}, "hash": "b8984b0d227a61994ce3fad5b8c3d0203da03f2c6cb78e85a4ba57db9ed7e35d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Bidirectional streaming implies that there\u2019s both a stream of data going to the service and being\nreceived back in real time. The example uses Amazon Transcribe streaming transcription to send an\naudio stream and receive a stream of transcribed text back in real time.\nSee Streaming Transcription in the Amazon Transcribe Developer Guide to learn more about this\nfeature.\nSee Getting Started in the Amazon Transcribe Developer Guide to get started using Amazon\nTranscribe.\nSet up the microphone\nThis code uses the javax.sound.sampled package to stream audio from an input device.\nCode\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nimport javax.sound.sampled.TargetDataLine;\npublic class Microphone {\npublic static TargetDataLine get() throws Exception {\nAudioFormat format = new AudioFormat(16000, 16, 1, true, false);\nDataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format);\nTargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo);\ndataLine.open(format);\nreturn dataLine;\n}\n}\nSee the complete example on GitHub.\nAmazon Transcribe 468\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a publisher\nThis code implements a publisher that publishes audio data from the Amazon Transcribe audio\nstream.\nCode\npackage com.amazonaws.transcribe;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UncheckedIOException;\nimport java.nio.ByteBuffer;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.atomic.AtomicLong;\nimport org.reactivestreams.Publisher;\nimport org.reactivestreams.Subscriber;\nimport org.reactivestreams.Subscription;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.services.transcribestreaming.model.AudioEvent;\nimport software.amazon.awssdk.services.transcribestreaming.model.AudioStream;\nimport\nsoftware.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException;\npublic class AudioStreamPublisher implements Publisher {\nprivate final InputStream inputStream;\npublic AudioStreamPublisher(InputStream inputStream) {\nthis.inputStream = inputStream;\n}\n@Override\npublic void subscribe(Subscriber s) {\ns.onSubscribe(new SubscriptionImpl(s, inputStream));\n}\nprivate class SubscriptionImpl implements Subscription {\nprivate static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;\nprivate ExecutorService executor = Executors.newFixedThreadPool(1);\nprivate AtomicLong demand = new AtomicLong(0);\nCreate a publisher 469\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate final Subscriber subscriber;\nprivate final InputStream inputStream;\nprivate SubscriptionImpl(Subscriber s, InputStream\ninputStream) {\nthis.subscriber = s;\nthis.inputStream = inputStream;\n}\n@Override\npublic void request(long n) {\nif (n <= 0) {\nsubscriber.onError(new IllegalArgumentException(\"Demand must be\npositive\"));\n}\ndemand.getAndAdd(n);\nexecutor.submit(() -> {\ntry {\ndo {\nByteBuffer audioBuffer = getNextEvent();\nif (audioBuffer.remaining() > 0) {\nAudioEvent audioEvent = audioEventFromBuffer(audioBuffer);\nsubscriber.onNext(audioEvent);\n} else {\nsubscriber.onComplete();\nbreak;\n}\n} while (demand.decrementAndGet() > 0);\n} catch (TranscribeStreamingException e) {\nsubscriber.onError(e);\n}\n});\n}\n@Override\npublic void cancel() {\n}\nprivate ByteBuffer getNextEvent() {\nByteBuffer audioBuffer;\nbyte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];\nCreate a publisher 470\nAWS SDK for Java 2.x Developer Guide for version 2.x\nint len = 0;\ntry {\nlen = inputStream.read(audioBytes);\nif (len <= 0) {\naudioBuffer = ByteBuffer.allocate(0);\n} else {\naudioBuffer = ByteBuffer.wrap(audioBytes, 0, len);\n}\n} catch (IOException e) {\nthrow new UncheckedIOException(e);\n}\nreturn audioBuffer;\n}\nprivate AudioEvent audioEventFromBuffer(ByteBuffer bb) {\nreturn AudioEvent.builder()\n.audioChunk(SdkBytes.fromByteBuffer(bb))\n.build();\n}\n}\n}\nSee the complete example on GitHub.\nCreate the client and start the stream\nIn the main method, create a request object, start the audio input stream and instantiate the\npublisher with the audio input.\nYou must also create a StartStreamTranscriptionResponseHandler to specify how to handle the\nresponse from Amazon Transcribe.\nThen, use the TranscribeStreamingAsyncClient\u2019s startStreamTranscription method to start\nthe bidirectional streaming.", "mimetype": "text/plain", "start_char_idx": 768794, "end_char_idx": 773258, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "885992aa-525c-4d3a-9b3f-04c6c3f6b0d3": {"__data__": {"id_": "885992aa-525c-4d3a-9b3f-04c6c3f6b0d3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f24a8807-5fed-44e7-b5e6-c555740fdeda", "node_type": "1", "metadata": {}, "hash": "1048ebe07900ddd345dff3f4bbba963258f7c9c329b0803732cc7c1b5a1f1b7b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "deeafbc1-5166-4acd-9e80-c2161448398c", "node_type": "1", "metadata": {}, "hash": "4c5a4c3d53ba58b0996c830caf4a7c30a6ad859d1ae780db16376ba3b309900a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Create the client and start the stream\nIn the main method, create a request object, start the audio input stream and instantiate the\npublisher with the audio input.\nYou must also create a StartStreamTranscriptionResponseHandler to specify how to handle the\nresponse from Amazon Transcribe.\nThen, use the TranscribeStreamingAsyncClient\u2019s startStreamTranscription method to start\nthe bidirectional streaming.\nImports\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nCreate the client and start the stream 471\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport javax.sound.sampled.TargetDataLine;\nimport javax.sound.sampled.AudioInputStream;\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient;\nimport\nsoftware.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException ;\nimport\nsoftware.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest;\nimport software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding;\nimport software.amazon.awssdk.services.transcribestreaming.model.LanguageCode;\nimport\nsoftware.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler;\nimport software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent;\nCode\npublic static void convertAudio(TranscribeStreamingAsyncClient client) throws\nException {\ntry {\nStartStreamTranscriptionRequest request =\nStartStreamTranscriptionRequest.builder()\n.mediaEncoding(MediaEncoding.PCM)\n.languageCode(LanguageCode.EN_US)\n.mediaSampleRateHertz(16_000).build();\nTargetDataLine mic = Microphone.get();\nmic.start();\nAudioStreamPublisher publisher = new AudioStreamPublisher(new\nAudioInputStream(mic));\nStartStreamTranscriptionResponseHandler response =\nStartStreamTranscriptionResponseHandler.builder().subscriber(e -> {\nTranscriptEvent event = (TranscriptEvent) e;\nevent.transcript().results().forEach(r ->\nr.alternatives().forEach(a -> System.out.println(a.transcript())));\n}).build();\n// Keeps Streaming until you end the Java program\nclient.startStreamTranscription(request, publisher, response);\nCreate the client and start the stream 472\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (TranscribeStreamingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nSee the complete example on GitHub.\nMore information\n\u2022 How It Works in the Amazon Transcribe Developer Guide.\n\u2022 Getting Started With Streaming Audio in the Amazon Transcribe Developer Guide.\nMore information 473\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x code examples\nThe code examples in this topic show you how to use the AWS SDK for Java 2.x with AWS.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nSome services contain additional example categories that show how to leverage libraries or\nfunctions specific to the service.\nServices\n\u2022 ACM examples using SDK for Java 2.x\n\u2022 API Gateway examples using SDK for Java 2.x\n\u2022 Application Auto Scaling examples using SDK for Java 2.x\n\u2022 Application Recovery Controller examples using SDK for Java 2.x\n\u2022 Aurora examples using SDK for Java 2.x\n\u2022 Auto Scaling examples using SDK for Java 2.x\n\u2022 AWS Batch examples using SDK for Java 2.x\n\u2022 Amazon Bedrock examples using SDK for Java 2.x\n\u2022 Amazon Bedrock Runtime examples using SDK for Java 2.x\n\u2022 CloudFront examples using SDK for Java 2.x\n\u2022 CloudWatch examples using SDK for Java 2.x\n\u2022 CloudWatch Events examples using SDK for Java 2.x\n\u2022 CloudWatch Logs examples using SDK for Java 2.x\n\u2022 Amazon Cognito Identity examples using SDK for Java 2.x\n\u2022 Amazon Cognito Identity Provider examples using SDK for Java 2.x\n\u2022 Amazon Comprehend examples using SDK for Java 2.x\n474\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Firehose examples using SDK for Java 2.x\n\u2022 Amazon DocumentDB examples using SDK for Java 2.x\n\u2022 DynamoDB examples using SDK for Java 2.x\n\u2022 Amazon EC2 examples using SDK for Java 2.x\n\u2022 Amazon ECR examples using SDK for Java 2.x\n\u2022 Amazon ECS examples using SDK for Java 2.", "mimetype": "text/plain", "start_char_idx": 772852, "end_char_idx": 777407, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "deeafbc1-5166-4acd-9e80-c2161448398c": {"__data__": {"id_": "deeafbc1-5166-4acd-9e80-c2161448398c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "885992aa-525c-4d3a-9b3f-04c6c3f6b0d3", "node_type": "1", "metadata": {}, "hash": "b8984b0d227a61994ce3fad5b8c3d0203da03f2c6cb78e85a4ba57db9ed7e35d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "54c38f20-5dc3-47fd-bf12-5d382a9d7c88", "node_type": "1", "metadata": {}, "hash": "21670a3b6c83cf33772a5afa21361f0c2938c093fb8972bd3c0e850864b8ce0e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "x\n\u2022 CloudWatch examples using SDK for Java 2.x\n\u2022 CloudWatch Events examples using SDK for Java 2.x\n\u2022 CloudWatch Logs examples using SDK for Java 2.x\n\u2022 Amazon Cognito Identity examples using SDK for Java 2.x\n\u2022 Amazon Cognito Identity Provider examples using SDK for Java 2.x\n\u2022 Amazon Comprehend examples using SDK for Java 2.x\n474\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Firehose examples using SDK for Java 2.x\n\u2022 Amazon DocumentDB examples using SDK for Java 2.x\n\u2022 DynamoDB examples using SDK for Java 2.x\n\u2022 Amazon EC2 examples using SDK for Java 2.x\n\u2022 Amazon ECR examples using SDK for Java 2.x\n\u2022 Amazon ECS examples using SDK for Java 2.x\n\u2022 Elastic Load Balancing - Version 2 examples using SDK for Java 2.x\n\u2022 MediaStore examples using SDK for Java 2.x\n\u2022 OpenSearch Service examples using SDK for Java 2.x\n\u2022 EventBridge examples using SDK for Java 2.x\n\u2022 EventBridge Scheduler examples using SDK for Java 2.x\n\u2022 Forecast examples using SDK for Java 2.x\n\u2022 AWS Glue examples using SDK for Java 2.x\n\u2022 HealthImaging examples using SDK for Java 2.x\n\u2022 IAM examples using SDK for Java 2.x\n\u2022 AWS IoT examples using SDK for Java 2.x\n\u2022 AWS IoT data examples using SDK for Java 2.x\n\u2022 AWS IoT SiteWise examples using SDK for Java 2.x\n\u2022 Amazon Keyspaces examples using SDK for Java 2.x\n\u2022 Kinesis examples using SDK for Java 2.x\n\u2022 AWS KMS examples using SDK for Java 2.x\n\u2022 Lambda examples using SDK for Java 2.x\n\u2022 Amazon Lex examples using SDK for Java 2.x\n\u2022 AWS Marketplace Catalog API examples using SDK for Java 2.x\n\u2022 AWS Marketplace Agreement API examples using SDK for Java 2.x\n\u2022 MediaConvert examples using SDK for Java 2.x\n\u2022 Migration Hub examples using SDK for Java 2.x\n\u2022 Amazon MSK examples using SDK for Java 2.x\n475\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Amazon Personalize examples using SDK for Java 2.x\n\u2022 Amazon Personalize Events examples using SDK for Java 2.x\n\u2022 Amazon Personalize Runtime examples using SDK for Java 2.x\n\u2022 Amazon Pinpoint examples using SDK for Java 2.x\n\u2022 Amazon Pinpoint SMS and Voice API examples using SDK for Java 2.x\n\u2022 Amazon Polly examples using SDK for Java 2.x\n\u2022 Amazon RDS examples using SDK for Java 2.x\n\u2022 Amazon RDS Data Service examples using SDK for Java 2.x\n\u2022 Amazon Redshift examples using SDK for Java 2.x\n\u2022 Amazon Rekognition examples using SDK for Java 2.x\n\u2022 Route 53 domain registration examples using SDK for Java 2.x\n\u2022 Amazon S3 examples using SDK for Java 2.x\n\u2022 Amazon S3 Control examples using SDK for Java 2.x\n\u2022 S3 Directory Buckets examples using SDK for Java 2.x\n\u2022 S3 Glacier examples using SDK for Java 2.x\n\u2022 SageMaker AI examples using SDK for Java 2.x\n\u2022 Secrets Manager examples using SDK for Java 2.x\n\u2022 Amazon SES examples using SDK for Java 2.x\n\u2022 Amazon SES API v2 examples using SDK for Java 2.x\n\u2022 Amazon SNS examples using SDK for Java 2.x\n\u2022 Amazon SQS examples using SDK for Java 2.x\n\u2022 Step Functions examples using SDK for Java 2.x\n\u2022 AWS STS examples using SDK for Java 2.x\n\u2022 AWS Support examples using SDK for Java 2.x\n\u2022 Systems Manager examples using SDK for Java 2.x\n\u2022 Amazon Textract examples using SDK for Java 2.x\n\u2022 Amazon Transcribe examples using SDK for Java 2.x\n\u2022 Amazon Transcribe Streaming examples using SDK for Java 2.x\n\u2022 Amazon Translate examples using SDK for Java 2.x\n476\nAWS SDK for Java 2.x Developer Guide for version 2.x\nACM examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with ACM.\nActions are code excerpts from larger programs and must be run in context.", "mimetype": "text/plain", "start_char_idx": 776753, "end_char_idx": 780326, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "54c38f20-5dc3-47fd-bf12-5d382a9d7c88": {"__data__": {"id_": "54c38f20-5dc3-47fd-bf12-5d382a9d7c88", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "deeafbc1-5166-4acd-9e80-c2161448398c", "node_type": "1", "metadata": {}, "hash": "4c5a4c3d53ba58b0996c830caf4a7c30a6ad859d1ae780db16376ba3b309900a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b59c3aa9-da22-4b6f-8b51-fbdfb42073b6", "node_type": "1", "metadata": {}, "hash": "439cf8966f9368a01707764f14c655ed0c4ce485a2889dcd3ee1dbc4c61565fd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "x\n\u2022 Step Functions examples using SDK for Java 2.x\n\u2022 AWS STS examples using SDK for Java 2.x\n\u2022 AWS Support examples using SDK for Java 2.x\n\u2022 Systems Manager examples using SDK for Java 2.x\n\u2022 Amazon Textract examples using SDK for Java 2.x\n\u2022 Amazon Transcribe examples using SDK for Java 2.x\n\u2022 Amazon Transcribe Streaming examples using SDK for Java 2.x\n\u2022 Amazon Translate examples using SDK for Java 2.x\n476\nAWS SDK for Java 2.x Developer Guide for version 2.x\nACM examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with ACM.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nActions\nAddTagsToCertificate\nThe following code example shows how to use AddTagsToCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class AddTagsToCertificate {\nACM 477\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\naddTags(certArn);\n}\n/**\n* Adds tags to a certificate in AWS Certificate Manager (ACM).\n*\n* @param certArn the Amazon Resource Name (ARN) of the certificate to add tags\nto\n*/\npublic static void addTags(String certArn) {\nAcmClient acmClient = AcmClient.create();\nList expectedTags =\nList.of(Tag.builder().key(\"key\").value(\"value\").build());\nAddTagsToCertificateRequest addTagsToCertificateRequest =\nAddTagsToCertificateRequest.builder()\n.certificateArn(certArn)\n.tags(expectedTags)\n.build();\ntry {\nacmClient.addTagsToCertificate(addTagsToCertificateRequest);\nSystem.out.println(\"Successfully added tags to a certificate\");\n} catch (AcmException e) {\nSystem.out.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see AddTagsToCertificate in AWS SDK for Java 2.x API Reference.\nActions 478\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteCertificate\nThe following code example shows how to use DeleteCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\ndeleteCertificate(certArn);\n}\n/**\n* Deletes an SSL/TLS certificate from the AWS Certificate Manager (ACM).\n*\nActions 479\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param certArn the Amazon Resource Name (ARN) of the certificate to be\ndeleted\n*/\npublic static void deleteCertificate( String certArn) {\nAcmClient acmClient = AcmClient.create();\nDeleteCertificateRequest request = DeleteCertificateRequest.builder()\n.certificateArn(certArn)\n.build();\ntry {\nacmClient.deleteCertificate(request);\nSystem.out.println(\"The certificate was deleted\");\n} catch (AcmException e) {\nSystem.out.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see DeleteCertificate in AWS SDK for Java 2.x API Reference.\nDescribeCertificate\nThe following code example shows how to use DescribeCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 779620, "end_char_idx": 783855, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b59c3aa9-da22-4b6f-8b51-fbdfb42073b6": {"__data__": {"id_": "b59c3aa9-da22-4b6f-8b51-fbdfb42073b6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "54c38f20-5dc3-47fd-bf12-5d382a9d7c88", "node_type": "1", "metadata": {}, "hash": "21670a3b6c83cf33772a5afa21361f0c2938c093fb8972bd3c0e850864b8ce0e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34b3096a-9aa7-4ee3-a4db-0c6286fa9e8a", "node_type": "1", "metadata": {}, "hash": "708aa094c6cf04412dbaf17841f5c66d336c900a4ce9a0206aaae26eaf966145", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\nActions 479\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param certArn the Amazon Resource Name (ARN) of the certificate to be\ndeleted\n*/\npublic static void deleteCertificate( String certArn) {\nAcmClient acmClient = AcmClient.create();\nDeleteCertificateRequest request = DeleteCertificateRequest.builder()\n.certificateArn(certArn)\n.build();\ntry {\nacmClient.deleteCertificate(request);\nSystem.out.println(\"The certificate was deleted\");\n} catch (AcmException e) {\nSystem.out.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see DeleteCertificate in AWS SDK for Java 2.x API Reference.\nDescribeCertificate\nThe following code example shows how to use DescribeCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\nActions 480\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic class DescribeCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\ndescribeCertificate(certArn);\n}\n/**\n* Describes the details of an SSL/TLS certificate.\n*\n* @param certArn the Amazon Resource Name (ARN) of the certificate to describe\n* @throws AcmException if an error occurs while describing the certificate\n*/\npublic static void describeCertificate(String certArn) {\nAcmClient acmClient = AcmClient.create();\nDescribeCertificateRequest req = DescribeCertificateRequest.builder()\n.certificateArn(certArn)\n.build();\ntry {\nDescribeCertificateResponse response =\nacmClient.describeCertificate(req);\n// Print the certificate details.\nSystem.out.println(\"Certificate ARN: \" +\nresponse.certificate().certificateArn());\nSystem.out.println(\"Domain Name: \" +\nresponse.certificate().domainName());\nSystem.out.println(\"Issued By: \" + response.certificate().issuer());\nSystem.out.println(\"Issued On: \" + response.certificate().issuedAt());\nActions 481\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Status: \" + response.certificate().status());\n} catch (AcmException e) {\nSystem.out.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see DescribeCertificate in AWS SDK for Java 2.x API Reference.\nExportCertificate\nThe following code example shows how to use ExportCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ExportCertificate {\npublic static void main(String[] args) throws Exception {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nActions 482\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\nexportCert(certArn);\n}\n/**\n* Exports an SSL/TLS certificate and its associated private key and certificate\nchain from AWS Certificate Manager (ACM).\n*\n* @param certArn The Amazon Resource Name (ARN) of the certificate that you\nwant to export.\n* @throws IOException If an I/O error occurs while reading the private key\npassphrase file or exporting the certificate.\n*/\npublic static void exportCert(String certArn) throws IOException {\nAcmClient acmClient = AcmClient.create();\n// Initialize a file descriptor for the passphrase file.\nRandomAccessFile filePassphrase = null;\nByteBuffer bufPassphrase = null;\n// Create a file stream for reading the private key passphrase.\ntry {\nfilePassphrase = new RandomAccessFile(\"C:\\\\AWS\\\\password.txt\", \"r\");\n} catch (IllegalArgumentException | SecurityException |\nFileNotFoundException ex) {\nthrow ex;\n}\n// Create a channel to map the file.\nFileChannel channelPassphrase = filePassphrase.getChannel();\n// Map the file to the buffer.", "mimetype": "text/plain", "start_char_idx": 783127, "end_char_idx": 787487, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "34b3096a-9aa7-4ee3-a4db-0c6286fa9e8a": {"__data__": {"id_": "34b3096a-9aa7-4ee3-a4db-0c6286fa9e8a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b59c3aa9-da22-4b6f-8b51-fbdfb42073b6", "node_type": "1", "metadata": {}, "hash": "439cf8966f9368a01707764f14c655ed0c4ce485a2889dcd3ee1dbc4c61565fd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6927e421-bd87-4cdb-85c2-c6dc07499069", "node_type": "1", "metadata": {}, "hash": "e5d041fe7c773f4e8dce246b6518df2b2918338a362a0cecd8f534af8c55b3b6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param certArn The Amazon Resource Name (ARN) of the certificate that you\nwant to export.\n* @throws IOException If an I/O error occurs while reading the private key\npassphrase file or exporting the certificate.\n*/\npublic static void exportCert(String certArn) throws IOException {\nAcmClient acmClient = AcmClient.create();\n// Initialize a file descriptor for the passphrase file.\nRandomAccessFile filePassphrase = null;\nByteBuffer bufPassphrase = null;\n// Create a file stream for reading the private key passphrase.\ntry {\nfilePassphrase = new RandomAccessFile(\"C:\\\\AWS\\\\password.txt\", \"r\");\n} catch (IllegalArgumentException | SecurityException |\nFileNotFoundException ex) {\nthrow ex;\n}\n// Create a channel to map the file.\nFileChannel channelPassphrase = filePassphrase.getChannel();\n// Map the file to the buffer.\ntry {\nbufPassphrase = channelPassphrase.map(FileChannel.MapMode.READ_ONLY, 0,\nchannelPassphrase.size());\nchannelPassphrase.close();\nfilePassphrase.close();\n} catch (IOException ex) {\nthrow ex;\n}\nActions 483\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create a request object.\nExportCertificateRequest req = ExportCertificateRequest.builder()\n.certificateArn(certArn)\n.passphrase(SdkBytes.fromByteBuffer(bufPassphrase))\n.build();\n// Export the certificate.\nExportCertificateResponse result = null;\ntry {\nresult = acmClient.exportCertificate(req);\n} catch (InvalidArnException | InvalidTagException |\nResourceNotFoundException ex) {\nthrow ex;\n}\n// Clear the buffer.\nbufPassphrase.clear();\n// Display the certificate and certificate chain.\nString certificate = result.certificate();\nSystem.out.println(certificate);\nString certificateChain = result.certificateChain();\nSystem.out.println(certificateChain);\n// This example retrieves but does not display the private key.\nString privateKey = result.privateKey();\nSystem.out.println(\"The example is complete\");\n}\n}\n\u2022 For API details, see ExportCertificate in AWS SDK for Java 2.x API Reference.\nImportCertificate\nThe following code example shows how to use ImportCertificate.\nActions 484\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ImportCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertificatePath - the path to the SSL/TLS certificate file.\nprivateKeyPath - the path to the private key file associated with\nthe SSL/TLS certificate.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nreturn;\n}\nString certificatePath = args[0];\nString privateKeyPath = args[1];\nString certificateArn = importCertificate(certificatePath, privateKeyPath);\nSystem.out.println(\"Certificate imported with ARN: \" + certificateArn);\n}\n/**\nActions 485\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Imports an SSL/TLS certificate and private key into AWS Certificate Manager\n(ACM) for use with\n* AWS services.\n*\n* @param certificatePath the file path to the SSL/TLS certificate\n* @param privateKeyPath the file path to the private key associated with the\ncertificate\n* @throws IOException if there is an error reading the certificate or private\nkey files\n*/\npublic static String importCertificate(String certificatePath, String\nprivateKeyPath) {\nAcmClient acmClient = AcmClient.create();\ntry {\nbyte[] certificateBytes = readFileBytes(certificatePath);\nbyte[] privateKeyBytes = readFileBytes(privateKeyPath);\nImportCertificateRequest request = ImportCertificateRequest.builder()\n.certificate(SdkBytes.fromByteBuffer(ByteBuffer.wrap(certificateBytes)))\n.privateKey(SdkBytes.fromByteBuffer(ByteBuffer.wrap(privateKeyBytes)))\n.build();\nImportCertificateResponse response =\nacmClient.importCertificate(request);\nString certificateArn = response.certificateArn();\nreturn certificateArn;\n} catch (IOException e) {\nSystem.err.println(\"Error reading certificate or private key file: \" +\ne.getMessage());\n}\nreturn \"\";\n}\nprivate static byte[] readFileBytes(String filePath) throws IOException {\ntry (InputStream inputStream = new FileInputStream(filePath)) {\nreturn IoUtils.toByteArray(inputStream);\n}\n}\n}\n\u2022 For API details, see ImportCertificate in AWS SDK for Java 2.x API Reference.\nActions 486\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListCertificates\nThe following code example shows how to use ListCertificates.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 786667, "end_char_idx": 791414, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6927e421-bd87-4cdb-85c2-c6dc07499069": {"__data__": {"id_": "6927e421-bd87-4cdb-85c2-c6dc07499069", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34b3096a-9aa7-4ee3-a4db-0c6286fa9e8a", "node_type": "1", "metadata": {}, "hash": "708aa094c6cf04412dbaf17841f5c66d336c900a4ce9a0206aaae26eaf966145", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "daa590a1-9945-4da5-a504-dc976cc52de3", "node_type": "1", "metadata": {}, "hash": "9aa3c6a8152e3f1fcd0be0eaf65b1ec125e588970c7bfecd70dbc1396d781ae0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 486\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListCertificates\nThe following code example shows how to use ListCertificates.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListCerts {\npublic static void main(String[] args) {\nlistCertificates();\n}\n/**\n* Lists all the certificates managed by AWS Certificate Manager (ACM) that have\na status of \"ISSUED\".\n*/\npublic static void listCertificates() {\nAcmClient acmClient = AcmClient.create();\ntry {\nListCertificatesRequest listRequest = ListCertificatesRequest.builder()\n.certificateStatuses(CertificateStatus.ISSUED)\n.maxItems(100)\n.build();\nListCertificatesIterable listResponse =\nacmClient.listCertificatesPaginator(listRequest);\n// Print the certificate details using streams\nlistResponse.certificateSummaryList().stream()\n.forEach(certificate -> {\nActions 487\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Certificate ARN: \" +\ncertificate.certificateArn());\nSystem.out.println(\"Certificate Domain Name: \" +\ncertificate.domainName());\nSystem.out.println(\"Certificate Status: \" +\ncertificate.statusAsString());\nSystem.out.println(\"---\");\n});\n} catch (AcmException e) {\nSystem.err.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see ListCertificates in AWS SDK for Java 2.x API Reference.\nListTagsForCertificate\nThe following code example shows how to use ListTagsForCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListCertTags {\nActions 488\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\nlistCertTags(certArn);\n}\n/**\n* Lists the tags associated with an AWS Certificate Manager (ACM) certificate.\n*\n* @param certArn the Amazon Resource Name (ARN) of the ACM certificate\n*/\npublic static void listCertTags(String certArn) {\nAcmClient acmClient = AcmClient.create();\nListTagsForCertificateRequest request =\nListTagsForCertificateRequest.builder()\n.certificateArn(certArn)\n.build();\nListTagsForCertificateResponse response =\nacmClient.listTagsForCertificate(request);\nList tagList = response.tags();\ntagList.forEach(tag -> {\nSystem.out.println(\"Key: \" + tag.key());\nSystem.out.println(\"Value: \" + tag.value());\n});\n}\n}\n\u2022 For API details, see ListTagsForCertificate in AWS SDK for Java 2.x API Reference.\nActions 489\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRemoveTagsFromCertificate\nThe following code example shows how to use RemoveTagsFromCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class RemoveTagsFromCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\nremoveTags(certArn);\n}\n/**\n* Removes tags from an AWS Certificate Manager (ACM) certificate.", "mimetype": "text/plain", "start_char_idx": 791225, "end_char_idx": 795355, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "daa590a1-9945-4da5-a504-dc976cc52de3": {"__data__": {"id_": "daa590a1-9945-4da5-a504-dc976cc52de3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6927e421-bd87-4cdb-85c2-c6dc07499069", "node_type": "1", "metadata": {}, "hash": "e5d041fe7c773f4e8dce246b6518df2b2918338a362a0cecd8f534af8c55b3b6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7c3b2889-bfe7-49fa-b20b-a13d568fff86", "node_type": "1", "metadata": {}, "hash": "a9869caeda732f2489cc2cc08f03a55a4b4d2bb37e42e10bac7350e000ed036a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class RemoveTagsFromCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\nremoveTags(certArn);\n}\n/**\n* Removes tags from an AWS Certificate Manager (ACM) certificate.\nActions 490\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* @param certArn the Amazon Resource Name (ARN) of the certificate from which\nto remove tags\n*/\npublic static void removeTags(String certArn) {\nAcmClient acmClient = AcmClient.create();\nList expectedTags =\nList.of(Tag.builder().key(\"key\").value(\"value\").build());\nRemoveTagsFromCertificateRequest req =\nRemoveTagsFromCertificateRequest.builder()\n.certificateArn(certArn)\n.tags(expectedTags)\n.build();\ntry {\nacmClient.removeTagsFromCertificate(req);\nSystem.out.println(\"Successfully removed tags from the certificate\");\n} catch (AcmException e) {\nSystem.err.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see RemoveTagsFromCertificate in AWS SDK for Java 2.x API Reference.\nRenewCertificate\nThe following code example shows how to use RenewCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\nActions 491\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class RenewCert {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncertArn - the ARN of the certificate.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString certArn = args[0];\nrenewCertificate(certArn);\n}\n/**\n* Renews an existing SSL/TLS certificate in AWS Certificate Manager (ACM).\n*\n* @param certArn The Amazon Resource Name (ARN) of the certificate to be\nrenewed.\n* @throws AcmException If there is an error renewing the certificate.\n*/\npublic static void renewCertificate(String certArn) {\nAcmClient acmClient = AcmClient.create();\nRenewCertificateRequest certificateRequest =\nRenewCertificateRequest.builder()\n.certificateArn(certArn)\n.build();\ntry {\nacmClient.renewCertificate(certificateRequest);\nSystem.out.println(\"The certificate was renewed\");\n} catch(AcmException e){\nSystem.out.println(e.getMessage());\n}\nActions 492\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n\u2022 For API details, see RenewCertificate in AWS SDK for Java 2.x API Reference.\nRequestCertificate\nThe following code example shows how to use RequestCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class RequestCert {\npublic static void main(String[] args) {\nrequestCertificate();\n}\n/**\n* Requests a certificate from the AWS Certificate Manager (ACM) service.", "mimetype": "text/plain", "start_char_idx": 794592, "end_char_idx": 798369, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7c3b2889-bfe7-49fa-b20b-a13d568fff86": {"__data__": {"id_": "7c3b2889-bfe7-49fa-b20b-a13d568fff86", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "daa590a1-9945-4da5-a504-dc976cc52de3", "node_type": "1", "metadata": {}, "hash": "9aa3c6a8152e3f1fcd0be0eaf65b1ec125e588970c7bfecd70dbc1396d781ae0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bfe66aab-a3ff-4be6-a394-61f49f90946e", "node_type": "1", "metadata": {}, "hash": "711203b9221ec818b24c72637bc422ec04c0f1fed576626b60596b5c95306752", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "RequestCertificate\nThe following code example shows how to use RequestCertificate.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*

\n* For more information, see the following documentation topic:\n*

\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class RequestCert {\npublic static void main(String[] args) {\nrequestCertificate();\n}\n/**\n* Requests a certificate from the AWS Certificate Manager (ACM) service.\n*/\npublic static void requestCertificate() {\nAcmClient acmClient = AcmClient.create();\nArrayList san = new ArrayList<>();\nsan.add(\"www.example.com\");\nActions 493\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRequestCertificateRequest req = RequestCertificateRequest.builder()\n.domainName(\"example.com\")\n.idempotencyToken(\"1Aq25pTy\")\n.subjectAlternativeNames(san)\n.build();\ntry {\nRequestCertificateResponse response = acmClient.requestCertificate(req);\nSystem.out.println(\"Cert ARN IS \" + response.certificateArn());\n} catch (AcmException e) {\nSystem.err.println(e.getMessage());\n}\n}\n}\n\u2022 For API details, see RequestCertificate in AWS SDK for Java 2.x API Reference.\nAPI Gateway examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with API Gateway.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nAWS community contributions are examples that were created and are maintained by multiple\nteams across AWS. To provide feedback, use the mechanism provided in the linked repositories.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\n\u2022 Scenarios\n\u2022 AWS community contributions\nAPI Gateway 494\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions\nCreateDeployment\nThe following code example shows how to use CreateDeployment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static String createNewDeployment(ApiGatewayClient apiGateway, String\nrestApiId, String stageName) {\ntry {\nCreateDeploymentRequest request = CreateDeploymentRequest.builder()\n.restApiId(restApiId)\n.description(\"Created using the AWS API Gateway Java API\")\n.stageName(stageName)\n.build();\nCreateDeploymentResponse response =\napiGateway.createDeployment(request);\nSystem.out.println(\"The id of the deployment is \" + response.id());\nreturn response.id();\n} catch (ApiGatewayException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateDeployment in AWS SDK for Java 2.x API Reference.\nActions 495\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateRestApi\nThe following code example shows how to use CreateRestApi.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static String createAPI(ApiGatewayClient apiGateway, String restApiId,\nString restApiName) {\ntry {\nCreateRestApiRequest request = CreateRestApiRequest.builder()\n.cloneFrom(restApiId)\n.description(\"Created using the Gateway Java API\")\n.name(restApiName)\n.build();\nCreateRestApiResponse response = apiGateway.createRestApi(request);\nSystem.out.println(\"The id of the new api is \" + response.id());\nreturn response.id();\n} catch (ApiGatewayException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateRestApi in AWS SDK for Java 2.x API Reference.\nDeleteDeployment\nThe following code example shows how to use DeleteDeployment.\nActions 496\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 797701, "end_char_idx": 802116, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bfe66aab-a3ff-4be6-a394-61f49f90946e": {"__data__": {"id_": "bfe66aab-a3ff-4be6-a394-61f49f90946e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7c3b2889-bfe7-49fa-b20b-a13d568fff86", "node_type": "1", "metadata": {}, "hash": "a9869caeda732f2489cc2cc08f03a55a4b4d2bb37e42e10bac7350e000ed036a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "30f9f7c4-2366-4ccb-8a07-175f77ed9756", "node_type": "1", "metadata": {}, "hash": "aaf86e1750c59a1569316524441b115bba4dce25462b8123b575f4833ef8b67e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteDeployment\nThe following code example shows how to use DeleteDeployment.\nActions 496\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void deleteSpecificDeployment(ApiGatewayClient apiGateway, String\nrestApiId, String deploymentId) {\ntry {\nDeleteDeploymentRequest request = DeleteDeploymentRequest.builder()\n.restApiId(restApiId)\n.deploymentId(deploymentId)\n.build();\napiGateway.deleteDeployment(request);\nSystem.out.println(\"Deployment was deleted\");\n} catch (ApiGatewayException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DeleteDeployment in AWS SDK for Java 2.x API Reference.\nDeleteRestApi\nThe following code example shows how to use DeleteRestApi.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 497\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void deleteAPI(ApiGatewayClient apiGateway, String restApiId) {\ntry {\nDeleteRestApiRequest request = DeleteRestApiRequest.builder()\n.restApiId(restApiId)\n.build();\napiGateway.deleteRestApi(request);\nSystem.out.println(\"The API was successfully deleted\");\n} catch (ApiGatewayException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DeleteRestApi in AWS SDK for Java 2.x API Reference.\nScenarios\nCreate a serverless application to manage photos\nThe following code example shows how to create a serverless application that lets users manage\nphotos using labels.\nSDK for Java 2.x\nShows how to develop a photo asset management application that detects labels in images\nusing Amazon Rekognition and stores them for later retrieval.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nFor a deep dive into the origin of this example see the post on AWS Community.\nServices used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\nScenarios 498\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Amazon Rekognition\n\u2022 Amazon S3\n\u2022 Amazon SNS\nUse API Gateway to invoke a Lambda function\nThe following code example shows how to create an AWS Lambda function invoked by Amazon API\nGateway.\nSDK for Java 2.x\nShows how to create an AWS Lambda function by using the Lambda Java runtime API.\nThis example invokes different AWS services to perform a specific use case. This example\ndemonstrates how to create a Lambda function invoked by Amazon API Gateway that scans an\nAmazon DynamoDB table for work anniversaries and uses Amazon Simple Notification Service\n(Amazon SNS) to send a text message to your employees that congratulates them at their one\nyear anniversary date.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\n\u2022 Amazon SNS\nAWS community contributions\nBuild and test a serverless application\nThe following code example shows how to build and test a serverless application using API\nGateway with Lambda and DynamoDB\nSDK for Java 2.x\nShows how to build and test a serverless application that consists of an API Gateway with\nLambda and DynamoDB using the Java SDK.\nAWS community contributions 499\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\nApplication Auto Scaling examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Application Auto Scaling.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nActions\nDeleteScalingPolicy\nThe following code example shows how to use DeleteScalingPolicy.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 801832, "end_char_idx": 806256, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "30f9f7c4-2366-4ccb-8a07-175f77ed9756": {"__data__": {"id_": "30f9f7c4-2366-4ccb-8a07-175f77ed9756", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bfe66aab-a3ff-4be6-a394-61f49f90946e", "node_type": "1", "metadata": {}, "hash": "711203b9221ec818b24c72637bc422ec04c0f1fed576626b60596b5c95306752", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9fdd7d68-e56b-409f-a400-cadb299185da", "node_type": "1", "metadata": {}, "hash": "2c60b2cd1d5500db755ddc16cab8ea7460afbeefd14a7e9b854c8d0cf4b62680", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Services used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\nApplication Auto Scaling examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Application Auto Scaling.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nActions\nDeleteScalingPolicy\nThe following code example shows how to use DeleteScalingPolicy.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nApplication Auto Scaling 500\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DeleteScalingPolicyRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DeregisterScalableTargetRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;\n/**\n* Before running this Java V2 code example, set up your development environment,\nincluding your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DisableDynamoDBAutoscaling {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\ntableId - The table Id value (for example, table/Music).\\s\npolicyName - The name of the policy (for example, $Music5-scaling-\npolicy).\n\"\"\";\nif (args.length != 2) {\nActions 501\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(usage);\nSystem.exit(1);\n}\nApplicationAutoScalingClient appAutoScalingClient =\nApplicationAutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\nServiceNamespace ns = ServiceNamespace.DYNAMODB;\nScalableDimension tableWCUs =\nScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;\nString tableId = args[0];\nString policyName = args[1];\ndeletePolicy(appAutoScalingClient, policyName, tableWCUs, ns, tableId);\nverifyScalingPolicies(appAutoScalingClient, tableId, ns, tableWCUs);\nderegisterScalableTarget(appAutoScalingClient, tableId, ns, tableWCUs);\nverifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);\n}\npublic static void deletePolicy(ApplicationAutoScalingClient\nappAutoScalingClient, String policyName, ScalableDimension tableWCUs,\nServiceNamespace ns, String tableId) {\ntry {\nDeleteScalingPolicyRequest delSPRequest =\nDeleteScalingPolicyRequest.builder()\n.policyName(policyName)\n.scalableDimension(tableWCUs)\n.serviceNamespace(ns)\n.resourceId(tableId)\n.build();\nappAutoScalingClient.deleteScalingPolicy(delSPRequest);\nSystem.out.println(policyName +\" was deleted successfully.", "mimetype": "text/plain", "start_char_idx": 805394, "end_char_idx": 809104, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9fdd7d68-e56b-409f-a400-cadb299185da": {"__data__": {"id_": "9fdd7d68-e56b-409f-a400-cadb299185da", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "30f9f7c4-2366-4ccb-8a07-175f77ed9756", "node_type": "1", "metadata": {}, "hash": "aaf86e1750c59a1569316524441b115bba4dce25462b8123b575f4833ef8b67e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "219d8599-efd8-4f69-a5af-b39886ecd9fb", "node_type": "1", "metadata": {}, "hash": "6164e0a8b7d75a04819090ae159b0f4b10ceee44405401f4c0c0ea0a45923ef9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} catch (ApplicationAutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\n}\n// Verify that the scaling policy was deleted\nActions 502\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void verifyScalingPolicies(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs) {\nDescribeScalingPoliciesRequest dscRequest =\nDescribeScalingPoliciesRequest.builder()\n.scalableDimension(tableWCUs)\n.serviceNamespace(ns)\n.resourceId(tableId)\n.build();\nDescribeScalingPoliciesResponse response =\nappAutoScalingClient.describeScalingPolicies(dscRequest);\nSystem.out.println(\"DescribeScalableTargets result: \");\nSystem.out.println(response);\n}\npublic static void deregisterScalableTarget(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs) {\ntry {\nDeregisterScalableTargetRequest targetRequest =\nDeregisterScalableTargetRequest.builder()\n.scalableDimension(tableWCUs)\n.serviceNamespace(ns)\n.resourceId(tableId)\n.build();\nappAutoScalingClient.deregisterScalableTarget(targetRequest);\nSystem.out.println(\"The scalable target was deregistered.\");\n} catch (ApplicationAutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\n}\npublic static void verifyTarget(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs) {\nDescribeScalableTargetsRequest dscRequest =\nDescribeScalableTargetsRequest.builder()\n.scalableDimension(tableWCUs)\n.serviceNamespace(ns)\n.resourceIds(tableId)\n.build();\nActions 503\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeScalableTargetsResponse response =\nappAutoScalingClient.describeScalableTargets(dscRequest);\nSystem.out.println(\"DescribeScalableTargets result: \");\nSystem.out.println(response);\n}\n}\n\u2022 For API details, see DeleteScalingPolicy in AWS SDK for Java 2.x API Reference.\nRegisterScalableTarget\nThe following code example shows how to use RegisterScalableTarget.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;\nimport software.amazon.awssdk.services.applicationautoscaling.model.PolicyType;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.PredefinedMetricSpecification;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.PutScalingPolicyRequest;\nActions 504\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.RegisterScalableTargetRequest;\nimport software.amazon.awssdk.services.applicationautoscaling.model.ScalingPolicy;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;\nimport software.amazon.awssdk.services.applicationautoscaling.model.MetricType;\nimport\nsoftware.amazon.awssdk.services.applicationautoscaling.model.TargetTrackingScalingPolicyConfiguration;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development environment,\nincluding your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class EnableDynamoDBAutoscaling {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\ntableId - The table Id value (for example, table/Music).\nroleARN - The ARN of the role that has ApplicationAutoScaling\npermissions.\npolicyName - The name of the policy to create.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nSystem.out.println(\"This example registers an Amazon DynamoDB table, which\nis the resource to scale.", "mimetype": "text/plain", "start_char_idx": 809104, "end_char_idx": 813624, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "219d8599-efd8-4f69-a5af-b39886ecd9fb": {"__data__": {"id_": "219d8599-efd8-4f69-a5af-b39886ecd9fb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9fdd7d68-e56b-409f-a400-cadb299185da", "node_type": "1", "metadata": {}, "hash": "2c60b2cd1d5500db755ddc16cab8ea7460afbeefd14a7e9b854c8d0cf4b62680", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9e2804ed-802b-4693-b107-5608986ac855", "node_type": "1", "metadata": {}, "hash": "0e64a543c7a489b536b92c9c5a1a1b3c65f826815c98adc12da5a8a3d4d87b01", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class EnableDynamoDBAutoscaling {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\ntableId - The table Id value (for example, table/Music).\nroleARN - The ARN of the role that has ApplicationAutoScaling\npermissions.\npolicyName - The name of the policy to create.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nSystem.out.println(\"This example registers an Amazon DynamoDB table, which\nis the resource to scale.\");\nString tableId = args[0];\nString roleARN = args[1];\nActions 505\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString policyName = args[2];\nServiceNamespace ns = ServiceNamespace.DYNAMODB;\nScalableDimension tableWCUs =\nScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;\nApplicationAutoScalingClient appAutoScalingClient =\nApplicationAutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\nregisterScalableTarget(appAutoScalingClient, tableId, roleARN, ns,\ntableWCUs);\nverifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);\nconfigureScalingPolicy(appAutoScalingClient, tableId, ns, tableWCUs,\npolicyName);\n}\npublic static void registerScalableTarget(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, String roleARN, ServiceNamespace ns,\nScalableDimension tableWCUs) {\ntry {\nRegisterScalableTargetRequest targetRequest =\nRegisterScalableTargetRequest.builder()\n.serviceNamespace(ns)\n.scalableDimension(tableWCUs)\n.resourceId(tableId)\n.roleARN(roleARN)\n.minCapacity(5)\n.maxCapacity(10)\n.build();\nappAutoScalingClient.registerScalableTarget(targetRequest);\nSystem.out.println(\"You have registered \" + tableId);\n} catch (ApplicationAutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\n}\n// Verify that the target was created.\npublic static void verifyTarget(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs) {\nDescribeScalableTargetsRequest dscRequest =\nDescribeScalableTargetsRequest.builder()\nActions 506\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.scalableDimension(tableWCUs)\n.serviceNamespace(ns)\n.resourceIds(tableId)\n.build();\nDescribeScalableTargetsResponse response =\nappAutoScalingClient.describeScalableTargets(dscRequest);\nSystem.out.println(\"DescribeScalableTargets result: \");\nSystem.out.println(response);\n}\n// Configure a scaling policy.\npublic static void configureScalingPolicy(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs, String policyName) {\n// Check if the policy exists before creating a new one.\nDescribeScalingPoliciesResponse describeScalingPoliciesResponse =\nappAutoScalingClient.describeScalingPolicies(DescribeScalingPoliciesRequest.builder()\n.serviceNamespace(ns)\n.resourceId(tableId)\n.scalableDimension(tableWCUs)\n.build());\nif (!describeScalingPoliciesResponse.scalingPolicies().isEmpty()) {\n// If policies exist, consider updating an existing policy instead of\ncreating a new one.\nSystem.out.println(\"Policy already exists. Consider updating it\ninstead.\");\nList polList =\ndescribeScalingPoliciesResponse.scalingPolicies();\nfor (ScalingPolicy pol : polList) {\nSystem.out.println(\"Policy name:\" +pol.policyName());\n}\n} else {\n// If no policies exist, proceed with creating a new policy.", "mimetype": "text/plain", "start_char_idx": 812962, "end_char_idx": 816474, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9e2804ed-802b-4693-b107-5608986ac855": {"__data__": {"id_": "9e2804ed-802b-4693-b107-5608986ac855", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "219d8599-efd8-4f69-a5af-b39886ecd9fb", "node_type": "1", "metadata": {}, "hash": "6164e0a8b7d75a04819090ae159b0f4b10ceee44405401f4c0c0ea0a45923ef9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "59bbdf9d-1fee-4252-beca-e4313d977ec4", "node_type": "1", "metadata": {}, "hash": "9aaf7e256bfc389a1b31d5a24fd87d298cfc356cc3a14c8b1fcc42b665203e34", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static void configureScalingPolicy(ApplicationAutoScalingClient\nappAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension\ntableWCUs, String policyName) {\n// Check if the policy exists before creating a new one.\nDescribeScalingPoliciesResponse describeScalingPoliciesResponse =\nappAutoScalingClient.describeScalingPolicies(DescribeScalingPoliciesRequest.builder()\n.serviceNamespace(ns)\n.resourceId(tableId)\n.scalableDimension(tableWCUs)\n.build());\nif (!describeScalingPoliciesResponse.scalingPolicies().isEmpty()) {\n// If policies exist, consider updating an existing policy instead of\ncreating a new one.\nSystem.out.println(\"Policy already exists. Consider updating it\ninstead.\");\nList polList =\ndescribeScalingPoliciesResponse.scalingPolicies();\nfor (ScalingPolicy pol : polList) {\nSystem.out.println(\"Policy name:\" +pol.policyName());\n}\n} else {\n// If no policies exist, proceed with creating a new policy.\nPredefinedMetricSpecification specification =\nPredefinedMetricSpecification.builder()\n.predefinedMetricType(MetricType.DYNAMO_DB_WRITE_CAPACITY_UTILIZATION)\n.build();\nTargetTrackingScalingPolicyConfiguration policyConfiguration =\nTargetTrackingScalingPolicyConfiguration.builder()\n.predefinedMetricSpecification(specification)\nActions 507\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.targetValue(50.0)\n.scaleInCooldown(60)\n.scaleOutCooldown(60)\n.build();\nPutScalingPolicyRequest putScalingPolicyRequest =\nPutScalingPolicyRequest.builder()\n.targetTrackingScalingPolicyConfiguration(policyConfiguration)\n.serviceNamespace(ns)\n.scalableDimension(tableWCUs)\n.resourceId(tableId)\n.policyName(policyName)\n.policyType(PolicyType.TARGET_TRACKING_SCALING)\n.build();\ntry {\nappAutoScalingClient.putScalingPolicy(putScalingPolicyRequest);\nSystem.out.println(\"You have successfully created a scaling policy\nfor an Application Auto Scaling scalable target\");\n} catch (ApplicationAutoScalingException e) {\nSystem.err.println(\"Error: \" + e.awsErrorDetails().errorMessage());\n}\n}\n}\n}\n\u2022 For API details, see RegisterScalableTarget in AWS SDK for Java 2.x API Reference.\nApplication Recovery Controller examples using SDK for Java\n2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Application Recovery Controller.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nApplication Recovery Controller 508\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTopics\n\u2022 Actions\nActions\nGetRoutingControlState\nThe following code example shows how to use GetRoutingControlState.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static GetRoutingControlStateResponse\ngetRoutingControlState(List clusterEndpoints,\nString routingControlArn) {\n// As a best practice, we recommend choosing a random cluster endpoint to\nget or\n// set routing control states.\n// For more information, see\n// https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-\npractices.html#route53-arc-best-practices.regional\nCollections.shuffle(clusterEndpoints);\nfor (ClusterEndpoint clusterEndpoint : clusterEndpoints) {\ntry {\nSystem.out.println(clusterEndpoint);\nRoute53RecoveryClusterClient client =\nRoute53RecoveryClusterClient.builder()\n.endpointOverride(URI.create(clusterEndpoint.endpoint()))\n.region(Region.of(clusterEndpoint.region())).build();\nreturn client.getRoutingControlState(\nGetRoutingControlStateRequest.builder()\n.routingControlArn(routingControlArn).build());\n} catch (Exception exception) {\nSystem.out.println(exception);\n}\n}\nActions 509\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn null;\n}\n\u2022 For API details, see GetRoutingControlState in AWS SDK for Java 2.x API Reference.\nUpdateRoutingControlState\nThe following code example shows how to use UpdateRoutingControlState.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static UpdateRoutingControlStateResponse\nupdateRoutingControlState(List clusterEndpoints,\nString routingControlArn,\nString routingControlState) {\n// As a best practice, we recommend choosing a random cluster endpoint to\nget or\n// set routing control states.", "mimetype": "text/plain", "start_char_idx": 815525, "end_char_idx": 820150, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "59bbdf9d-1fee-4252-beca-e4313d977ec4": {"__data__": {"id_": "59bbdf9d-1fee-4252-beca-e4313d977ec4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9e2804ed-802b-4693-b107-5608986ac855", "node_type": "1", "metadata": {}, "hash": "0e64a543c7a489b536b92c9c5a1a1b3c65f826815c98adc12da5a8a3d4d87b01", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "738dd8e4-d9d1-481b-81d0-340aec1dd43a", "node_type": "1", "metadata": {}, "hash": "016d18e2145f3b3ecb269c6a4b62ec6b33c2904da325b2bafc4cd85451ac3a5c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "UpdateRoutingControlState\nThe following code example shows how to use UpdateRoutingControlState.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static UpdateRoutingControlStateResponse\nupdateRoutingControlState(List clusterEndpoints,\nString routingControlArn,\nString routingControlState) {\n// As a best practice, we recommend choosing a random cluster endpoint to\nget or\n// set routing control states.\n// For more information, see\n// https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-\npractices.html#route53-arc-best-practices.regional\nCollections.shuffle(clusterEndpoints);\nfor (ClusterEndpoint clusterEndpoint : clusterEndpoints) {\ntry {\nSystem.out.println(clusterEndpoint);\nRoute53RecoveryClusterClient client =\nRoute53RecoveryClusterClient.builder()\n.endpointOverride(URI.create(clusterEndpoint.endpoint()))\n.region(Region.of(clusterEndpoint.region()))\n.build();\nreturn client.updateRoutingControlState(\nUpdateRoutingControlStateRequest.builder()\n.routingControlArn(routingControlArn).routingControlState(routingControlState).build());\n} catch (Exception exception) {\nActions 510\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(exception);\n}\n}\nreturn null;\n}\n\u2022 For API details, see UpdateRoutingControlState in AWS SDK for Java 2.x API Reference.\nAurora examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Aurora.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello Aurora\nThe following code examples show how to get started using Aurora.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.rds.RdsClient;\nAurora 511\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.rds.paginators.DescribeDBClustersIterable;\npublic class DescribeDbClusters {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nRdsClient rdsClient = RdsClient.builder()\n.region(region)\n.build();\ndescribeClusters(rdsClient);\nrdsClient.close();\n}\npublic static void describeClusters(RdsClient rdsClient) {\nDescribeDBClustersIterable clustersIterable =\nrdsClient.describeDBClustersPaginator();\nclustersIterable.stream()\n.flatMap(r -> r.dbClusters().stream())\n.forEach(cluster -> System.out\n.println(\"Database name: \" + cluster.databaseName() + \" Arn\n= \" + cluster.dbClusterArn()));\n}\n}\n\u2022 For API details, see DescribeDBClusters in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create a custom Aurora DB cluster parameter group and set parameter values.\n\u2022 Create a DB cluster that uses the parameter group.\nBasics 512\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Create a DB instance that contains a database.\n\u2022 Take a snapshot of the DB cluster, then clean up resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This example requires an AWS Secrets Manager secret that contains the\n* database credentials. If you do not create a\n* secret, this example will not work. For details, see:\n*\n* https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-\nservices-use-secrets_RS.html\n*\n* This Java example performs the following tasks:\n*\n* 1. Gets available engine families for Amazon Aurora MySQL-Compatible Edition\n* by calling the DescribeDbEngineVersions(Engine='aurora-mysql') method.\n* 2.", "mimetype": "text/plain", "start_char_idx": 819631, "end_char_idx": 824247, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "738dd8e4-d9d1-481b-81d0-340aec1dd43a": {"__data__": {"id_": "738dd8e4-d9d1-481b-81d0-340aec1dd43a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "59bbdf9d-1fee-4252-beca-e4313d977ec4", "node_type": "1", "metadata": {}, "hash": "9aaf7e256bfc389a1b31d5a24fd87d298cfc356cc3a14c8b1fcc42b665203e34", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b32e6ef9-10e5-46c6-86ef-c069e8a29153", "node_type": "1", "metadata": {}, "hash": "3f843e960c98d1a0e082947cbe1be0aca5fd69c27b727d29e79c29bc6d19a1fe", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This example requires an AWS Secrets Manager secret that contains the\n* database credentials. If you do not create a\n* secret, this example will not work. For details, see:\n*\n* https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-\nservices-use-secrets_RS.html\n*\n* This Java example performs the following tasks:\n*\n* 1. Gets available engine families for Amazon Aurora MySQL-Compatible Edition\n* by calling the DescribeDbEngineVersions(Engine='aurora-mysql') method.\n* 2. Selects an engine family and creates a custom DB cluster parameter group\n* by invoking the describeDBClusterParameters method.\n* 3. Gets the parameter groups by invoking the describeDBClusterParameterGroups\n* method.\n* 4. Gets parameters in the group by invoking the describeDBClusterParameters\n* method.\n* 5. Modifies the auto_increment_offset parameter by invoking the\n* modifyDbClusterParameterGroupRequest method.\n* 6. Gets and displays the updated parameters.\n* 7. Gets a list of allowed engine versions by invoking the\n* describeDbEngineVersions method.\nBasics 513\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* 8. Creates an Aurora DB cluster database cluster that contains a MySQL\n* database.\n* 9. Waits for DB instance to be ready.\n* 10. Gets a list of instance classes available for the selected engine.\n* 11. Creates a database instance in the cluster.\n* 12. Waits for DB instance to be ready.\n* 13. Creates a snapshot.\n* 14. Waits for DB snapshot to be ready.\n* 15. Deletes the DB cluster.\n* 16. Deletes the DB cluster group.\n*/\npublic class AuroraScenario {\npublic static long sleepTime = 20;\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws InterruptedException {\nfinal String usage = \"\\n\" +\n\"Usage:\\n\" +\n\" \n \n\"\n+\n\"Where:\\n\" +\n\" dbClusterGroupName - The name of the DB cluster parameter\ngroup. \\n\" +\n\" dbParameterGroupFamily - The DB cluster parameter group family\nname (for example, aurora-mysql5.7). \\n\"\n+\n\" dbInstanceClusterIdentifier - The instance cluster identifier\nvalue.\\n\" +\n\" dbInstanceIdentifier - The database instance identifier.\\n\" +\n\" dbName - The database name.\\n\" +\n\" dbSnapshotIdentifier - The snapshot identifier.\\n\" +\n\" secretName - The name of the AWS Secrets Manager secret that\ncontains the database credentials\\\"\\n\";\n;\nif (args.length != 7) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString dbClusterGroupName = args[0];\nString dbParameterGroupFamily = args[1];\nBasics 514\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString dbInstanceClusterIdentifier = args[2];\nString dbInstanceIdentifier = args[3];\nString dbName = args[4];\nString dbSnapshotIdentifier = args[5];\nString secretName = args[6];\n// Retrieve the database credentials using AWS Secrets Manager.\nGson gson = new Gson();\nUser user = gson.fromJson(String.valueOf(getSecretValues(secretName)),\nUser.class);\nString username = user.getUsername();\nString userPassword = user.getPassword();\nRegion region = Region.US_WEST_2;\nRdsClient rdsClient = RdsClient.builder()\n.region(region)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon Aurora example scenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"1. Return a list of the available DB engines\");\ndescribeDBEngines(rdsClient);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Create a custom parameter group\");\ncreateDBClusterParameterGroup(rdsClient, dbClusterGroupName,\ndbParameterGroupFamily);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"3.", "mimetype": "text/plain", "start_char_idx": 823388, "end_char_idx": 827503, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b32e6ef9-10e5-46c6-86ef-c069e8a29153": {"__data__": {"id_": "b32e6ef9-10e5-46c6-86ef-c069e8a29153", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "738dd8e4-d9d1-481b-81d0-340aec1dd43a", "node_type": "1", "metadata": {}, "hash": "016d18e2145f3b3ecb269c6a4b62ec6b33c2904da325b2bafc4cd85451ac3a5c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d08c0d78-59ae-40b8-acdc-ca772c874ee5", "node_type": "1", "metadata": {}, "hash": "18792e1ce49856d974d45839fc0d369b9c99628f68a28b4fea0ef96fe7cd6044", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Gson gson = new Gson();\nUser user = gson.fromJson(String.valueOf(getSecretValues(secretName)),\nUser.class);\nString username = user.getUsername();\nString userPassword = user.getPassword();\nRegion region = Region.US_WEST_2;\nRdsClient rdsClient = RdsClient.builder()\n.region(region)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon Aurora example scenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"1. Return a list of the available DB engines\");\ndescribeDBEngines(rdsClient);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Create a custom parameter group\");\ncreateDBClusterParameterGroup(rdsClient, dbClusterGroupName,\ndbParameterGroupFamily);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"3. Get the parameter group\");\ndescribeDbClusterParameterGroups(rdsClient, dbClusterGroupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. Get the parameters in the group\");\ndescribeDbClusterParameters(rdsClient, dbClusterGroupName, 0);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nBasics 515\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"5. Modify the auto_increment_offset parameter\");\nmodifyDBClusterParas(rdsClient, dbClusterGroupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Display the updated parameter value\");\ndescribeDbClusterParameters(rdsClient, dbClusterGroupName, -1);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Get a list of allowed engine versions\");\ngetAllowedEngines(rdsClient, dbParameterGroupFamily);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Create an Aurora DB cluster database\");\nString arnClusterVal = createDBCluster(rdsClient, dbClusterGroupName,\ndbName, dbInstanceClusterIdentifier,\nusername, userPassword);\nSystem.out.println(\"The ARN of the cluster is \" + arnClusterVal);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"9. Wait for DB instance to be ready\");\nwaitForInstanceReady(rdsClient, dbInstanceClusterIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"10. Get a list of instance classes available for the\nselected engine\");\nString instanceClass = getListInstanceClasses(rdsClient);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"11. Create a database instance in the cluster.\");\nString clusterDBARN = createDBInstanceCluster(rdsClient,\ndbInstanceIdentifier, dbInstanceClusterIdentifier,\ninstanceClass);\nSystem.out.println(\"The ARN of the database is \" + clusterDBARN);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"12. Wait for DB instance to be ready\");\nwaitDBInstanceReady(rdsClient, dbInstanceIdentifier);\nBasics 516\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"13. Create a snapshot\");\ncreateDBClusterSnapshot(rdsClient, dbInstanceClusterIdentifier,\ndbSnapshotIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"14. Wait for DB snapshot to be ready\");\nwaitForSnapshotReady(rdsClient, dbSnapshotIdentifier,\ndbInstanceClusterIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"14. Delete the DB instance\");\ndeleteDatabaseInstance(rdsClient, dbInstanceIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"15. Delete the DB cluster\");\ndeleteCluster(rdsClient, dbInstanceClusterIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"16. Delete the DB cluster group\");\ndeleteDBClusterGroup(rdsClient, dbClusterGroupName, clusterDBARN);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The Scenario has successfully completed.", "mimetype": "text/plain", "start_char_idx": 826683, "end_char_idx": 830626, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d08c0d78-59ae-40b8-acdc-ca772c874ee5": {"__data__": {"id_": "d08c0d78-59ae-40b8-acdc-ca772c874ee5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b32e6ef9-10e5-46c6-86ef-c069e8a29153", "node_type": "1", "metadata": {}, "hash": "3f843e960c98d1a0e082947cbe1be0aca5fd69c27b727d29e79c29bc6d19a1fe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b311f2db-345b-42aa-ab1f-2e728ff07e9c", "node_type": "1", "metadata": {}, "hash": "f43150aa04b4969e5b3ecbf3f3c2bdb38509dd08c273437f2a6af0bb7a83215c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Wait for DB snapshot to be ready\");\nwaitForSnapshotReady(rdsClient, dbSnapshotIdentifier,\ndbInstanceClusterIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"14. Delete the DB instance\");\ndeleteDatabaseInstance(rdsClient, dbInstanceIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"15. Delete the DB cluster\");\ndeleteCluster(rdsClient, dbInstanceClusterIdentifier);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"16. Delete the DB cluster group\");\ndeleteDBClusterGroup(rdsClient, dbClusterGroupName, clusterDBARN);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The Scenario has successfully completed.\");\nSystem.out.println(DASHES);\nrdsClient.close();\n}\nprivate static SecretsManagerClient getSecretClient() {\nRegion region = Region.US_WEST_2;\nreturn SecretsManagerClient.builder()\n.region(region)\n.credentialsProvider(EnvironmentVariableCredentialsProvider.create())\n.build();\n}\nBasics 517\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static String getSecretValues(String secretName) {\nSecretsManagerClient secretClient = getSecretClient();\nGetSecretValueRequest valueRequest = GetSecretValueRequest.builder()\n.secretId(secretName)\n.build();\nGetSecretValueResponse valueResponse =\nsecretClient.getSecretValue(valueRequest);\nreturn valueResponse.secretString();\n}\npublic static void deleteDBClusterGroup(RdsClient rdsClient, String\ndbClusterGroupName, String clusterDBARN)\nthrows InterruptedException {\ntry {\nboolean isDataDel = false;\nboolean didFind;\nString instanceARN;\n// Make sure that the database has been deleted.\nwhile (!isDataDel) {\nDescribeDbInstancesResponse response =\nrdsClient.describeDBInstances();\nList instanceList = response.dbInstances();\nint listSize = instanceList.size();\ndidFind = false;\nint index = 1;\nfor (DBInstance instance : instanceList) {\ninstanceARN = instance.dbInstanceArn();\nif (instanceARN.compareTo(clusterDBARN) == 0) {\nSystem.out.println(clusterDBARN + \" still exists\");\ndidFind = true;\n}\nif ((index == listSize) && (!didFind)) {\n// Went through the entire list and did not find the\ndatabase ARN.\nisDataDel = true;\n}\nThread.sleep(sleepTime * 1000);\nindex++;\n}\n}\nBasics 518\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteDbClusterParameterGroupRequest clusterParameterGroupRequest =\nDeleteDbClusterParameterGroupRequest\n.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.build();\nrdsClient.deleteDBClusterParameterGroup(clusterParameterGroupRequest);\nSystem.out.println(dbClusterGroupName + \" was deleted.\");\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void deleteCluster(RdsClient rdsClient, String\ndbInstanceClusterIdentifier) {\ntry {\nDeleteDbClusterRequest deleteDbClusterRequest =\nDeleteDbClusterRequest.builder()\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.skipFinalSnapshot(true)\n.build();\nrdsClient.deleteDBCluster(deleteDbClusterRequest);\nSystem.out.println(dbInstanceClusterIdentifier + \" was deleted!\");\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void deleteDatabaseInstance(RdsClient rdsClient, String\ndbInstanceIdentifier) {\ntry {\nDeleteDbInstanceRequest deleteDbInstanceRequest =\nDeleteDbInstanceRequest.builder()\n.dbInstanceIdentifier(dbInstanceIdentifier)\n.deleteAutomatedBackups(true)\n.skipFinalSnapshot(true)\n.build();\nBasics 519\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteDbInstanceResponse response =\nrdsClient.deleteDBInstance(deleteDbInstanceRequest);\nSystem.out.println(\"The status of the database is \" +\nresponse.dbInstance().dbInstanceStatus());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void waitForSnapshotReady(RdsClient rdsClient, String\ndbSnapshotIdentifier,\nString dbInstanceClusterIdentifier) {\ntry {\nboolean snapshotReady = false;\nString snapshotReadyStr;\nSystem.out.println(\"Waiting for the snapshot to become available.\");\nDescribeDbClusterSnapshotsRequest snapshotsRequest =\nDescribeDbClusterSnapshotsRequest.builder()\n.dbClusterSnapshotIdentifier(dbSnapshotIdentifier)\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.build();\nwhile (!snapshotReady) {\nDescribeDbClusterSnapshotsResponse response =\nrdsClient.describeDBClusterSnapshots(snapshotsRequest);\nList snapshotList =\nresponse.dbClusterSnapshots();\nfor (DBClusterSnapshot snapshot : snapshotList) {\nsnapshotReadyStr = snapshot.status();\nif (snapshotReadyStr.contains(\"available\")) {\nsnapshotReady = true;\n} else {\nSystem.out.println(\".", "mimetype": "text/plain", "start_char_idx": 829889, "end_char_idx": 834573, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b311f2db-345b-42aa-ab1f-2e728ff07e9c": {"__data__": {"id_": "b311f2db-345b-42aa-ab1f-2e728ff07e9c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d08c0d78-59ae-40b8-acdc-ca772c874ee5", "node_type": "1", "metadata": {}, "hash": "18792e1ce49856d974d45839fc0d369b9c99628f68a28b4fea0ef96fe7cd6044", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dbe7368e-7963-4de5-b58c-8e512a86a120", "node_type": "1", "metadata": {}, "hash": "47a71e639af5c349533f6f9cf5d0cefb97371b2c58a9bcaef7492b6ce1110554", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nDescribeDbClusterSnapshotsRequest snapshotsRequest =\nDescribeDbClusterSnapshotsRequest.builder()\n.dbClusterSnapshotIdentifier(dbSnapshotIdentifier)\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.build();\nwhile (!snapshotReady) {\nDescribeDbClusterSnapshotsResponse response =\nrdsClient.describeDBClusterSnapshots(snapshotsRequest);\nList snapshotList =\nresponse.dbClusterSnapshots();\nfor (DBClusterSnapshot snapshot : snapshotList) {\nsnapshotReadyStr = snapshot.status();\nif (snapshotReadyStr.contains(\"available\")) {\nsnapshotReady = true;\n} else {\nSystem.out.println(\".\");\nThread.sleep(sleepTime * 5000);\n}\n}\n}\nSystem.out.println(\"The Snapshot is available!\");\n} catch (RdsException | InterruptedException e) {\nBasics 520\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void createDBClusterSnapshot(RdsClient rdsClient, String\ndbInstanceClusterIdentifier,\nString dbSnapshotIdentifier) {\ntry {\nCreateDbClusterSnapshotRequest snapshotRequest =\nCreateDbClusterSnapshotRequest.builder()\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.dbClusterSnapshotIdentifier(dbSnapshotIdentifier)\n.build();\nCreateDbClusterSnapshotResponse response =\nrdsClient.createDBClusterSnapshot(snapshotRequest);\nSystem.out.println(\"The Snapshot ARN is \" +\nresponse.dbClusterSnapshot().dbClusterSnapshotArn());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void waitDBInstanceReady(RdsClient rdsClient, String\ndbInstanceIdentifier) {\nboolean instanceReady = false;\nString instanceReadyStr;\nSystem.out.println(\"Waiting for instance to become available.\");\ntry {\nDescribeDbInstancesRequest instanceRequest =\nDescribeDbInstancesRequest.builder()\n.dbInstanceIdentifier(dbInstanceIdentifier)\n.build();\nString endpoint = \"\";\nwhile (!instanceReady) {\nDescribeDbInstancesResponse response =\nrdsClient.describeDBInstances(instanceRequest);\nList instanceList = response.dbInstances();\nfor (DBInstance instance : instanceList) {\ninstanceReadyStr = instance.dbInstanceStatus();\nBasics 521\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (instanceReadyStr.contains(\"available\")) {\nendpoint = instance.endpoint().address();\ninstanceReady = true;\n} else {\nSystem.out.print(\".\");\nThread.sleep(sleepTime * 1000);\n}\n}\n}\nSystem.out.println(\"Database instance is available! The connection\nendpoint is \" + endpoint);\n} catch (RdsException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static String createDBInstanceCluster(RdsClient rdsClient,\nString dbInstanceIdentifier,\nString dbInstanceClusterIdentifier,\nString instanceClass) {\ntry {\nCreateDbInstanceRequest instanceRequest =\nCreateDbInstanceRequest.builder()\n.dbInstanceIdentifier(dbInstanceIdentifier)\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.engine(\"aurora-mysql\")\n.dbInstanceClass(instanceClass)\n.build();\nCreateDbInstanceResponse response =\nrdsClient.createDBInstance(instanceRequest);\nSystem.out.print(\"The status is \" +\nresponse.dbInstance().dbInstanceStatus());\nreturn response.dbInstance().dbInstanceArn();\n} catch (RdsException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nBasics 522\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static String getListInstanceClasses(RdsClient rdsClient) {\ntry {\nDescribeOrderableDbInstanceOptionsRequest optionsRequest =\nDescribeOrderableDbInstanceOptionsRequest\n.builder()\n.engine(\"aurora-mysql\")\n.maxRecords(20)\n.build();\nDescribeOrderableDbInstanceOptionsResponse response = rdsClient\n.describeOrderableDBInstanceOptions(optionsRequest);\nList instanceOptions =\nresponse.orderableDBInstanceOptions();\nString instanceClass = \"\";\nfor (OrderableDBInstanceOption instanceOption : instanceOptions) {\ninstanceClass = instanceOption.dbInstanceClass();\nSystem.out.println(\"The instance class is \" +\ninstanceOption.dbInstanceClass());\nSystem.out.println(\"The engine version is \" +\ninstanceOption.engineVersion());\n}\nreturn instanceClass;\n} catch (RdsException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n// Waits until the database instance is available.\npublic static void waitForInstanceReady(RdsClient rdsClient, String\ndbClusterIdentifier) {\nboolean instanceReady = false;\nString instanceReadyStr;\nSystem.out.println(\"Waiting for instance to become available.", "mimetype": "text/plain", "start_char_idx": 833978, "end_char_idx": 838429, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "dbe7368e-7963-4de5-b58c-8e512a86a120": {"__data__": {"id_": "dbe7368e-7963-4de5-b58c-8e512a86a120", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b311f2db-345b-42aa-ab1f-2e728ff07e9c", "node_type": "1", "metadata": {}, "hash": "f43150aa04b4969e5b3ecbf3f3c2bdb38509dd08c273437f2a6af0bb7a83215c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e061ab11-ab3b-42b4-a6fb-98bc8c7e2e35", "node_type": "1", "metadata": {}, "hash": "e7bde9b380ad71223be83b3cdeddcad15acf07418ee7fa47fc0d30f7645dd927", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static void waitForInstanceReady(RdsClient rdsClient, String\ndbClusterIdentifier) {\nboolean instanceReady = false;\nString instanceReadyStr;\nSystem.out.println(\"Waiting for instance to become available.\");\ntry {\nDescribeDbClustersRequest instanceRequest =\nDescribeDbClustersRequest.builder()\n.dbClusterIdentifier(dbClusterIdentifier)\n.build();\nwhile (!instanceReady) {\nBasics 523\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeDbClustersResponse response =\nrdsClient.describeDBClusters(instanceRequest);\nList clusterList = response.dbClusters();\nfor (DBCluster cluster : clusterList) {\ninstanceReadyStr = cluster.status();\nif (instanceReadyStr.contains(\"available\")) {\ninstanceReady = true;\n} else {\nSystem.out.print(\".\");\nThread.sleep(sleepTime * 1000);\n}\n}\n}\nSystem.out.println(\"Database cluster is available!\");\n} catch (RdsException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static String createDBCluster(RdsClient rdsClient, String\ndbParameterGroupFamily, String dbName,\nString dbClusterIdentifier, String userName, String password) {\ntry {\nCreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder()\n.databaseName(dbName)\n.dbClusterIdentifier(dbClusterIdentifier)\n.dbClusterParameterGroupName(dbParameterGroupFamily)\n.engine(\"aurora-mysql\")\n.masterUsername(userName)\n.masterUserPassword(password)\n.build();\nCreateDbClusterResponse response =\nrdsClient.createDBCluster(clusterRequest);\nreturn response.dbCluster().dbClusterArn();\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\nBasics 524\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Get a list of allowed engine versions.\npublic static void getAllowedEngines(RdsClient rdsClient, String\ndbParameterGroupFamily) {\ntry {\nDescribeDbEngineVersionsRequest versionsRequest =\nDescribeDbEngineVersionsRequest.builder()\n.dbParameterGroupFamily(dbParameterGroupFamily)\n.engine(\"aurora-mysql\")\n.build();\nDescribeDbEngineVersionsResponse response =\nrdsClient.describeDBEngineVersions(versionsRequest);\nList dbEngines = response.dbEngineVersions();\nfor (DBEngineVersion dbEngine : dbEngines) {\nSystem.out.println(\"The engine version is \" +\ndbEngine.engineVersion());\nSystem.out.println(\"The engine description is \" +\ndbEngine.dbEngineDescription());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n// Modify the auto_increment_offset parameter.\npublic static void modifyDBClusterParas(RdsClient rdsClient, String\ndClusterGroupName) {\ntry {\nParameter parameter1 = Parameter.builder()\n.parameterName(\"auto_increment_offset\")\n.applyMethod(\"immediate\")\n.parameterValue(\"5\")\n.build();\nList paraList = new ArrayList<>();\nparaList.add(parameter1);\nModifyDbClusterParameterGroupRequest groupRequest =\nModifyDbClusterParameterGroupRequest.builder()\n.dbClusterParameterGroupName(dClusterGroupName)\n.parameters(paraList)\n.build();\nBasics 525\nAWS SDK for Java 2.x Developer Guide for version 2.x\nModifyDbClusterParameterGroupResponse response =\nrdsClient.modifyDBClusterParameterGroup(groupRequest);\nSystem.out.println(\n\"The parameter group \" + response.dbClusterParameterGroupName()\n+ \" was successfully modified\");\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void describeDbClusterParameters(RdsClient rdsClient, String\ndbCLusterGroupName, int flag) {\ntry {\nDescribeDbClusterParametersRequest dbParameterGroupsRequest;\nif (flag == 0) {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\n.build();\n} else {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\n.source(\"user\")\n.build();\n}\nDescribeDbClusterParametersResponse response = rdsClient\n.describeDBClusterParameters(dbParameterGroupsRequest);\nList dbParameters = response.parameters();\nString paraName;\nfor (Parameter para : dbParameters) {\n// Only print out information about either auto_increment_offset or\n// auto_increment_increment.", "mimetype": "text/plain", "start_char_idx": 838221, "end_char_idx": 842392, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e061ab11-ab3b-42b4-a6fb-98bc8c7e2e35": {"__data__": {"id_": "e061ab11-ab3b-42b4-a6fb-98bc8c7e2e35", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dbe7368e-7963-4de5-b58c-8e512a86a120", "node_type": "1", "metadata": {}, "hash": "47a71e639af5c349533f6f9cf5d0cefb97371b2c58a9bcaef7492b6ce1110554", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6309fda8-c605-4685-81cc-fda613c092fa", "node_type": "1", "metadata": {}, "hash": "c7c3878559dc66c8762ed7a16280a332ca5e50b2c2fd20de025de02687dce955", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "paraName = para.parameterName();\nif ((paraName.compareTo(\"auto_increment_offset\") == 0)\n|| (paraName.compareTo(\"auto_increment_increment \") == 0)) {\nSystem.out.println(\"*** The parameter name is \" + paraName);\nSystem.out.println(\"*** The parameter value is \" +\npara.parameterValue());\nBasics 526\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"*** The parameter data type is \" +\npara.dataType());\nSystem.out.println(\"*** The parameter description is \" +\npara.description());\nSystem.out.println(\"*** The parameter allowed values is \" +\npara.allowedValues());\n}\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void describeDbClusterParameterGroups(RdsClient rdsClient, String\ndbClusterGroupName) {\ntry {\nDescribeDbClusterParameterGroupsRequest groupsRequest =\nDescribeDbClusterParameterGroupsRequest.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.maxRecords(20)\n.build();\nList groups =\nrdsClient.describeDBClusterParameterGroups(groupsRequest)\n.dbClusterParameterGroups();\nfor (DBClusterParameterGroup group : groups) {\nSystem.out.println(\"The group name is \" +\ngroup.dbClusterParameterGroupName());\nSystem.out.println(\"The group ARN is \" +\ngroup.dbClusterParameterGroupArn());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void createDBClusterParameterGroup(RdsClient rdsClient, String\ndbClusterGroupName,\nString dbParameterGroupFamily) {\ntry {\nBasics 527\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateDbClusterParameterGroupRequest groupRequest =\nCreateDbClusterParameterGroupRequest.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.dbParameterGroupFamily(dbParameterGroupFamily)\n.description(\"Created by using the AWS SDK for Java\")\n.build();\nCreateDbClusterParameterGroupResponse response =\nrdsClient.createDBClusterParameterGroup(groupRequest);\nSystem.out.println(\"The group name is \" +\nresponse.dbClusterParameterGroup().dbClusterParameterGroupName());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\npublic static void describeDBEngines(RdsClient rdsClient) {\ntry {\nDescribeDbEngineVersionsRequest engineVersionsRequest =\nDescribeDbEngineVersionsRequest.builder()\n.engine(\"aurora-mysql\")\n.defaultOnly(true)\n.maxRecords(20)\n.build();\nDescribeDbEngineVersionsResponse response =\nrdsClient.describeDBEngineVersions(engineVersionsRequest);\nList engines = response.dbEngineVersions();\n// Get all DBEngineVersion objects.\nfor (DBEngineVersion engineOb : engines) {\nSystem.out.println(\"The name of the DB parameter group family for\nthe database engine is \"\n+ engineOb.dbParameterGroupFamily());\nSystem.out.println(\"The name of the database engine \" +\nengineOb.engine());\nSystem.out.println(\"The version number of the database engine \" +\nengineOb.engineVersion());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nBasics 528\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 CreateDBCluster\n\u2022 CreateDBClusterParameterGroup\n\u2022 CreateDBClusterSnapshot\n\u2022 CreateDBInstance\n\u2022 DeleteDBCluster\n\u2022 DeleteDBClusterParameterGroup\n\u2022 DeleteDBInstance\n\u2022 DescribeDBClusterParameterGroups\n\u2022 DescribeDBClusterParameters\n\u2022 DescribeDBClusterSnapshots\n\u2022 DescribeDBClusters\n\u2022 DescribeDBEngineVersions\n\u2022 DescribeDBInstances\n\u2022 DescribeOrderableDBInstanceOptions\n\u2022 ModifyDBClusterParameterGroup\nActions\nCreateDBCluster\nThe following code example shows how to use CreateDBCluster.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 529\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static String createDBCluster(RdsClient rdsClient, String\ndbParameterGroupFamily, String dbName,\nString dbClusterIdentifier, String userName, String password) {\ntry {\nCreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder()\n.databaseName(dbName)\n.dbClusterIdentifier(dbClusterIdentifier)\n.dbClusterParameterGroupName(dbParameterGroupFamily)\n.engine(\"aurora-mysql\")\n.masterUsername(userName)\n.masterUserPassword(password)\n.build();\nCreateDbClusterResponse response =\nrdsClient.createDBCluster(clusterRequest);\nreturn response.dbCluster().dbClusterArn();\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateDBCluster in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 842393, "end_char_idx": 847012, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6309fda8-c605-4685-81cc-fda613c092fa": {"__data__": {"id_": "6309fda8-c605-4685-81cc-fda613c092fa", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e061ab11-ab3b-42b4-a6fb-98bc8c7e2e35", "node_type": "1", "metadata": {}, "hash": "e7bde9b380ad71223be83b3cdeddcad15acf07418ee7fa47fc0d30f7645dd927", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bd1027e9-5bfd-4c8a-a4bf-764cb710ca81", "node_type": "1", "metadata": {}, "hash": "81f4d73e1190103523e357b026fcfa93d36121e5ea4933a0efc84d748f64d9ae", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 529\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static String createDBCluster(RdsClient rdsClient, String\ndbParameterGroupFamily, String dbName,\nString dbClusterIdentifier, String userName, String password) {\ntry {\nCreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder()\n.databaseName(dbName)\n.dbClusterIdentifier(dbClusterIdentifier)\n.dbClusterParameterGroupName(dbParameterGroupFamily)\n.engine(\"aurora-mysql\")\n.masterUsername(userName)\n.masterUserPassword(password)\n.build();\nCreateDbClusterResponse response =\nrdsClient.createDBCluster(clusterRequest);\nreturn response.dbCluster().dbClusterArn();\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateDBCluster in AWS SDK for Java 2.x API Reference.\nCreateDBClusterParameterGroup\nThe following code example shows how to use CreateDBClusterParameterGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void createDBClusterParameterGroup(RdsClient rdsClient, String\ndbClusterGroupName,\nActions 530\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString dbParameterGroupFamily) {\ntry {\nCreateDbClusterParameterGroupRequest groupRequest =\nCreateDbClusterParameterGroupRequest.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.dbParameterGroupFamily(dbParameterGroupFamily)\n.description(\"Created by using the AWS SDK for Java\")\n.build();\nCreateDbClusterParameterGroupResponse response =\nrdsClient.createDBClusterParameterGroup(groupRequest);\nSystem.out.println(\"The group name is \" +\nresponse.dbClusterParameterGroup().dbClusterParameterGroupName());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see CreateDBClusterParameterGroup in AWS SDK for Java 2.x API Reference.\nCreateDBClusterSnapshot\nThe following code example shows how to use CreateDBClusterSnapshot.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void createDBClusterSnapshot(RdsClient rdsClient, String\ndbInstanceClusterIdentifier,\nString dbSnapshotIdentifier) {\ntry {\nCreateDbClusterSnapshotRequest snapshotRequest =\nCreateDbClusterSnapshotRequest.builder()\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\nActions 531\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.dbClusterSnapshotIdentifier(dbSnapshotIdentifier)\n.build();\nCreateDbClusterSnapshotResponse response =\nrdsClient.createDBClusterSnapshot(snapshotRequest);\nSystem.out.println(\"The Snapshot ARN is \" +\nresponse.dbClusterSnapshot().dbClusterSnapshotArn());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see CreateDBClusterSnapshot in AWS SDK for Java 2.x API Reference.\nCreateDBInstance\nThe following code example shows how to use CreateDBInstance.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static String createDBInstanceCluster(RdsClient rdsClient,\nString dbInstanceIdentifier,\nString dbInstanceClusterIdentifier,\nString instanceClass) {\ntry {\nCreateDbInstanceRequest instanceRequest =\nCreateDbInstanceRequest.builder()\n.dbInstanceIdentifier(dbInstanceIdentifier)\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.engine(\"aurora-mysql\")\n.dbInstanceClass(instanceClass)\n.build();\nActions 532\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateDbInstanceResponse response =\nrdsClient.createDBInstance(instanceRequest);\nSystem.out.print(\"The status is \" +\nresponse.dbInstance().dbInstanceStatus());\nreturn response.dbInstance().dbInstanceArn();\n} catch (RdsException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateDBInstance in AWS SDK for Java 2.x API Reference.\nDeleteDBCluster\nThe following code example shows how to use DeleteDBCluster.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void deleteCluster(RdsClient rdsClient, String\ndbInstanceClusterIdentifier) {\ntry {\nDeleteDbClusterRequest deleteDbClusterRequest =\nDeleteDbClusterRequest.builder()\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.skipFinalSnapshot(true)\n.build();\nrdsClient.deleteDBCluster(deleteDbClusterRequest);\nSystem.out.println(dbInstanceClusterIdentifier + \" was deleted!", "mimetype": "text/plain", "start_char_idx": 846096, "end_char_idx": 850782, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bd1027e9-5bfd-4c8a-a4bf-764cb710ca81": {"__data__": {"id_": "bd1027e9-5bfd-4c8a-a4bf-764cb710ca81", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6309fda8-c605-4685-81cc-fda613c092fa", "node_type": "1", "metadata": {}, "hash": "c7c3878559dc66c8762ed7a16280a332ca5e50b2c2fd20de025de02687dce955", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5dc465b2-16e7-4216-8033-32335e23e84c", "node_type": "1", "metadata": {}, "hash": "b37197bd803962920dca7eaaaae197dc37cf9886040d3ecead2497d16adc56a4", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteDBCluster\nThe following code example shows how to use DeleteDBCluster.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void deleteCluster(RdsClient rdsClient, String\ndbInstanceClusterIdentifier) {\ntry {\nDeleteDbClusterRequest deleteDbClusterRequest =\nDeleteDbClusterRequest.builder()\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.skipFinalSnapshot(true)\n.build();\nrdsClient.deleteDBCluster(deleteDbClusterRequest);\nSystem.out.println(dbInstanceClusterIdentifier + \" was deleted!\");\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nActions 533\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DeleteDBCluster in AWS SDK for Java 2.x API Reference.\nDeleteDBClusterParameterGroup\nThe following code example shows how to use DeleteDBClusterParameterGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void deleteDBClusterGroup(RdsClient rdsClient, String\ndbClusterGroupName, String clusterDBARN)\nthrows InterruptedException {\ntry {\nboolean isDataDel = false;\nboolean didFind;\nString instanceARN;\n// Make sure that the database has been deleted.\nwhile (!isDataDel) {\nDescribeDbInstancesResponse response =\nrdsClient.describeDBInstances();\nList instanceList = response.dbInstances();\nint listSize = instanceList.size();\ndidFind = false;\nint index = 1;\nfor (DBInstance instance : instanceList) {\ninstanceARN = instance.dbInstanceArn();\nif (instanceARN.compareTo(clusterDBARN) == 0) {\nSystem.out.println(clusterDBARN + \" still exists\");\ndidFind = true;\n}\nif ((index == listSize) && (!didFind)) {\nActions 534\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Went through the entire list and did not find the\ndatabase ARN.\nisDataDel = true;\n}\nThread.sleep(sleepTime * 1000);\nindex++;\n}\n}\nDeleteDbClusterParameterGroupRequest clusterParameterGroupRequest =\nDeleteDbClusterParameterGroupRequest\n.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.build();\nrdsClient.deleteDBClusterParameterGroup(clusterParameterGroupRequest);\nSystem.out.println(dbClusterGroupName + \" was deleted.\");\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DeleteDBClusterParameterGroup in AWS SDK for Java 2.x API Reference.\nDeleteDBInstance\nThe following code example shows how to use DeleteDBInstance.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void deleteDatabaseInstance(RdsClient rdsClient, String\ndbInstanceIdentifier) {\ntry {\nActions 535\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteDbInstanceRequest deleteDbInstanceRequest =\nDeleteDbInstanceRequest.builder()\n.dbInstanceIdentifier(dbInstanceIdentifier)\n.deleteAutomatedBackups(true)\n.skipFinalSnapshot(true)\n.build();\nDeleteDbInstanceResponse response =\nrdsClient.deleteDBInstance(deleteDbInstanceRequest);\nSystem.out.println(\"The status of the database is \" +\nresponse.dbInstance().dbInstanceStatus());\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DeleteDBInstance in AWS SDK for Java 2.x API Reference.\nDescribeDBClusterParameterGroups\nThe following code example shows how to use DescribeDBClusterParameterGroups.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 850186, "end_char_idx": 853855, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5dc465b2-16e7-4216-8033-32335e23e84c": {"__data__": {"id_": "5dc465b2-16e7-4216-8033-32335e23e84c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bd1027e9-5bfd-4c8a-a4bf-764cb710ca81", "node_type": "1", "metadata": {}, "hash": "81f4d73e1190103523e357b026fcfa93d36121e5ea4933a0efc84d748f64d9ae", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "33a84877-1f76-4c11-b610-586e7f8b2d4d", "node_type": "1", "metadata": {}, "hash": "92811d642c1d88862e3e07954c7cb7693b84295e103e4a5611f7e83a20315f01", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeDBClusterParameterGroups\nThe following code example shows how to use DescribeDBClusterParameterGroups.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDbClusterParameterGroups(RdsClient rdsClient, String\ndbClusterGroupName) {\ntry {\nDescribeDbClusterParameterGroupsRequest groupsRequest =\nDescribeDbClusterParameterGroupsRequest.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.maxRecords(20)\n.build();\nActions 536\nAWS SDK for Java 2.x Developer Guide for version 2.x\nList groups =\nrdsClient.describeDBClusterParameterGroups(groupsRequest)\n.dbClusterParameterGroups();\nfor (DBClusterParameterGroup group : groups) {\nSystem.out.println(\"The group name is \" +\ngroup.dbClusterParameterGroupName());\nSystem.out.println(\"The group ARN is \" +\ngroup.dbClusterParameterGroupArn());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBClusterParameterGroups in AWS SDK for Java 2.x API\nReference.\nDescribeDBClusterParameters\nThe following code example shows how to use DescribeDBClusterParameters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDbClusterParameters(RdsClient rdsClient, String\ndbCLusterGroupName, int flag) {\ntry {\nDescribeDbClusterParametersRequest dbParameterGroupsRequest;\nif (flag == 0) {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\nActions 537\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n} else {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\n.source(\"user\")\n.build();\n}\nDescribeDbClusterParametersResponse response = rdsClient\n.describeDBClusterParameters(dbParameterGroupsRequest);\nList dbParameters = response.parameters();\nString paraName;\nfor (Parameter para : dbParameters) {\n// Only print out information about either auto_increment_offset or\n// auto_increment_increment.\nparaName = para.parameterName();\nif ((paraName.compareTo(\"auto_increment_offset\") == 0)\n|| (paraName.compareTo(\"auto_increment_increment \") == 0)) {\nSystem.out.println(\"*** The parameter name is \" + paraName);\nSystem.out.println(\"*** The parameter value is \" +\npara.parameterValue());\nSystem.out.println(\"*** The parameter data type is \" +\npara.dataType());\nSystem.out.println(\"*** The parameter description is \" +\npara.description());\nSystem.out.println(\"*** The parameter allowed values is \" +\npara.allowedValues());\n}\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBClusterParameters in AWS SDK for Java 2.x API Reference.\nDescribeDBClusterSnapshots\nThe following code example shows how to use DescribeDBClusterSnapshots.\nActions 538\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void waitForSnapshotReady(RdsClient rdsClient, String\ndbSnapshotIdentifier,\nString dbInstanceClusterIdentifier) {\ntry {\nboolean snapshotReady = false;\nString snapshotReadyStr;\nSystem.out.println(\"Waiting for the snapshot to become available.\");\nDescribeDbClusterSnapshotsRequest snapshotsRequest =\nDescribeDbClusterSnapshotsRequest.builder()\n.dbClusterSnapshotIdentifier(dbSnapshotIdentifier)\n.dbClusterIdentifier(dbInstanceClusterIdentifier)\n.build();\nwhile (!snapshotReady) {\nDescribeDbClusterSnapshotsResponse response =\nrdsClient.describeDBClusterSnapshots(snapshotsRequest);\nList snapshotList =\nresponse.dbClusterSnapshots();\nfor (DBClusterSnapshot snapshot : snapshotList) {\nsnapshotReadyStr = snapshot.status();\nif (snapshotReadyStr.contains(\"available\")) {\nsnapshotReady = true;\n} else {\nSystem.out.println(\".\");\nThread.sleep(sleepTime * 5000);\n}\n}\n}\nSystem.out.println(\"The Snapshot is available!\");\n} catch (RdsException | InterruptedException e) {\nSystem.out.println(e.getLocalizedMessage());\nActions 539\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBClusterSnapshots in AWS SDK for Java 2.x API Reference.\nDescribeDBClusters\nThe following code example shows how to use DescribeDBClusters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 853604, "end_char_idx": 858280, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "33a84877-1f76-4c11-b610-586e7f8b2d4d": {"__data__": {"id_": "33a84877-1f76-4c11-b610-586e7f8b2d4d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5dc465b2-16e7-4216-8033-32335e23e84c", "node_type": "1", "metadata": {}, "hash": "b37197bd803962920dca7eaaaae197dc37cf9886040d3ecead2497d16adc56a4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "16577af4-0cef-49bd-9ddd-69952167c15a", "node_type": "1", "metadata": {}, "hash": "f8c95fe06e83a96d1f6ee0995b004ac3e93eca15ee8d3f19b65be1adac38fac0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nThread.sleep(sleepTime * 5000);\n}\n}\n}\nSystem.out.println(\"The Snapshot is available!\");\n} catch (RdsException | InterruptedException e) {\nSystem.out.println(e.getLocalizedMessage());\nActions 539\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBClusterSnapshots in AWS SDK for Java 2.x API Reference.\nDescribeDBClusters\nThe following code example shows how to use DescribeDBClusters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDbClusterParameters(RdsClient rdsClient, String\ndbCLusterGroupName, int flag) {\ntry {\nDescribeDbClusterParametersRequest dbParameterGroupsRequest;\nif (flag == 0) {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\n.build();\n} else {\ndbParameterGroupsRequest =\nDescribeDbClusterParametersRequest.builder()\n.dbClusterParameterGroupName(dbCLusterGroupName)\n.source(\"user\")\n.build();\n}\nDescribeDbClusterParametersResponse response = rdsClient\n.describeDBClusterParameters(dbParameterGroupsRequest);\nList dbParameters = response.parameters();\nString paraName;\nfor (Parameter para : dbParameters) {\n// Only print out information about either auto_increment_offset or\nActions 540\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// auto_increment_increment.\nparaName = para.parameterName();\nif ((paraName.compareTo(\"auto_increment_offset\") == 0)\n|| (paraName.compareTo(\"auto_increment_increment \") == 0)) {\nSystem.out.println(\"*** The parameter name is \" + paraName);\nSystem.out.println(\"*** The parameter value is \" +\npara.parameterValue());\nSystem.out.println(\"*** The parameter data type is \" +\npara.dataType());\nSystem.out.println(\"*** The parameter description is \" +\npara.description());\nSystem.out.println(\"*** The parameter allowed values is \" +\npara.allowedValues());\n}\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBClusters in AWS SDK for Java 2.x API Reference.\nDescribeDBEngineVersions\nThe following code example shows how to use DescribeDBEngineVersions.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDBEngines(RdsClient rdsClient) {\ntry {\nDescribeDbEngineVersionsRequest engineVersionsRequest =\nDescribeDbEngineVersionsRequest.builder()\n.engine(\"aurora-mysql\")\nActions 541\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.defaultOnly(true)\n.maxRecords(20)\n.build();\nDescribeDbEngineVersionsResponse response =\nrdsClient.describeDBEngineVersions(engineVersionsRequest);\nList engines = response.dbEngineVersions();\n// Get all DBEngineVersion objects.\nfor (DBEngineVersion engineOb : engines) {\nSystem.out.println(\"The name of the DB parameter group family for\nthe database engine is \"\n+ engineOb.dbParameterGroupFamily());\nSystem.out.println(\"The name of the database engine \" +\nengineOb.engine());\nSystem.out.println(\"The version number of the database engine \" +\nengineOb.engineVersion());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBEngineVersions in AWS SDK for Java 2.x API Reference.\nDescribeDBInstances\nThe following code example shows how to use DescribeDBInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Waits until the database instance is available.\nActions 542\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void waitForInstanceReady(RdsClient rdsClient, String\ndbClusterIdentifier) {\nboolean instanceReady = false;\nString instanceReadyStr;\nSystem.out.println(\"Waiting for instance to become available.\");\ntry {\nDescribeDbClustersRequest instanceRequest =\nDescribeDbClustersRequest.builder()\n.dbClusterIdentifier(dbClusterIdentifier)\n.build();\nwhile (!instanceReady) {\nDescribeDbClustersResponse response =\nrdsClient.describeDBClusters(instanceRequest);\nList clusterList = response.dbClusters();\nfor (DBCluster cluster : clusterList) {\ninstanceReadyStr = cluster.status();\nif (instanceReadyStr.contains(\"available\")) {\ninstanceReady = true;\n} else {\nSystem.out.print(\".\");\nThread.sleep(sleepTime * 1000);\n}\n}\n}\nSystem.out.println(\"Database cluster is available!", "mimetype": "text/plain", "start_char_idx": 857696, "end_char_idx": 862217, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "16577af4-0cef-49bd-9ddd-69952167c15a": {"__data__": {"id_": "16577af4-0cef-49bd-9ddd-69952167c15a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "33a84877-1f76-4c11-b610-586e7f8b2d4d", "node_type": "1", "metadata": {}, "hash": "92811d642c1d88862e3e07954c7cb7693b84295e103e4a5611f7e83a20315f01", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "95a44b1a-c6b9-4f73-acf8-3d0798376a2c", "node_type": "1", "metadata": {}, "hash": "3a13aed6cf9bb955a92c7fea243473994267b073d47d37735e50ce9c34983cca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Waits until the database instance is available.\nActions 542\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void waitForInstanceReady(RdsClient rdsClient, String\ndbClusterIdentifier) {\nboolean instanceReady = false;\nString instanceReadyStr;\nSystem.out.println(\"Waiting for instance to become available.\");\ntry {\nDescribeDbClustersRequest instanceRequest =\nDescribeDbClustersRequest.builder()\n.dbClusterIdentifier(dbClusterIdentifier)\n.build();\nwhile (!instanceReady) {\nDescribeDbClustersResponse response =\nrdsClient.describeDBClusters(instanceRequest);\nList clusterList = response.dbClusters();\nfor (DBCluster cluster : clusterList) {\ninstanceReadyStr = cluster.status();\nif (instanceReadyStr.contains(\"available\")) {\ninstanceReady = true;\n} else {\nSystem.out.print(\".\");\nThread.sleep(sleepTime * 1000);\n}\n}\n}\nSystem.out.println(\"Database cluster is available!\");\n} catch (RdsException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeDBInstances in AWS SDK for Java 2.x API Reference.\nDescribeOrderableDBInstanceOptions\nThe following code example shows how to use DescribeOrderableDBInstanceOptions.\nActions 543\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDBEngines(RdsClient rdsClient) {\ntry {\nDescribeDbEngineVersionsRequest engineVersionsRequest =\nDescribeDbEngineVersionsRequest.builder()\n.engine(\"aurora-mysql\")\n.defaultOnly(true)\n.maxRecords(20)\n.build();\nDescribeDbEngineVersionsResponse response =\nrdsClient.describeDBEngineVersions(engineVersionsRequest);\nList engines = response.dbEngineVersions();\n// Get all DBEngineVersion objects.\nfor (DBEngineVersion engineOb : engines) {\nSystem.out.println(\"The name of the DB parameter group family for\nthe database engine is \"\n+ engineOb.dbParameterGroupFamily());\nSystem.out.println(\"The name of the database engine \" +\nengineOb.engine());\nSystem.out.println(\"The version number of the database engine \" +\nengineOb.engineVersion());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeOrderableDBInstanceOptions in AWS SDK for Java 2.x API\nReference.\nActions 544\nAWS SDK for Java 2.x Developer Guide for version 2.x\nModifyDBClusterParameterGroup\nThe following code example shows how to use ModifyDBClusterParameterGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeDbClusterParameterGroups(RdsClient rdsClient, String\ndbClusterGroupName) {\ntry {\nDescribeDbClusterParameterGroupsRequest groupsRequest =\nDescribeDbClusterParameterGroupsRequest.builder()\n.dbClusterParameterGroupName(dbClusterGroupName)\n.maxRecords(20)\n.build();\nList groups =\nrdsClient.describeDBClusterParameterGroups(groupsRequest)\n.dbClusterParameterGroups();\nfor (DBClusterParameterGroup group : groups) {\nSystem.out.println(\"The group name is \" +\ngroup.dbClusterParameterGroupName());\nSystem.out.println(\"The group ARN is \" +\ngroup.dbClusterParameterGroupArn());\n}\n} catch (RdsException e) {\nSystem.out.println(e.getLocalizedMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see ModifyDBClusterParameterGroup in AWS SDK for Java 2.x API Reference.\nActions 545\nAWS SDK for Java 2.x Developer Guide for version 2.x\nScenarios\nCreate an Aurora Serverless work item tracker\nThe following code example shows how to create a web application that tracks work items in an\nAmazon Aurora Serverless database and uses Amazon Simple Email Service (Amazon SES) to send\nreports.\nSDK for Java 2.x\nShows how to create a web application that tracks and reports on work items stored in an\nAmazon RDS database.\nFor complete source code and instructions on how to set up a Spring REST API that queries\nAmazon Aurora Serverless data and for use by a React application, see the full example on\nGitHub.\nFor complete source code and instructions on how to set up and run an example that uses the\nJDBC API, see the full example on GitHub.\nServices used in this example\n\u2022 Aurora\n\u2022 Amazon RDS\n\u2022 Amazon RDS Data Service\n\u2022 Amazon SES\nAuto Scaling examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Auto Scaling.\nBasics are code examples that show you how to perform the essential operations within a service.", "mimetype": "text/plain", "start_char_idx": 861323, "end_char_idx": 865953, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "95a44b1a-c6b9-4f73-acf8-3d0798376a2c": {"__data__": {"id_": "95a44b1a-c6b9-4f73-acf8-3d0798376a2c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "16577af4-0cef-49bd-9ddd-69952167c15a", "node_type": "1", "metadata": {}, "hash": "f8c95fe06e83a96d1f6ee0995b004ac3e93eca15ee8d3f19b65be1adac38fac0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dbca4706-5dec-43de-970f-ab310f50cafd", "node_type": "1", "metadata": {}, "hash": "153ca19911c32e47c6343d95eddfd7688b90e61bc70ac476731ba174aab4f505", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SDK for Java 2.x\nShows how to create a web application that tracks and reports on work items stored in an\nAmazon RDS database.\nFor complete source code and instructions on how to set up a Spring REST API that queries\nAmazon Aurora Serverless data and for use by a React application, see the full example on\nGitHub.\nFor complete source code and instructions on how to set up and run an example that uses the\nJDBC API, see the full example on GitHub.\nServices used in this example\n\u2022 Aurora\n\u2022 Amazon RDS\n\u2022 Amazon RDS Data Service\n\u2022 Amazon SES\nAuto Scaling examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Auto Scaling.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nScenarios 546\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello Auto Scaling\nThe following code examples show how to get started using Auto Scaling.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.autoscaling.AutoScalingClient;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;\nimport java.util.List;\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeAutoScalingGroups {\npublic static void main(String[] args) throws InterruptedException {\nAutoScalingClient autoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\ndescribeGroups(autoScalingClient);\n}\npublic static void describeGroups(AutoScalingClient autoScalingClient) {\nAuto Scaling 547\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeAutoScalingGroupsResponse response =\nautoScalingClient.describeAutoScalingGroups();\nList groups = response.autoScalingGroups();\ngroups.forEach(group -> {\nSystem.out.println(\"Group Name: \" + group.autoScalingGroupName());\nSystem.out.println(\"Group ARN: \" + group.autoScalingGroupARN());\n});\n}\n}\n\u2022 For API details, see DescribeAutoScalingGroups in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create an Amazon EC2 Auto Scaling group with a launch template and Availability Zones, and\nget information about running instances.\n\u2022 Enable Amazon CloudWatch metrics collection.\n\u2022 Update the group's desired capacity and wait for an instance to start.\n\u2022 Terminate an instance in the group.\n\u2022 List scaling activities that occur in response to user requests and capacity changes.\n\u2022 Get statistics for CloudWatch metrics, then clean up resources.\nBasics 548\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* In addition, create a launch template. For more information, see the\n* following topic:\n*\n* https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-\ntemplates.html#create-launch-template\n*\n* This code example performs the following operations:\n* 1. Creates an Auto Scaling group using an AutoScalingWaiter.\n* 2. Gets a specific Auto Scaling group and returns an instance Id value.\n* 3. Describes Auto Scaling with the Id value.\n* 4. Enables metrics collection.\n* 5. Update an Auto Scaling group.\n* 6. Describes Account details.\n* 7. Describe account details\"\n* 8.", "mimetype": "text/plain", "start_char_idx": 865128, "end_char_idx": 869734, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "dbca4706-5dec-43de-970f-ab310f50cafd": {"__data__": {"id_": "dbca4706-5dec-43de-970f-ab310f50cafd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "95a44b1a-c6b9-4f73-acf8-3d0798376a2c", "node_type": "1", "metadata": {}, "hash": "3a13aed6cf9bb955a92c7fea243473994267b073d47d37735e50ce9c34983cca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8fcab725-6697-4f99-b9fb-ef1afe18f980", "node_type": "1", "metadata": {}, "hash": "627f517bca42273f39f95a89ac32cb788c9c06819abecd062304d3f76c9ef3f2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* In addition, create a launch template. For more information, see the\n* following topic:\n*\n* https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-\ntemplates.html#create-launch-template\n*\n* This code example performs the following operations:\n* 1. Creates an Auto Scaling group using an AutoScalingWaiter.\n* 2. Gets a specific Auto Scaling group and returns an instance Id value.\n* 3. Describes Auto Scaling with the Id value.\n* 4. Enables metrics collection.\n* 5. Update an Auto Scaling group.\n* 6. Describes Account details.\n* 7. Describe account details\"\n* 8. Updates an Auto Scaling group to use an additional instance.\n* 9. Gets the specific Auto Scaling group and gets the number of instances.\n* 10. List the scaling activities that have occurred for the group.\n* 11. Terminates an instance in the Auto Scaling group.\n* 12. Stops the metrics collection.\n* 13. Deletes the Auto Scaling group.\n*/\npublic class AutoScalingScenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws InterruptedException {\nBasics 549\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ngroupName - The name of the Auto Scaling group.\nlaunchTemplateName - The name of the launch template.\\s\nvpcZoneId - A subnet Id for a virtual private cloud (VPC) where\ninstances in the Auto Scaling group can be created.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString groupName = args[0];\nString launchTemplateName = args[1];\nString vpcZoneId = args[2];\nAutoScalingClient autoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon EC2 Auto Scaling example\nscenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"1. Create an Auto Scaling group named \" + groupName);\ncreateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName,\nvpcZoneId);\nSystem.out.println(\n\"Wait 1 min for the resources, including the instance. Otherwise, an\nempty instance Id is returned\");\nThread.sleep(60000);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Get Auto Scale group Id value\");\nString instanceId = getSpecificAutoScalingGroups(autoScalingClient,\ngroupName);\nif (instanceId.compareTo(\"\") == 0) {\nBasics 550\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Error - no instance Id value\");\nSystem.exit(1);\n} else {\nSystem.out.println(\"The instance Id value is \" + instanceId);\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"3. Describe Auto Scaling with the Id value \" +\ninstanceId);\ndescribeAutoScalingInstance(autoScalingClient, instanceId);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. Enable metrics collection \" + instanceId);\nenableMetricsCollection(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"5. Update an Auto Scaling group to update max size to\n3\");\nupdateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Describe Auto Scaling groups\");\ndescribeAutoScalingGroups(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Describe account details\");\ndescribeAccountLimits(autoScalingClient);\nSystem.out.println(\n\"Wait 1 min for the resources, including the instance. Otherwise, an\nempty instance Id is returned\");\nThread.sleep(60000);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Set desired capacity to 2\");\nsetDesiredCapacity(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nBasics 551\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"9.", "mimetype": "text/plain", "start_char_idx": 869016, "end_char_idx": 873137, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8fcab725-6697-4f99-b9fb-ef1afe18f980": {"__data__": {"id_": "8fcab725-6697-4f99-b9fb-ef1afe18f980", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dbca4706-5dec-43de-970f-ab310f50cafd", "node_type": "1", "metadata": {}, "hash": "153ca19911c32e47c6343d95eddfd7688b90e61bc70ac476731ba174aab4f505", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "05b21a26-f329-4d25-a93f-f8d63816e622", "node_type": "1", "metadata": {}, "hash": "407504975b7b1e6df4232463fff755eb9aba69f6be467537b77a6cf955269d73", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Describe Auto Scaling groups\");\ndescribeAutoScalingGroups(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Describe account details\");\ndescribeAccountLimits(autoScalingClient);\nSystem.out.println(\n\"Wait 1 min for the resources, including the instance. Otherwise, an\nempty instance Id is returned\");\nThread.sleep(60000);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Set desired capacity to 2\");\nsetDesiredCapacity(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nBasics 551\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"9. Get the two instance Id values and state\");\ngetSpecificAutoScalingGroups(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"10. List the scaling activities that have occurred for\nthe group\");\ndescribeScalingActivities(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"11. Terminate an instance in the Auto Scaling group\");\nterminateInstanceInAutoScalingGroup(autoScalingClient, instanceId);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"12. Stop the metrics collection\");\ndisableMetricsCollection(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"13. Delete the Auto Scaling group\");\ndeleteAutoScalingGroup(autoScalingClient, groupName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The Scenario has successfully completed.\");\nSystem.out.println(DASHES);\nautoScalingClient.close();\n}\npublic static void describeScalingActivities(AutoScalingClient\nautoScalingClient, String groupName) {\ntry {\nDescribeScalingActivitiesRequest scalingActivitiesRequest =\nDescribeScalingActivitiesRequest.builder()\n.autoScalingGroupName(groupName)\n.maxRecords(10)\n.build();\nDescribeScalingActivitiesResponse response = autoScalingClient\n.describeScalingActivities(scalingActivitiesRequest);\nList activities = response.activities();\nBasics 552\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfor (Activity activity : activities) {\nSystem.out.println(\"The activity Id is \" + activity.activityId());\nSystem.out.println(\"The activity details are \" +\nactivity.details());\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void setDesiredCapacity(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nSetDesiredCapacityRequest capacityRequest =\nSetDesiredCapacityRequest.builder()\n.autoScalingGroupName(groupName)\n.desiredCapacity(2)\n.build();\nautoScalingClient.setDesiredCapacity(capacityRequest);\nSystem.out.println(\"You have set the DesiredCapacity to 2\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void createAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName,\nString launchTemplateName,\nString vpcZoneId) {\ntry {\nAutoScalingWaiter waiter = autoScalingClient.waiter();\nLaunchTemplateSpecification templateSpecification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(launchTemplateName)\n.build();\nCreateAutoScalingGroupRequest request =\nCreateAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\nBasics 553\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.availabilityZones(\"us-east-1a\")\n.launchTemplate(templateSpecification)\n.maxSize(1)\n.minSize(1)\n.vpcZoneIdentifier(vpcZoneId)\n.build();\nautoScalingClient.createAutoScalingGroup(request);\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nWaiterResponse waiterResponse =\nwaiter\n.waitUntilGroupExists(groupsRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Auto Scaling Group created\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void describeAutoScalingInstance(AutoScalingClient\nautoScalingClient, String id) {\ntry {\nDescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest\n= DescribeAutoScalingInstancesRequest\n.builder()\n.instanceIds(id)\n.build();", "mimetype": "text/plain", "start_char_idx": 872456, "end_char_idx": 876851, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "05b21a26-f329-4d25-a93f-f8d63816e622": {"__data__": {"id_": "05b21a26-f329-4d25-a93f-f8d63816e622", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8fcab725-6697-4f99-b9fb-ef1afe18f980", "node_type": "1", "metadata": {}, "hash": "627f517bca42273f39f95a89ac32cb788c9c06819abecd062304d3f76c9ef3f2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d7383294-0fd9-442a-bc8e-d61b2e66bed3", "node_type": "1", "metadata": {}, "hash": "a76f249b240fd3d8ed2f549cb95688909ada3fb141b5d4b6338cec43520fe758", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "minSize(1)\n.vpcZoneIdentifier(vpcZoneId)\n.build();\nautoScalingClient.createAutoScalingGroup(request);\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nWaiterResponse waiterResponse =\nwaiter\n.waitUntilGroupExists(groupsRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Auto Scaling Group created\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void describeAutoScalingInstance(AutoScalingClient\nautoScalingClient, String id) {\ntry {\nDescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest\n= DescribeAutoScalingInstancesRequest\n.builder()\n.instanceIds(id)\n.build();\nDescribeAutoScalingInstancesResponse response = autoScalingClient\n.describeAutoScalingInstances(describeAutoScalingInstancesRequest);\nList instances =\nresponse.autoScalingInstances();\nfor (AutoScalingInstanceDetails instance : instances) {\nSystem.out.println(\"The instance lifecycle state is: \" +\ninstance.lifecycleState());\n}\nBasics 554\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void describeAutoScalingGroups(AutoScalingClient\nautoScalingClient, String groupName) {\ntry {\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.maxRecords(10)\n.build();\nDescribeAutoScalingGroupsResponse response =\nautoScalingClient.describeAutoScalingGroups(groupsRequest);\nList groups = response.autoScalingGroups();\nfor (AutoScalingGroup group : groups) {\nSystem.out.println(\"*** The service to use for the health checks: \"\n+ group.healthCheckType());\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static String getSpecificAutoScalingGroups(AutoScalingClient\nautoScalingClient, String groupName) {\ntry {\nString instanceId = \"\";\nDescribeAutoScalingGroupsRequest scalingGroupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response = autoScalingClient\n.describeAutoScalingGroups(scalingGroupsRequest);\nList groups = response.autoScalingGroups();\nfor (AutoScalingGroup group : groups) {\nSystem.out.println(\"The group name is \" +\ngroup.autoScalingGroupName());\nBasics 555\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"The group ARN is \" +\ngroup.autoScalingGroupARN());\nList instances = group.instances();\nfor (Instance instance : instances) {\ninstanceId = instance.instanceId();\nSystem.out.println(\"The instance id is \" + instanceId);\nSystem.out.println(\"The lifecycle state is \" +\ninstance.lifecycleState());\n}\n}\nreturn instanceId;\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\npublic static void enableMetricsCollection(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nEnableMetricsCollectionRequest collectionRequest =\nEnableMetricsCollectionRequest.builder()\n.autoScalingGroupName(groupName)\n.metrics(\"GroupMaxSize\")\n.granularity(\"1Minute\")\n.build();\nautoScalingClient.enableMetricsCollection(collectionRequest);\nSystem.out.println(\"The enable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void disableMetricsCollection(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nBasics 556\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDisableMetricsCollectionRequest disableMetricsCollectionRequest =\nDisableMetricsCollectionRequest.builder()\n.autoScalingGroupName(groupName)\n.metrics(\"GroupMaxSize\")\n.build();\nautoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);\nSystem.out.println(\"The disable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);", "mimetype": "text/plain", "start_char_idx": 876022, "end_char_idx": 880307, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d7383294-0fd9-442a-bc8e-d61b2e66bed3": {"__data__": {"id_": "d7383294-0fd9-442a-bc8e-d61b2e66bed3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "05b21a26-f329-4d25-a93f-f8d63816e622", "node_type": "1", "metadata": {}, "hash": "407504975b7b1e6df4232463fff755eb9aba69f6be467537b77a6cf955269d73", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1dc62790-7f9b-4fb6-9c76-33e6f88339ff", "node_type": "1", "metadata": {}, "hash": "d53f0bdda9bc430c9a8dcf74d208945fcd20b502364fe120ff817359a33183eb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "build();\nautoScalingClient.enableMetricsCollection(collectionRequest);\nSystem.out.println(\"The enable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void disableMetricsCollection(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nBasics 556\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDisableMetricsCollectionRequest disableMetricsCollectionRequest =\nDisableMetricsCollectionRequest.builder()\n.autoScalingGroupName(groupName)\n.metrics(\"GroupMaxSize\")\n.build();\nautoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);\nSystem.out.println(\"The disable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void describeAccountLimits(AutoScalingClient autoScalingClient) {\ntry {\nDescribeAccountLimitsResponse response =\nautoScalingClient.describeAccountLimits();\nSystem.out.println(\"The max number of auto scaling groups is \" +\nresponse.maxNumberOfAutoScalingGroups());\nSystem.out.println(\"The current number of auto scaling groups is \" +\nresponse.numberOfAutoScalingGroups());\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void updateAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName,\nString launchTemplateName) {\ntry {\nAutoScalingWaiter waiter = autoScalingClient.waiter();\nLaunchTemplateSpecification templateSpecification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(launchTemplateName)\n.build();\nUpdateAutoScalingGroupRequest groupRequest =\nUpdateAutoScalingGroupRequest.builder()\nBasics 557\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.maxSize(3)\n.autoScalingGroupName(groupName)\n.launchTemplate(templateSpecification)\n.build();\nautoScalingClient.updateAutoScalingGroup(groupRequest);\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nWaiterResponse waiterResponse =\nwaiter\n.waitUntilGroupInService(groupsRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"You successfully updated the auto scaling group \" +\ngroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void terminateInstanceInAutoScalingGroup(AutoScalingClient\nautoScalingClient, String instanceId) {\ntry {\nTerminateInstanceInAutoScalingGroupRequest request =\nTerminateInstanceInAutoScalingGroupRequest.builder()\n.instanceId(instanceId)\n.shouldDecrementDesiredCapacity(false)\n.build();\nautoScalingClient.terminateInstanceInAutoScalingGroup(request);\nSystem.out.println(\"You have terminated instance \" + instanceId);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName) {\nBasics 558\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\nautoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(\"You successfully deleted \" + groupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 CreateAutoScalingGroup\n\u2022 DeleteAutoScalingGroup\n\u2022 DescribeAutoScalingGroups\n\u2022 DescribeAutoScalingInstances\n\u2022 DescribeScalingActivities\n\u2022 DisableMetricsCollection\n\u2022 EnableMetricsCollection\n\u2022 SetDesiredCapacity\n\u2022 TerminateInstanceInAutoScalingGroup\n\u2022 UpdateAutoScalingGroup\nActions\nCreateAutoScalingGroup\nThe following code example shows how to use CreateAutoScalingGroup.\nActions 559\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 879438, "end_char_idx": 883728, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1dc62790-7f9b-4fb6-9c76-33e6f88339ff": {"__data__": {"id_": "1dc62790-7f9b-4fb6-9c76-33e6f88339ff", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d7383294-0fd9-442a-bc8e-d61b2e66bed3", "node_type": "1", "metadata": {}, "hash": "a76f249b240fd3d8ed2f549cb95688909ada3fb141b5d4b6338cec43520fe758", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6f15b4b0-804a-4284-8241-de0362fc1d22", "node_type": "1", "metadata": {}, "hash": "103ef6b702953105998b8ec6612ac1638fad91667ecc5d36ee3312d66195abf8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "println(\"You successfully deleted \" + groupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 CreateAutoScalingGroup\n\u2022 DeleteAutoScalingGroup\n\u2022 DescribeAutoScalingGroups\n\u2022 DescribeAutoScalingInstances\n\u2022 DescribeScalingActivities\n\u2022 DisableMetricsCollection\n\u2022 EnableMetricsCollection\n\u2022 SetDesiredCapacity\n\u2022 TerminateInstanceInAutoScalingGroup\n\u2022 UpdateAutoScalingGroup\nActions\nCreateAutoScalingGroup\nThe following code example shows how to use CreateAutoScalingGroup.\nActions 559\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.autoscaling.AutoScalingClient;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingException;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification;\nimport software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter;\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateAutoScalingGroup {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \n\nWhere:\ngroupName - The name of the Auto Scaling group.\nlaunchTemplateName - The name of the launch template.\\s\nActions 560\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvpcZoneId - A subnet Id for a virtual private cloud (VPC) where\ninstances in the Auto Scaling group can be created.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString groupName = args[0];\nString launchTemplateName = args[1];\nString vpcZoneId = args[2];\nAutoScalingClient autoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\ncreateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName,\nvpcZoneId);\nautoScalingClient.close();\n}\npublic static void createAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName,\nString launchTemplateName,\nString vpcZoneId) {\ntry {\nAutoScalingWaiter waiter = autoScalingClient.waiter();\nLaunchTemplateSpecification templateSpecification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(launchTemplateName)\n.build();\nCreateAutoScalingGroupRequest request =\nCreateAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.availabilityZones(\"us-east-1a\")\n.launchTemplate(templateSpecification)\n.maxSize(1)\n.minSize(1)\n.vpcZoneIdentifier(vpcZoneId)\n.build();\nautoScalingClient.createAutoScalingGroup(request);\nActions 561\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nWaiterResponse waiterResponse =\nwaiter\n.waitUntilGroupExists(groupsRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Auto Scaling Group created\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see CreateAutoScalingGroup in AWS SDK for Java 2.x API Reference.\nDeleteAutoScalingGroup\nThe following code example shows how to use DeleteAutoScalingGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.autoscaling.AutoScalingClient;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingException;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest;\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 882904, "end_char_idx": 887457, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6f15b4b0-804a-4284-8241-de0362fc1d22": {"__data__": {"id_": "6f15b4b0-804a-4284-8241-de0362fc1d22", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1dc62790-7f9b-4fb6-9c76-33e6f88339ff", "node_type": "1", "metadata": {}, "hash": "d53f0bdda9bc430c9a8dcf74d208945fcd20b502364fe120ff817359a33183eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4b0017f3-bb15-4d76-9d59-e15abb40c668", "node_type": "1", "metadata": {}, "hash": "d89ec7721b9765c74714d6b8b903f211b14a5bd138cbdd3b1530a20775e6a86e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteAutoScalingGroup\nThe following code example shows how to use DeleteAutoScalingGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.autoscaling.AutoScalingClient;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingException;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest;\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.\nActions 562\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteAutoScalingGroup {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ngroupName - The name of the Auto Scaling group.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString groupName = args[0];\nAutoScalingClient autoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\ndeleteAutoScalingGroup(autoScalingClient, groupName);\nautoScalingClient.close();\n}\npublic static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\nautoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(\"You successfully deleted \" + groupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nActions 563\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DeleteAutoScalingGroup in AWS SDK for Java 2.x API Reference.\nDescribeAutoScalingGroups\nThe following code example shows how to use DescribeAutoScalingGroups.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.autoscaling.AutoScalingClient;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingException;\nimport software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;\nimport\nsoftware.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;\nimport software.amazon.awssdk.services.autoscaling.model.Instance;\nimport java.util.List;\n/**\n* Before running this SDK for Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeAutoScalingInstances {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nActions 564\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUsage:\n\nWhere:\ngroupName - The name of the Auto Scaling group.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString groupName = args[0];\nAutoScalingClient autoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\nString instanceId = getAutoScaling(autoScalingClient, groupName);\nSystem.out.println(instanceId);\nautoScalingClient.close();\n}\npublic static String getAutoScaling(AutoScalingClient autoScalingClient, String\ngroupName) {\ntry {\nString instanceId = \"\";\nDescribeAutoScalingGroupsRequest scalingGroupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response = autoScalingClient\n.describeAutoScalingGroups(scalingGroupsRequest);\nList groups = response.autoScalingGroups();\nfor (AutoScalingGroup group : groups) {\nSystem.out.println(\"The group name is \" +\ngroup.autoScalingGroupName());\nSystem.out.println(\"The group ARN is \" +\ngroup.autoScalingGroupARN());\nList instances = group.instances();\nfor (Instance instance : instances) {\ninstanceId = instance.instanceId();\nActions 565\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\nreturn instanceId;\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see DescribeAutoScalingGroups in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 886818, "end_char_idx": 891478, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4b0017f3-bb15-4d76-9d59-e15abb40c668": {"__data__": {"id_": "4b0017f3-bb15-4d76-9d59-e15abb40c668", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6f15b4b0-804a-4284-8241-de0362fc1d22", "node_type": "1", "metadata": {}, "hash": "103ef6b702953105998b8ec6612ac1638fad91667ecc5d36ee3312d66195abf8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "21081f43-7894-4288-a343-cfe41d62aec0", "node_type": "1", "metadata": {}, "hash": "7d694572ed3f35a6b656d34ca5416737bac1c0a04f9f2e58549d6e4c9a8f4a3c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeAutoScalingInstances\nThe following code example shows how to use DescribeAutoScalingInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeAutoScalingInstance(AutoScalingClient\nautoScalingClient, String id) {\ntry {\nDescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest\n= DescribeAutoScalingInstancesRequest\n.builder()\n.instanceIds(id)\n.build();\nDescribeAutoScalingInstancesResponse response = autoScalingClient\n.describeAutoScalingInstances(describeAutoScalingInstancesRequest);\nList instances =\nresponse.autoScalingInstances();\nfor (AutoScalingInstanceDetails instance : instances) {\nActions 566\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"The instance lifecycle state is: \" +\ninstance.lifecycleState());\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeAutoScalingInstances in AWS SDK for Java 2.x API Reference.\nDescribeScalingActivities\nThe following code example shows how to use DescribeScalingActivities.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void describeScalingActivities(AutoScalingClient\nautoScalingClient, String groupName) {\ntry {\nDescribeScalingActivitiesRequest scalingActivitiesRequest =\nDescribeScalingActivitiesRequest.builder()\n.autoScalingGroupName(groupName)\n.maxRecords(10)\n.build();\nDescribeScalingActivitiesResponse response = autoScalingClient\n.describeScalingActivities(scalingActivitiesRequest);\nList activities = response.activities();\nfor (Activity activity : activities) {\nSystem.out.println(\"The activity Id is \" + activity.activityId());\nSystem.out.println(\"The activity details are \" +\nactivity.details());\nActions 567\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see DescribeScalingActivities in AWS SDK for Java 2.x API Reference.\nDisableMetricsCollection\nThe following code example shows how to use DisableMetricsCollection.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void disableMetricsCollection(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nDisableMetricsCollectionRequest disableMetricsCollectionRequest =\nDisableMetricsCollectionRequest.builder()\n.autoScalingGroupName(groupName)\n.metrics(\"GroupMaxSize\")\n.build();\nautoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);\nSystem.out.println(\"The disable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nActions 568\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see DisableMetricsCollection in AWS SDK for Java 2.x API Reference.\nEnableMetricsCollection\nThe following code example shows how to use EnableMetricsCollection.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void enableMetricsCollection(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nEnableMetricsCollectionRequest collectionRequest =\nEnableMetricsCollectionRequest.builder()\n.autoScalingGroupName(groupName)\n.metrics(\"GroupMaxSize\")\n.granularity(\"1Minute\")\n.build();\nautoScalingClient.enableMetricsCollection(collectionRequest);\nSystem.out.println(\"The enable metrics collection operation was\nsuccessful\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see EnableMetricsCollection in AWS SDK for Java 2.x API Reference.\nActions 569\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSetDesiredCapacity\nThe following code example shows how to use SetDesiredCapacity.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void setDesiredCapacity(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nSetDesiredCapacityRequest capacityRequest =\nSetDesiredCapacityRequest.builder()\n.autoScalingGroupName(groupName)\n.desiredCapacity(2)\n.build();\nautoScalingClient.setDesiredCapacity(capacityRequest);\nSystem.out.println(\"You have set the DesiredCapacity to 2\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see SetDesiredCapacity in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 891479, "end_char_idx": 896353, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "21081f43-7894-4288-a343-cfe41d62aec0": {"__data__": {"id_": "21081f43-7894-4288-a343-cfe41d62aec0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4b0017f3-bb15-4d76-9d59-e15abb40c668", "node_type": "1", "metadata": {}, "hash": "d89ec7721b9765c74714d6b8b903f211b14a5bd138cbdd3b1530a20775e6a86e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7d2fb3fd-9b5e-48dc-a246-4d4f4b84ec24", "node_type": "1", "metadata": {}, "hash": "ce18af00519cb71e4271fae342d46ea5b1424a5cd9abb7520036716a4289e38e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 569\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSetDesiredCapacity\nThe following code example shows how to use SetDesiredCapacity.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void setDesiredCapacity(AutoScalingClient autoScalingClient,\nString groupName) {\ntry {\nSetDesiredCapacityRequest capacityRequest =\nSetDesiredCapacityRequest.builder()\n.autoScalingGroupName(groupName)\n.desiredCapacity(2)\n.build();\nautoScalingClient.setDesiredCapacity(capacityRequest);\nSystem.out.println(\"You have set the DesiredCapacity to 2\");\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see SetDesiredCapacity in AWS SDK for Java 2.x API Reference.\nTerminateInstanceInAutoScalingGroup\nThe following code example shows how to use TerminateInstanceInAutoScalingGroup.\nActions 570\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void terminateInstanceInAutoScalingGroup(AutoScalingClient\nautoScalingClient, String instanceId) {\ntry {\nTerminateInstanceInAutoScalingGroupRequest request =\nTerminateInstanceInAutoScalingGroupRequest.builder()\n.instanceId(instanceId)\n.shouldDecrementDesiredCapacity(false)\n.build();\nautoScalingClient.terminateInstanceInAutoScalingGroup(request);\nSystem.out.println(\"You have terminated instance \" + instanceId);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see TerminateInstanceInAutoScalingGroup in AWS SDK for Java 2.x API\nReference.\nUpdateAutoScalingGroup\nThe following code example shows how to use UpdateAutoScalingGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 571\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void updateAutoScalingGroup(AutoScalingClient autoScalingClient,\nString groupName,\nString launchTemplateName) {\ntry {\nAutoScalingWaiter waiter = autoScalingClient.waiter();\nLaunchTemplateSpecification templateSpecification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(launchTemplateName)\n.build();\nUpdateAutoScalingGroupRequest groupRequest =\nUpdateAutoScalingGroupRequest.builder()\n.maxSize(3)\n.autoScalingGroupName(groupName)\n.launchTemplate(templateSpecification)\n.build();\nautoScalingClient.updateAutoScalingGroup(groupRequest);\nDescribeAutoScalingGroupsRequest groupsRequest =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nWaiterResponse waiterResponse =\nwaiter\n.waitUntilGroupInService(groupsRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"You successfully updated the auto scaling group \" +\ngroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see UpdateAutoScalingGroup in AWS SDK for Java 2.x API Reference.\nActions 572\nAWS SDK for Java 2.x Developer Guide for version 2.x\nScenarios\nBuild and manage a resilient service\nThe following code example shows how to create a load-balanced web service that returns book,\nmovie, and song recommendations. The example shows how the service responds to failures, and\nhow to restructure the service for more resilience when failures occur.\n\u2022 Use an Amazon EC2 Auto Scaling group to create Amazon Elastic Compute Cloud (Amazon EC2)\ninstances based on a launch template and to keep the number of instances in a specified range.\n\u2022 Handle and distribute HTTP requests with Elastic Load Balancing.\n\u2022 Monitor the health of instances in an Auto Scaling group and forward requests only to healthy\ninstances.\n\u2022 Run a Python web server on each EC2 instance to handle HTTP requests. The web server\nresponds with recommendations and health checks.\n\u2022 Simulate a recommendation service with an Amazon DynamoDB table.\n\u2022 Control web server response to requests and health checks by updating AWS Systems Manager\nparameters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.", "mimetype": "text/plain", "start_char_idx": 895513, "end_char_idx": 900130, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7d2fb3fd-9b5e-48dc-a246-4d4f4b84ec24": {"__data__": {"id_": "7d2fb3fd-9b5e-48dc-a246-4d4f4b84ec24", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "21081f43-7894-4288-a343-cfe41d62aec0", "node_type": "1", "metadata": {}, "hash": "7d694572ed3f35a6b656d34ca5416737bac1c0a04f9f2e58549d6e4c9a8f4a3c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "60e739c8-97b1-43ce-896f-e983b52143bc", "node_type": "1", "metadata": {}, "hash": "c9a82acd4661c2cc1f7ff8b02d1c573bd25cd03f1b442f306806c327f10169a9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 Handle and distribute HTTP requests with Elastic Load Balancing.\n\u2022 Monitor the health of instances in an Auto Scaling group and forward requests only to healthy\ninstances.\n\u2022 Run a Python web server on each EC2 instance to handle HTTP requests. The web server\nresponds with recommendations and health checks.\n\u2022 Simulate a recommendation service with an Amazon DynamoDB table.\n\u2022 Control web server response to requests and health checks by updating AWS Systems Manager\nparameters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.\npublic static final String tableName = \"doc-example-recommendation-service\";\npublic static final String startScript = \"C:\\\\AWS\\\\resworkflow\\\n\\server_startup_script.sh\"; // Modify file location.\npublic static final String policyFile = \"C:\\\\AWS\\\\resworkflow\\\n\\instance_policy.json\"; // Modify file location.\nScenarios 573\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static final String ssmJSON = \"C:\\\\AWS\\\\resworkflow\\\n\\ssm_only_policy.json\"; // Modify file location.\npublic static final String failureResponse = \"doc-example-resilient-\narchitecture-failure-response\";\npublic static final String healthCheck = \"doc-example-resilient-architecture-\nhealth-check\";\npublic static final String templateName = \"doc-example-resilience-template\";\npublic static final String roleName = \"doc-example-resilience-role\";\npublic static final String policyName = \"doc-example-resilience-pol\";\npublic static final String profileName = \"doc-example-resilience-prof\";\npublic static final String badCredsProfileName = \"doc-example-resilience-prof-\nbc\";\npublic static final String targetGroupName = \"doc-example-resilience-tg\";\npublic static final String autoScalingGroupName = \"doc-example-resilience-\ngroup\";\npublic static final String lbName = \"doc-example-resilience-lb\";\npublic static final String protocol = \"HTTP\";\npublic static final int port = 80;\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws IOException, InterruptedException\n{\nScanner in = new Scanner(System.in);\nDatabase database = new Database();\nAutoScaler autoScaler = new AutoScaler();\nLoadBalancer loadBalancer = new LoadBalancer();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the demonstration of How to Build and Manage\na Resilient Service!\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"A - SETUP THE RESOURCES\");\nSystem.out.println(\"Press Enter when you're ready to start deploying\nresources.\");\nin.nextLine();\ndeploy(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"B - DEMO THE RESILIENCE FUNCTIONALITY\");\nScenarios 574\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\ndemo(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"C - DELETE THE RESOURCES\");\nSystem.out.println(\"\"\"\nThis concludes the demo of how to build and manage a resilient\nservice.\nTo keep things tidy and to avoid unwanted charges on your account,\nwe can clean up all AWS resources\nthat were created for this demo.\n\"\"\");\nSystem.out.println(\"\\n Do you want to delete the resources (y/n)? \");\nString userInput = in.nextLine().trim().toLowerCase(); // Capture user input\nif (userInput.equals(\"y\")) {\n// Delete resources here\ndeleteResources(loadBalancer, autoScaler, database);\nSystem.out.println(\"Resources deleted.\");\n} else {\nSystem.out.println(\"\"\"\nOkay, we'll leave the resources intact.\nDon't forget to delete them when you're done with them or you\nmight incur unexpected charges.\n\"\"\");\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The example has completed. \");\nSystem.out.println(\"\\n Thanks for watching!\");\nSystem.out.println(DASHES);\n}\n// Deletes the AWS resources used in this example.", "mimetype": "text/plain", "start_char_idx": 899329, "end_char_idx": 903475, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "60e739c8-97b1-43ce-896f-e983b52143bc": {"__data__": {"id_": "60e739c8-97b1-43ce-896f-e983b52143bc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7d2fb3fd-9b5e-48dc-a246-4d4f4b84ec24", "node_type": "1", "metadata": {}, "hash": "ce18af00519cb71e4271fae342d46ea5b1424a5cd9abb7520036716a4289e38e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "383bc2ed-4c36-41ed-9a79-9306d3307353", "node_type": "1", "metadata": {}, "hash": "e03a5742470ca63f39103efe5959141c307f18e4a2c3542efb790eb711b4adb5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "To keep things tidy and to avoid unwanted charges on your account,\nwe can clean up all AWS resources\nthat were created for this demo.\n\"\"\");\nSystem.out.println(\"\\n Do you want to delete the resources (y/n)? \");\nString userInput = in.nextLine().trim().toLowerCase(); // Capture user input\nif (userInput.equals(\"y\")) {\n// Delete resources here\ndeleteResources(loadBalancer, autoScaler, database);\nSystem.out.println(\"Resources deleted.\");\n} else {\nSystem.out.println(\"\"\"\nOkay, we'll leave the resources intact.\nDon't forget to delete them when you're done with them or you\nmight incur unexpected charges.\n\"\"\");\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The example has completed. \");\nSystem.out.println(\"\\n Thanks for watching!\");\nSystem.out.println(DASHES);\n}\n// Deletes the AWS resources used in this example.\nprivate static void deleteResources(LoadBalancer loadBalancer, AutoScaler\nautoScaler, Database database)\nthrows IOException, InterruptedException {\nloadBalancer.deleteLoadBalancer(lbName);\nSystem.out.println(\"*** Wait 30 secs for resource to be deleted\");\nTimeUnit.SECONDS.sleep(30);\nScenarios 575\nAWS SDK for Java 2.x Developer Guide for version 2.x\nloadBalancer.deleteTargetGroup(targetGroupName);\nautoScaler.deleteAutoScaleGroup(autoScalingGroupName);\nautoScaler.deleteRolesPolicies(policyName, roleName, profileName);\nautoScaler.deleteTemplate(templateName);\ndatabase.deleteTable(tableName);\n}\nprivate static void deploy(LoadBalancer loadBalancer) throws\nInterruptedException, IOException {\nScanner in = new Scanner(System.in);\nSystem.out.println(\n\"\"\"\nFor this demo, we'll use the AWS SDK for Java (v2) to create\nseveral AWS resources\nto set up a load-balanced web service endpoint and explore\nsome ways to make it resilient\nagainst various kinds of failures.\nSome of the resources create by this demo are:\n\\t* A DynamoDB table that the web service depends on to\nprovide book, movie, and song recommendations.\n\\t* An EC2 launch template that defines EC2 instances that\neach contain a Python web server.\n\\t* An EC2 Auto Scaling group that manages EC2 instances\nacross several Availability Zones.\n\\t* An Elastic Load Balancing (ELB) load balancer that\ntargets the Auto Scaling group to distribute requests.\n\"\"\");\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating and populating a DynamoDB table named \" +\ntableName);\nDatabase database = new Database();\ndatabase.createTable(tableName, fileName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an EC2 launch template that runs '{startup_script}' when an\ninstance starts.\nScenarios 576\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThis script starts a Python web server defined in the `server.py`\nscript. The web server\nlistens to HTTP requests on port 80 and responds to requests to '/'\nand to '/healthcheck'.\nFor demo purposes, this server is run as the root user. In\nproduction, the best practice is to\nrun a web server, such as Apache, with least-privileged credentials.\nThe template also defines an IAM policy that each instance uses to\nassume a role that grants\npermissions to access the DynamoDB recommendation table and Systems\nManager parameters\nthat control the flow of the demo.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\ntemplateCreator.createTemplate(policyFile, policyName, profileName,\nstartScript, templateName, roleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\n\"Creating an EC2 Auto Scaling group that maintains three EC2\ninstances, each in a different Availability Zone.\");\nSystem.out.println(\"*** Wait 30 secs for the VPC to be created\");\nTimeUnit.SECONDS.sleep(30);\nAutoScaler autoScaler = new AutoScaler();\nString[] zones = autoScaler.createGroup(3, templateName,\nautoScalingGroupName);\nSystem.out.println(\"\"\"\nAt this point, you have EC2 instances created. Once each instance\nstarts, it listens for\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nScenarios 577\nAWS SDK for Java 2.x Developer Guide for version 2.x\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances.", "mimetype": "text/plain", "start_char_idx": 902631, "end_char_idx": 907306, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "383bc2ed-4c36-41ed-9a79-9306d3307353": {"__data__": {"id_": "383bc2ed-4c36-41ed-9a79-9306d3307353", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "60e739c8-97b1-43ce-896f-e983b52143bc", "node_type": "1", "metadata": {}, "hash": "c9a82acd4661c2cc1f7ff8b02d1c573bd25cd03f1b442f306806c327f10169a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca3531c8-1fca-4824-8970-4bcf0ae5f77e", "node_type": "1", "metadata": {}, "hash": "7d0cc2f9448747f02259969b7fdd9b2d6716b31d7307508c29ef73ca5a85d7e3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Once each instance\nstarts, it listens for\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nScenarios 577\nAWS SDK for Java 2.x Developer Guide for version 2.x\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances. The load\nbalancer provides a\nsingle endpoint where clients connect and dispatches requests to\ninstances in the group.\n\"\"\");\nString vpcId = autoScaler.getDefaultVPC();\nList subnets = autoScaler.getSubnets(vpcId, zones);\nSystem.out.println(\"You have retrieved a list with \" + subnets.size() + \"\nsubnets\");\nString targetGroupArn = loadBalancer.createTargetGroup(protocol, port,\nvpcId, targetGroupName);\nString elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn,\nlbName, port, protocol);\nautoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName,\ntargetGroupArn);\nSystem.out.println(\"Verifying access to the load balancer endpoint...\");\nboolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);\nif (!wasSuccessul) {\nSystem.out.println(\"Couldn't connect to the load balancer, verifying\nthat the port is open...\");\nCloseableHttpClient httpClient = HttpClients.createDefault();\n// Create an HTTP GET request to \"http://checkip.amazonaws.com\"\nHttpGet httpGet = new HttpGet(\"http://checkip.amazonaws.com\");\ntry {\n// Execute the request and get the response\nHttpResponse response = httpClient.execute(httpGet);\n// Read the response content.\nString ipAddress =\nIOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();\n// Print the public IP address.\nSystem.out.println(\"Public IP Address: \" + ipAddress);\nGroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port,\nipAddress);\nScenarios 578\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (!groupInfo.isPortOpen()) {\nSystem.out.println(\"\"\"\nFor this example to work, the default security group for\nyour default VPC must\nallow access from this computer. You can either add it\nautomatically from this\nexample or add it yourself using the AWS Management\nConsole.\n\"\"\");\nSystem.out.println(\n\"Do you want to add a rule to security group \" +\ngroupInfo.getGroupName() + \" to allow\");\nSystem.out.println(\"inbound traffic on port \" + port + \" from\nyour computer's IP address (y/n) \");\nString ans = in.nextLine();\nif (\"y\".equalsIgnoreCase(ans)) {\nautoScaler.openInboundPort(groupInfo.getGroupName(),\nString.valueOf(port), ipAddress);\nSystem.out.println(\"Security group rule added.\");\n} else {\nSystem.out.println(\"No security group rule added.\");\n}\n}\n} catch (AutoScalingException e) {\ne.printStackTrace();\n}\n} else if (wasSuccessul) {\nSystem.out.println(\"Your load balancer is ready. You can access it by\nbrowsing to:\");\nSystem.out.println(\"\\t http://\" + elbDnsName);\n} else {\nSystem.out.println(\"Couldn't get a successful response from the load\nbalancer endpoint. Troubleshoot by\");\nSystem.out.println(\"manually verifying that your VPC and security group\nare configured correctly and that\");\nSystem.out.println(\"you can successfully make a GET request to the load\nbalancer.\");\n}\nSystem.out.println(\"Press Enter when you're ready to continue with the\ndemo.\");\nin.nextLine();\nScenarios 579\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n// A method that controls the demo part of the Java program.\npublic static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.", "mimetype": "text/plain", "start_char_idx": 906626, "end_char_idx": 911195, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ca3531c8-1fca-4824-8970-4bcf0ae5f77e": {"__data__": {"id_": "ca3531c8-1fca-4824-8970-4bcf0ae5f77e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "383bc2ed-4c36-41ed-9a79-9306d3307353", "node_type": "1", "metadata": {}, "hash": "e03a5742470ca63f39103efe5959141c307f18e4a2c3542efb790eb711b4adb5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6e832700-e49b-4ae0-aaed-76ddd9e0d8d0", "node_type": "1", "metadata": {}, "hash": "59a0c8dd97d665b6fe0eff5ee0fb7b9d9b52f8680e8f5cc1e22ff8a3cbccdf42", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.\nThe table name is contained in a Systems Manager parameter\nnamed self.param_helper.table.\nTo simulate a failure of the recommendation service, let's\nset this parameter to name a non-existent table.\n\"\"\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\nSystem.out.println(\n\"\"\"\n\\nNow, sending a GET request to the load balancer endpoint\nreturns a failure code. But, the service reports as\nhealthy to the load balancer because shallow health checks\ndon't check for failure of the recommendation service.\n\"\"\");\nScenarios 580\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nInstead of failing when the recommendation service fails,\nthe web service can return a static response.\nWhile this is not a perfect solution, it presents the\ncustomer with a somewhat better experience than failure.\n\"\"\");\nparamHelper.put(paramHelper.failureResponse, \"static\");\nSystem.out.println(\"\"\"\nNow, sending a GET request to the load balancer endpoint returns a\nstatic response.\nThe service still reports as healthy because health checks are still\nshallow.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"Let's reinstate the recommendation service.\");\nparamHelper.put(paramHelper.tableName, paramHelper.dyntable);\nSystem.out.println(\"\"\"\nLet's also substitute bad credentials for one of the instances in\nthe target group so that it can't\naccess the DynamoDB recommendation table. We will get an instance id\nvalue.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\nAutoScaler autoScaler = new AutoScaler();\n// Create a new instance profile based on badCredsProfileName.\ntemplateCreator.createInstanceProfile(policyFile, policyName,\nbadCredsProfileName, roleName);\nString badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);\nSystem.out.println(\"The bad instance id values used for this demo is \" +\nbadInstanceId);\nString profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);\nSystem.out.println(\"The association Id value is \" + profileAssociationId);\nSystem.out.println(\"Replacing the profile for instance \" + badInstanceId\n+ \" with a profile that contains bad credentials\");\nScenarios 581\nAWS SDK for Java 2.x Developer Guide for version 2.x\nautoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName,\nprofileAssociationId);\nSystem.out.println(\n\"\"\"\nNow, sending a GET request to the load balancer endpoint\nreturns either a recommendation or a static response,\ndepending on which instance is selected by the load\nbalancer.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"\"\"\nLet's implement a deep health check. For this demo, a deep health\ncheck tests whether\nthe web service can access the DynamoDB table that it depends on for\nrecommendations. Note that\nthe deep health check is only for ELB routing and not for Auto\nScaling instance health.\nThis kind of deep health check is not recommended for Auto Scaling\ninstance health, because it\nrisks accidental termination of all instances in the Auto Scaling\ngroup when a dependent service fails.\n\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.\n\"\"\");\nScenarios 582\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nBecause the instances in this demo are controlled by an auto\nscaler, the simplest way to fix an unhealthy\ninstance is to terminate it and let the auto scaler start a\nnew instance to replace it.", "mimetype": "text/plain", "start_char_idx": 910326, "end_char_idx": 915164, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6e832700-e49b-4ae0-aaed-76ddd9e0d8d0": {"__data__": {"id_": "6e832700-e49b-4ae0-aaed-76ddd9e0d8d0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca3531c8-1fca-4824-8970-4bcf0ae5f77e", "node_type": "1", "metadata": {}, "hash": "7d0cc2f9448747f02259969b7fdd9b2d6716b31d7307508c29ef73ca5a85d7e3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7361a568-2312-479e-aa47-e13ad758108a", "node_type": "1", "metadata": {}, "hash": "c1c151a26bffd8cfbc148a7e5f8ba1908430235010ecccf1e6ca947dbe42d617", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.\n\"\"\");\nScenarios 582\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nBecause the instances in this demo are controlled by an auto\nscaler, the simplest way to fix an unhealthy\ninstance is to terminate it and let the auto scaler start a\nnew instance to replace it.\n\"\"\");\nautoScaler.terminateInstance(badInstanceId);\nSystem.out.println(\"\"\"\nEven while the instance is terminating and the new instance is\nstarting, sending a GET\nrequest to the web service continues to get a successful\nrecommendation response because\nthe load balancer routes requests to the healthy instances. After\nthe replacement instance\nstarts and reports as healthy, it is included in the load balancing\nrotation.\nNote that terminating and replacing an instance typically takes\nseveral minutes, during which time you\ncan see the changing health check status until the new instance is\nrunning and healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"If the recommendation service fails now, deep health checks mean\nall instances report as unhealthy.\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\ndemoChoices(loadBalancer);\nparamHelper.reset();\n}\npublic static void demoChoices(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nString[] actions = {\n\"Send a GET request to the load balancer endpoint.\",\n\"Check the health of load balancer targets.\",\n\"Go to the next part of the demo.\"\n};\nScanner scanner = new Scanner(System.in);\nScenarios 583\nAWS SDK for Java 2.x Developer Guide for version 2.x\nwhile (true) {\nSystem.out.println(\"-\".repeat(88));\nSystem.out.println(\"See the current state of the service by selecting\none of the following choices:\");\nfor (int i = 0; i < actions.length; i++) {\nSystem.out.println(i + \": \" + actions[i]);\n}\ntry {\nSystem.out.print(\"\\nWhich action would you like to take? \");\nint choice = scanner.nextInt();\nSystem.out.println(\"-\".repeat(88));\nswitch (choice) {\ncase 0 -> {\nSystem.out.println(\"Request:\\n\");\nSystem.out.println(\"GET http://\" +\nloadBalancer.getEndpoint(lbName));\nCloseableHttpClient httpClient =\nHttpClients.createDefault();\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" +\nloadBalancer.getEndpoint(lbName));\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\n// Display the JSON response\nBufferedReader reader = new BufferedReader(\nnew\nInputStreamReader(response.getEntity().getContent()));\nStringBuilder jsonResponse = new StringBuilder();\nString line;\nwhile ((line = reader.readLine()) != null) {\njsonResponse.append(line);\n}\nreader.close();\n// Print the formatted JSON response.\nSystem.out.println(\"Full Response:\\n\");\nScenarios 584\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(jsonResponse.toString());\n// Close the HTTP client.\nhttpClient.close();\n}\ncase 1 -> {\nSystem.out.println(\"\\nChecking the health of load balancer\ntargets:\\n\");\nList health =\nloadBalancer.checkTargetHealth(targetGroupName);\nfor (TargetHealthDescription target : health) {\nSystem.out.printf(\"\\tTarget %s on port %d is %s%n\",\ntarget.target().id(),\ntarget.target().port(),\ntarget.targetHealth().stateAsString());\n}\nSystem.out.println(\"\"\"\nNote that it can take a minute or two for the health\ncheck to update\nafter changes are made.\n\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nSystem.out.println(\"Invalid input. Please select again.\");\nscanner.nextLine(); // Clear the input buffer.\n}", "mimetype": "text/plain", "start_char_idx": 914252, "end_char_idx": 918713, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7361a568-2312-479e-aa47-e13ad758108a": {"__data__": {"id_": "7361a568-2312-479e-aa47-e13ad758108a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6e832700-e49b-4ae0-aaed-76ddd9e0d8d0", "node_type": "1", "metadata": {}, "hash": "59a0c8dd97d665b6fe0eff5ee0fb7b9d9b52f8680e8f5cc1e22ff8a3cbccdf42", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b2ca5baf-a3ad-493f-86f6-8177d451c5b0", "node_type": "1", "metadata": {}, "hash": "91c23fda4f0dd76959eb938cb91019e4f6e216cb050a3f01ffb349aa14cd78be", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nSystem.out.println(\"Invalid input. Please select again.\");\nscanner.nextLine(); // Clear the input buffer.\n}\n}\n}\npublic static String readFileAsString(String filePath) throws IOException {\nbyte[] bytes = Files.readAllBytes(Paths.get(filePath));\nreturn new String(bytes);\n}\n}\nScenarios 585\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that wraps Auto Scaling and Amazon EC2 actions.\npublic class AutoScaler {\nprivate static Ec2Client ec2Client;\nprivate static AutoScalingClient autoScalingClient;\nprivate static IamClient iamClient;\nprivate static SsmClient ssmClient;\nprivate IamClient getIAMClient() {\nif (iamClient == null) {\niamClient = IamClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn iamClient;\n}\nprivate SsmClient getSSMClient() {\nif (ssmClient == null) {\nssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ssmClient;\n}\nprivate Ec2Client getEc2Client() {\nif (ec2Client == null) {\nec2Client = Ec2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ec2Client;\n}\nprivate AutoScalingClient getAutoScalingClient() {\nif (autoScalingClient == null) {\nautoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\nScenarios 586\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n}\nreturn autoScalingClient;\n}\n/**\n* Terminates and instances in an EC2 Auto Scaling group. After an instance is\n* terminated, it can no longer be accessed.\n*/\npublic void terminateInstance(String instanceId) {\nTerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest =\nTerminateInstanceInAutoScalingGroupRequest\n.builder()\n.instanceId(instanceId)\n.shouldDecrementDesiredCapacity(false)\n.build();\ngetAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);\nSystem.out.format(\"Terminated instance %s.\", instanceId);\n}\n/**\n* Replaces the profile associated with a running instance. After the profile is\n* replaced, the instance is rebooted to ensure that it uses the new profile.\n* When\n* the instance is ready, Systems Manager is used to restart the Python web\n* server.\n*/\npublic void replaceInstanceProfile(String instanceId, String\nnewInstanceProfileName, String profileAssociationId)\nthrows InterruptedException {\n// Create an IAM instance profile specification.\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\niamInstanceProfile =\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\n.builder()\n.name(newInstanceProfileName) // Make sure 'newInstanceProfileName'\nis a valid IAM Instance Profile\n// name.\n.build();\n// Replace the IAM instance profile association for the EC2 instance.\nScenarios 587\nAWS SDK for Java 2.x Developer Guide for version 2.x\nReplaceIamInstanceProfileAssociationRequest replaceRequest =\nReplaceIamInstanceProfileAssociationRequest\n.builder()\n.iamInstanceProfile(iamInstanceProfile)\n.associationId(profileAssociationId) // Make sure\n'profileAssociationId' is a valid association ID.\n.build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.", "mimetype": "text/plain", "start_char_idx": 918317, "end_char_idx": 922280, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b2ca5baf-a3ad-493f-86f6-8177d451c5b0": {"__data__": {"id_": "b2ca5baf-a3ad-493f-86f6-8177d451c5b0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7361a568-2312-479e-aa47-e13ad758108a", "node_type": "1", "metadata": {}, "hash": "c1c151a26bffd8cfbc148a7e5f8ba1908430235010ecccf1e6ca947dbe42d617", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8fc7e000-a3c2-4f96-87c9-0bea15114873", "node_type": "1", "metadata": {}, "hash": "624f27f8ce4572c345721ec8ce928ae416e6763be9056f6452cb80fcad4bd790", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.\");\n}\ntries++;\ntry {\nTimeUnit.SECONDS.sleep(10);\n} catch (InterruptedException e) {\ne.printStackTrace();\n}\nDescribeInstanceInformationResponse informationResponse =\ngetSSMClient().describeInstanceInformation();\nList instanceInformationList =\ninformationResponse.instanceInformationList();\nfor (InstanceInformation info : instanceInformationList) {\nif (info.instanceId().equals(instanceId)) {\nScenarios 588\nAWS SDK for Java 2.x Developer Guide for version 2.x\ninstReady = true;\nbreak;\n}\n}\n}\nSendCommandRequest sendCommandRequest = SendCommandRequest.builder()\n.instanceIds(instanceId)\n.documentName(\"AWS-RunShellScript\")\n.parameters(Collections.singletonMap(\"commands\",\nCollections.singletonList(\"cd / && sudo python3 server.py\n80\")))\n.build();\ngetSSMClient().sendCommand(sendCommandRequest);\nSystem.out.println(\"Restarted the Python web server on instance \" +\ninstanceId + \".\");\n}\npublic void openInboundPort(String secGroupId, String port, String ipAddress) {\nAuthorizeSecurityGroupIngressRequest ingressRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(secGroupId)\n.cidrIp(ipAddress)\n.fromPort(Integer.parseInt(port))\n.build();\ngetEc2Client().authorizeSecurityGroupIngress(ingressRequest);\nSystem.out.format(\"Authorized ingress to %s on port %s from %s.\",\nsecGroupId, port, ipAddress);\n}\n/**\n* Detaches a role from an instance profile, detaches policies from the role,\n* and deletes all the resources.\n*/\npublic void deleteInstanceProfile(String roleName, String profileName) {\ntry {\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\ngetInstanceProfileRequest =\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\n.builder()\n.instanceProfileName(profileName)\n.build();\nScenarios 589\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetInstanceProfileResponse response =\ngetIAMClient().getInstanceProfile(getInstanceProfileRequest);\nString name = response.instanceProfile().instanceProfileName();\nSystem.out.println(name);\nRemoveRoleFromInstanceProfileRequest profileRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.roleName(roleName)\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(profileRequest);\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.build();\ngetIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);\nSystem.out.println(\"Deleted instance profile \" + profileName);\nDeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()\n.roleName(roleName)\n.build();\n// List attached role policies.\nListAttachedRolePoliciesResponse rolesResponse = getIAMClient()\n.listAttachedRolePolicies(role -> role.roleName(roleName));\nList attachedPolicies =\nrolesResponse.attachedPolicies();\nfor (AttachedPolicy attachedPolicy : attachedPolicies) {\nDetachRolePolicyRequest request = DetachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(attachedPolicy.policyArn())\n.build();\ngetIAMClient().detachRolePolicy(request);\nSystem.out.println(\"Detached and deleted policy \" +\nattachedPolicy.policyName());\n}\ngetIAMClient().deleteRole(deleteRoleRequest);\nSystem.out.println(\"Instance profile and role deleted.\");\nScenarios 590\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address.", "mimetype": "text/plain", "start_char_idx": 921577, "end_char_idx": 926385, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8fc7e000-a3c2-4f96-87c9-0bea15114873": {"__data__": {"id_": "8fc7e000-a3c2-4f96-87c9-0bea15114873", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b2ca5baf-a3ad-493f-86f6-8177d451c5b0", "node_type": "1", "metadata": {}, "hash": "91c23fda4f0dd76959eb938cb91019e4f6e216cb050a3f01ffb349aa14cd78be", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "86613be0-b201-40ed-a6b1-54581e753641", "node_type": "1", "metadata": {}, "hash": "6f1862a0d067de8725356940d853ba4cd0d1146e7e8a757ec93ef935505e5ff8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nScenarios 590\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address. In some situations, such as connecting from a corporate network, you\n* must instead specify a prefix list ID. You can also temporarily open the port\n* to\n* any IP address while running this example. If you do, be sure to remove\n* public\n* access when you're done.\n*\n*/\npublic GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {\nboolean portIsOpen = false;\nGroupInfo groupInfo = new GroupInfo();\ntry {\nFilter filter = Filter.builder()\n.name(\"group-name\")\n.values(\"default\")\n.build();\nScenarios 591\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFilter filter1 = Filter.builder()\n.name(\"vpc-id\")\n.values(VPC)\n.build();\nDescribeSecurityGroupsRequest securityGroupsRequest =\nDescribeSecurityGroupsRequest.builder()\n.filters(filter, filter1)\n.build();\nDescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()\n.describeSecurityGroups(securityGroupsRequest);\nString securityGroup =\nsecurityGroupsResponse.securityGroups().get(0).groupName();\ngroupInfo.setGroupName(securityGroup);\nfor (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {\nSystem.out.println(\"Found security group: \" + secGroup.groupId());\nfor (IpPermission ipPermission : secGroup.ipPermissions()) {\nif (ipPermission.fromPort() == port) {\nSystem.out.println(\"Found inbound rule: \" + ipPermission);\nfor (IpRange ipRange : ipPermission.ipRanges()) {\nString cidrIp = ipRange.cidrIp();\nif (cidrIp.startsWith(ipAddress) ||\ncidrIp.equals(\"0.0.0.0/0\")) {\nSystem.out.println(cidrIp + \" is applicable\");\nportIsOpen = true;\n}\n}\nif (!ipPermission.prefixListIds().isEmpty()) {\nSystem.out.println(\"Prefix lList is applicable\");\nportIsOpen = true;\n}\nif (!portIsOpen) {\nSystem.out\n.println(\"The inbound rule does not appear to be\nopen to either this computer's IP,\"\n+ \" all IP addresses (0.0.0.0/0), or to\na prefix list ID.\");\n} else {\nScenarios 592\nAWS SDK for Java 2.x Developer Guide for version 2.x\nbreak;\n}\n}\n}\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\ngroupInfo.setPortOpen(portIsOpen);\nreturn groupInfo;\n}\n/*\n* Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto\n* Scaling group.\n* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\nScenarios 593\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Get availability zones.", "mimetype": "text/plain", "start_char_idx": 925528, "end_char_idx": 929429, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "86613be0-b201-40ed-a6b1-54581e753641": {"__data__": {"id_": "86613be0-b201-40ed-a6b1-54581e753641", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8fc7e000-a3c2-4f96-87c9-0bea15114873", "node_type": "1", "metadata": {}, "hash": "624f27f8ce4572c345721ec8ce928ae416e6763be9056f6452cb80fcad4bd790", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f6237566-db60-4345-9af3-4b79f7263880", "node_type": "1", "metadata": {}, "hash": "235509e0a8cab68cd375b5e02fe882cfc4b424a98edc5b41536dffe6c6872648", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\nScenarios 593\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Get availability zones.\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\nzonesRequest =\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\n.builder()\n.build();\nDescribeAvailabilityZonesResponse zonesResponse =\ngetEc2Client().describeAvailabilityZones(zonesRequest);\nList availabilityZoneNames =\nzonesResponse.availabilityZones().stream()\n.map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)\n.collect(Collectors.toList());\nString availabilityZones = String.join(\",\", availabilityZoneNames);\nLaunchTemplateSpecification specification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(templateName)\n.version(\"$Default\")\n.build();\nString[] zones = availabilityZones.split(\",\");\nCreateAutoScalingGroupRequest groupRequest =\nCreateAutoScalingGroupRequest.builder()\n.launchTemplate(specification)\n.availabilityZones(zones)\n.maxSize(groupSize)\n.minSize(groupSize)\n.autoScalingGroupName(autoScalingGroupName)\n.build();\ntry {\ngetAutoScalingClient().createAutoScalingGroup(groupRequest);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Created an EC2 Auto Scaling group named \" +\nautoScalingGroupName);\nreturn zones;\n}\nScenarios 594\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic String getDefaultVPC() {\n// Define the filter.\nFilter defaultFilter = Filter.builder()\n.name(\"is-default\")\n.values(\"true\")\n.build();\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request =\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest\n.builder()\n.filters(defaultFilter)\n.build();\nDescribeVpcsResponse response = getEc2Client().describeVpcs(request);\nreturn response.vpcs().get(0).vpcId();\n}\n// Gets the default subnets in a VPC for a specified list of Availability Zones.\npublic List getSubnets(String vpcId, String[] availabilityZones) {\nList subnets = null;\nFilter vpcFilter = Filter.builder()\n.name(\"vpc-id\")\n.values(vpcId)\n.build();\nFilter azFilter = Filter.builder()\n.name(\"availability-zone\")\n.values(availabilityZones)\n.build();\nFilter defaultForAZ = Filter.builder()\n.name(\"default-for-az\")\n.values(\"true\")\n.build();\nDescribeSubnetsRequest request = DescribeSubnetsRequest.builder()\n.filters(vpcFilter, azFilter, defaultForAZ)\n.build();\nDescribeSubnetsResponse response = getEc2Client().describeSubnets(request);\nsubnets = response.subnets();\nreturn subnets;\n}\nScenarios 595\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Gets data about the instances in the EC2 Auto Scaling group.\npublic String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.", "mimetype": "text/plain", "start_char_idx": 928543, "end_char_idx": 932749, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f6237566-db60-4345-9af3-4b79f7263880": {"__data__": {"id_": "f6237566-db60-4345-9af3-4b79f7263880", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "86613be0-b201-40ed-a6b1-54581e753641", "node_type": "1", "metadata": {}, "hash": "6f1862a0d067de8725356940d853ba4cd0d1146e7e8a757ec93ef935505e5ff8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0e5ab22d-2e9a-4b95-bfb0-660d20dcae0d", "node_type": "1", "metadata": {}, "hash": "1dc800329cd894fcc6954d7d5f7f3c463ea56d539c75f12aa06a9c0fe6a4afa2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.\npublic String getInstanceProfile(String instanceId) {\nFilter filter = Filter.builder()\n.name(\"instance-id\")\n.values(instanceId)\n.build();\nDescribeIamInstanceProfileAssociationsRequest associationsRequest =\nDescribeIamInstanceProfileAssociationsRequest\n.builder()\n.filters(filter)\n.build();\nDescribeIamInstanceProfileAssociationsResponse response = getEc2Client()\n.describeIamInstanceProfileAssociations(associationsRequest);\nreturn response.iamInstanceProfileAssociations().get(0).associationId();\n}\npublic void deleteRolesPolicies(String policyName, String roleName, String\nInstanceProfile) {\nListPoliciesRequest listPoliciesRequest =\nListPoliciesRequest.builder().build();\nScenarios 596\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListPoliciesResponse listPoliciesResponse =\ngetIAMClient().listPolicies(listPoliciesRequest);\nfor (Policy policy : listPoliciesResponse.policies()) {\nif (policy.policyName().equals(policyName)) {\n// List the entities (users, groups, roles) that are attached to the\npolicy.\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\nlistEntitiesRequest =\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\n.builder()\n.policyArn(policy.arn())\n.build();\nListEntitiesForPolicyResponse listEntitiesResponse = iamClient\n.listEntitiesForPolicy(listEntitiesRequest);\nif (!listEntitiesResponse.policyGroups().isEmpty() || !\nlistEntitiesResponse.policyUsers().isEmpty()\n|| !listEntitiesResponse.policyRoles().isEmpty()) {\n// Detach the policy from any entities it is attached to.\nDetachRolePolicyRequest detachPolicyRequest =\nDetachRolePolicyRequest.builder()\n.policyArn(policy.arn())\n.roleName(roleName) // Specify the name of the IAM role\n.build();\ngetIAMClient().detachRolePolicy(detachPolicyRequest);\nSystem.out.println(\"Policy detached from entities.\");\n}\n// Now, you can delete the policy.\nDeletePolicyRequest deletePolicyRequest =\nDeletePolicyRequest.builder()\n.policyArn(policy.arn())\n.build();\ngetIAMClient().deletePolicy(deletePolicyRequest);\nSystem.out.println(\"Policy deleted successfully.\");\nbreak;\n}\n}\n// List the roles associated with the instance profile\nListInstanceProfilesForRoleRequest listRolesRequest =\nListInstanceProfilesForRoleRequest.builder()\nScenarios 597\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.roleName(roleName)\n.build();\n// Detach the roles from the instance profile\nListInstanceProfilesForRoleResponse listRolesResponse =\niamClient.listInstanceProfilesForRole(listRolesRequest);\nfor (software.amazon.awssdk.services.iam.model.InstanceProfile profile :\nlistRolesResponse.instanceProfiles()) {\nRemoveRoleFromInstanceProfileRequest removeRoleRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.roleName(roleName) // Remove the extra dot here\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);\nSystem.out.println(\"Role \" + roleName + \" removed from instance profile\n\" + InstanceProfile);\n}\n// Delete the instance profile after removing all roles\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.build();\ngetIAMClient().deleteInstanceProfile(r ->\nr.instanceProfileName(InstanceProfile));\nSystem.out.println(InstanceProfile + \" Deleted\");\nSystem.out.println(\"All roles and policies are deleted.\");\n}\n}\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\nScenarios 598\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.", "mimetype": "text/plain", "start_char_idx": 932007, "end_char_idx": 936644, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0e5ab22d-2e9a-4b95-bfb0-660d20dcae0d": {"__data__": {"id_": "0e5ab22d-2e9a-4b95-bfb0-660d20dcae0d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f6237566-db60-4345-9af3-4b79f7263880", "node_type": "1", "metadata": {}, "hash": "235509e0a8cab68cd375b5e02fe882cfc4b424a98edc5b41536dffe6c6872648", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "640b07a7-4f08-48da-b512-683641fefc29", "node_type": "1", "metadata": {}, "hash": "daecce7d3c455a50bdd548350e6523f553fcb56e0290594382742ba167aee991", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n}\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\nScenarios 598\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.\npublic List checkTargetHealth(String targetGroupName) {\nDescribeTargetGroupsRequest targetGroupsRequest =\nDescribeTargetGroupsRequest.builder()\n.names(targetGroupName)\n.build();\nDescribeTargetGroupsResponse tgResponse =\ngetLoadBalancerClient().describeTargetGroups(targetGroupsRequest);\nDescribeTargetHealthRequest healthRequest =\nDescribeTargetHealthRequest.builder()\n.targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())\n.build();\nDescribeTargetHealthResponse healthResponse =\ngetLoadBalancerClient().describeTargetHealth(healthRequest);\nreturn healthResponse.targetHealthDescriptions();\n}\n// Gets the HTTP endpoint of the load balancer.\npublic String getEndpoint(String lbName) {\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nreturn res.loadBalancers().get(0).dnsName();\n}\n// Deletes a load balancer.\npublic void deleteLoadBalancer(String lbName) {\ntry {\n// Use a waiter to delete the Load Balancer.\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())\n.build();\nScenarios 599\nAWS SDK for Java 2.x Developer Guide for version 2.x\ngetLoadBalancerClient().deleteLoadBalancer(\nbuilder ->\nbuilder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancersDeleted(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(lbName + \" was deleted.\");\n}\n// Deletes the target group.\npublic void deleteTargetGroup(String targetGroupName) {\ntry {\nDescribeTargetGroupsResponse res = getLoadBalancerClient()\n.describeTargetGroups(describe ->\ndescribe.names(targetGroupName));\ngetLoadBalancerClient()\n.deleteTargetGroup(builder ->\nbuilder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(targetGroupName + \" was deleted.\");\n}\n// Verify this computer can successfully send a GET request to the load balancer\n// endpoint.\npublic boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException,\nInterruptedException {\nboolean success = false;\nint retries = 3;\nCloseableHttpClient httpClient = HttpClients.createDefault();\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" + elbDnsName);\ntry {\nwhile ((!success) && (retries > 0)) {\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nScenarios 600\nAWS SDK for Java 2.x Developer Guide for version 2.x\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.", "mimetype": "text/plain", "start_char_idx": 936106, "end_char_idx": 940299, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "640b07a7-4f08-48da-b512-683641fefc29": {"__data__": {"id_": "640b07a7-4f08-48da-b512-683641fefc29", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0e5ab22d-2e9a-4b95-bfb0-660d20dcae0d", "node_type": "1", "metadata": {}, "hash": "1dc800329cd894fcc6954d7d5f7f3c463ea56d539c75f12aa06a9c0fe6a4afa2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b709e6c9-327a-41b7-a204-ac572ba3b050", "node_type": "1", "metadata": {}, "hash": "2ccf12d065a5c6c11bff835625272784fb6f860162ec9d8a94189be2db4ef35f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "HttpResponse response = httpClient.execute(httpGet);\nScenarios 600\nAWS SDK for Java 2.x Developer Guide for version 2.x\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.\n*/\npublic String createTargetGroup(String protocol, int port, String vpcId, String\ntargetGroupName) {\nCreateTargetGroupRequest targetGroupRequest =\nCreateTargetGroupRequest.builder()\n.healthCheckPath(\"/healthcheck\")\n.healthCheckTimeoutSeconds(5)\n.port(port)\n.vpcId(vpcId)\n.name(targetGroupName)\n.protocol(protocol)\n.build();\nCreateTargetGroupResponse targetGroupResponse =\ngetLoadBalancerClient().createTargetGroup(targetGroupRequest);\nString targetGroupArn =\ntargetGroupResponse.targetGroups().get(0).targetGroupArn();\nString targetGroup =\ntargetGroupResponse.targetGroups().get(0).targetGroupName();\nScenarios 601\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"The \" + targetGroup + \" was created with ARN\" +\ntargetGroupArn);\nreturn targetGroupArn;\n}\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.\n*/\npublic String createLoadBalancer(List subnetIds, String targetGroupARN,\nString lbName, int port,\nString protocol) {\ntry {\nList subnetIdStrings = subnetIds.stream()\n.map(Subnet::subnetId)\n.collect(Collectors.toList());\nCreateLoadBalancerRequest balancerRequest =\nCreateLoadBalancerRequest.builder()\n.subnets(subnetIdStrings)\n.name(lbName)\n.scheme(\"internet-facing\")\n.build();\n// Create and wait for the load balancer to become available.\nCreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(lbARN)\n.build();\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\nScenarios 602\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Get the DNS name (endpoint) of the load balancer.\nString lbDNSName = lsResponse.loadBalancers().get(0).dnsName();\nSystem.out.println(\"*** Load Balancer DNS Name: \" + lbDNSName);\n// Create a listener for the load balance.\nAction action = Action.builder()\n.targetGroupArn(targetGroupARN)\n.type(\"forward\")\n.build();\nCreateListenerRequest listenerRequest = CreateListenerRequest.builder()\n.loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())\n.defaultActions(action)\n.port(port)\n.protocol(protocol)\n.defaultActions(action)\n.build();\ngetLoadBalancerClient().createListener(listenerRequest);\nSystem.out.println(\"Created listener to forward traffic from load\nbalancer \" + lbName + \" to target group \"\n+ targetGroupARN);\n// Return the load balancer DNS name.\nreturn lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nScenarios 603\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.\nDescribeTableRequest describeTableRequest =\nDescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ngetDynamoDbClient().describeTable(describeTableRequest);\nSystem.out.println(\"Table '\" + tableName + \"' exists.", "mimetype": "text/plain", "start_char_idx": 939543, "end_char_idx": 944096, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b709e6c9-327a-41b7-a204-ac572ba3b050": {"__data__": {"id_": "b709e6c9-327a-41b7-a204-ac572ba3b050", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "640b07a7-4f08-48da-b512-683641fefc29", "node_type": "1", "metadata": {}, "hash": "daecce7d3c455a50bdd548350e6523f553fcb56e0290594382742ba167aee991", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c9920f29-354c-4b57-9be4-1cd5de4be0b8", "node_type": "1", "metadata": {}, "hash": "407283857bcf25807fe942347e473431e1b0fa3803b4ac23a26cf171a7ce81b2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nScenarios 603\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.\nDescribeTableRequest describeTableRequest =\nDescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ngetDynamoDbClient().describeTable(describeTableRequest);\nSystem.out.println(\"Table '\" + tableName + \"' exists.\");\nreturn true;\n} catch (ResourceNotFoundException e) {\nSystem.out.println(\"Table '\" + tableName + \"' does not exist.\");\n} catch (DynamoDbException e) {\nSystem.err.println(\"Error checking table existence: \" + e.getMessage());\n}\nreturn false;\n}\n/*\n* Creates a DynamoDB table to use a recommendation service. The table has a\n* hash key named 'MediaType' that defines the type of media recommended, such\n* as\n* Book or Movie, and a range key named 'ItemId' that, combined with the\n* MediaType,\n* forms a unique identifier for the recommended item.\n*/\npublic void createTable(String tableName, String fileName) throws IOException {\n// First check to see if the table exists.\nboolean doesExist = doesTableExist(tableName);\nif (!doesExist) {\nDynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();\nCreateTableRequest createTableRequest = CreateTableRequest.builder()\n.tableName(tableName)\nScenarios 604\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.attributeDefinitions(\nAttributeDefinition.builder()\n.attributeName(\"MediaType\")\n.attributeType(ScalarAttributeType.S)\n.build(),\nAttributeDefinition.builder()\n.attributeName(\"ItemId\")\n.attributeType(ScalarAttributeType.N)\n.build())\n.keySchema(\nKeySchemaElement.builder()\n.attributeName(\"MediaType\")\n.keyType(KeyType.HASH)\n.build(),\nKeySchemaElement.builder()\n.attributeName(\"ItemId\")\n.keyType(KeyType.RANGE)\n.build())\n.provisionedThroughput(\nProvisionedThroughput.builder()\n.readCapacityUnits(5L)\n.writeCapacityUnits(5L)\n.build())\n.build();\ngetDynamoDbClient().createTable(createTableRequest);\nSystem.out.println(\"Creating table \" + tableName + \"...\");\n// Wait until the Amazon DynamoDB table is created.\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Table \" + tableName + \" created.\");\n// Add records to the table.\npopulateTable(fileName, tableName);\n}\n}\npublic void deleteTable(String tableName) {\nScenarios 605\nAWS SDK for Java 2.x Developer Guide for version 2.x\ngetDynamoDbClient().deleteTable(table -> table.tableName(tableName));\nSystem.out.println(\"Table \" + tableName + \" deleted.\");\n}\n// Populates the table with data located in a JSON file using the DynamoDB\n// enhanced client.\npublic void populateTable(String fileName, String tableName) throws IOException\n{\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(getDynamoDbClient())\n.build();\nObjectMapper objectMapper = new ObjectMapper();\nFile jsonFile = new File(fileName);\nJsonNode rootNode = objectMapper.readTree(jsonFile);\nDynamoDbTable mappedTable = enhancedClient.table(tableName,\nTableSchema.fromBean(Recommendation.class));\nfor (JsonNode currentNode : rootNode) {\nString mediaType = currentNode.path(\"MediaType\").path(\"S\").asText();\nint itemId = currentNode.path(\"ItemId\").path(\"N\").asInt();\nString title = currentNode.path(\"Title\").path(\"S\").asText();\nString creator = currentNode.path(\"Creator\").path(\"S\").asText();\n// Create a Recommendation object and set its properties.\nRecommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nCreate a class that wraps Systems Manager actions.", "mimetype": "text/plain", "start_char_idx": 943223, "end_char_idx": 947654, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c9920f29-354c-4b57-9be4-1cd5de4be0b8": {"__data__": {"id_": "c9920f29-354c-4b57-9be4-1cd5de4be0b8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b709e6c9-327a-41b7-a204-ac572ba3b050", "node_type": "1", "metadata": {}, "hash": "2ccf12d065a5c6c11bff835625272784fb6f860162ec9d8a94189be2db4ef35f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b67a7af3-3450-4042-89fa-f7ef60de3b75", "node_type": "1", "metadata": {}, "hash": "5a91e3a0d1bcd6449e16d7b510d880873032fd3b58f443e04747739da7d5c0ea", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Recommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nCreate a class that wraps Systems Manager actions.\npublic class ParameterHelper {\nString tableName = \"doc-example-resilient-architecture-table\";\nScenarios 606\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString dyntable = \"doc-example-recommendation-service\";\nString failureResponse = \"doc-example-resilient-architecture-failure-response\";\nString healthCheck = \"doc-example-resilient-architecture-health-check\";\npublic void reset() {\nput(dyntable, tableName);\nput(failureResponse, \"none\");\nput(healthCheck, \"shallow\");\n}\npublic void put(String name, String value) {\nSsmClient ssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\nPutParameterRequest parameterRequest = PutParameterRequest.builder()\n.name(name)\n.value(value)\n.overwrite(true)\n.type(\"String\")\n.build();\nssmClient.putParameter(parameterRequest);\nSystem.out.printf(\"Setting demo parameter %s to '%s'.\", name, value);\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 AttachLoadBalancerTargetGroups\n\u2022 CreateAutoScalingGroup\n\u2022 CreateInstanceProfile\n\u2022 CreateLaunchTemplate\n\u2022 CreateListener\n\u2022 CreateLoadBalancer\n\u2022 CreateTargetGroup\n\u2022 DeleteAutoScalingGroup\n\u2022 DeleteInstanceProfile\n\u2022 DeleteLaunchTemplate\nScenarios 607\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 DeleteLoadBalancer\n\u2022 DeleteTargetGroup\n\u2022 DescribeAutoScalingGroups\n\u2022 DescribeAvailabilityZones\n\u2022 DescribeIamInstanceProfileAssociations\n\u2022 DescribeInstances\n\u2022 DescribeLoadBalancers\n\u2022 DescribeSubnets\n\u2022 DescribeTargetGroups\n\u2022 DescribeTargetHealth\n\u2022 DescribeVpcs\n\u2022 RebootInstances\n\u2022 ReplaceIamInstanceProfileAssociation\n\u2022 TerminateInstanceInAutoScalingGroup\n\u2022 UpdateAutoScalingGroup\nAWS Batch examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with AWS Batch.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello AWS Batch\nThe following code example shows how to get started using AWS Batch.\nAWS Batch 608\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 947290, "end_char_idx": 950257, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b67a7af3-3450-4042-89fa-f7ef60de3b75": {"__data__": {"id_": "b67a7af3-3450-4042-89fa-f7ef60de3b75", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c9920f29-354c-4b57-9be4-1cd5de4be0b8", "node_type": "1", "metadata": {}, "hash": "407283857bcf25807fe942347e473431e1b0fa3803b4ac23a26cf171a7ce81b2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c52d7ca-871c-4e4e-b094-6e51e7e242a7", "node_type": "1", "metadata": {}, "hash": "323d11750aec9388f158ec27e43dfe0a5fc33473d33d69d536c816b455f0d236", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello AWS Batch\nThe following code example shows how to get started using AWS Batch.\nAWS Batch 608\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;\nimport software.amazon.awssdk.core.retry.RetryPolicy;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.batch.BatchAsyncClient;\nimport software.amazon.awssdk.services.batch.model.JobStatus;\nimport software.amazon.awssdk.services.batch.model.JobSummary;\nimport software.amazon.awssdk.services.batch.model.ListJobsRequest;\nimport software.amazon.awssdk.services.batch.paginators.ListJobsPublisher;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\npublic class HelloBatch {\nprivate static BatchAsyncClient batchClient;\npublic static void main(String[] args) {\nList jobs = listJobs(\"my-job-queue\");\njobs.forEach(job ->\nSystem.out.printf(\"Job ID: %s, Job Name: %s, Job Status: %s%n\",\njob.jobId(), job.jobName(), job.status())\n);\n}\npublic static List listJobs(String jobQueue) {\nif (jobQueue == null || jobQueue.isEmpty()) {\nthrow new IllegalArgumentException(\"Job queue cannot be null or empty\");\n}\nListJobsRequest listJobsRequest = ListJobsRequest.builder()\n.jobQueue(jobQueue)\n.jobStatus(JobStatus.SUCCEEDED)\nAWS Batch 609\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nList jobSummaries = new ArrayList<>();\nListJobsPublisher listJobsPaginator =\ngetAsyncClient().listJobsPaginator(listJobsRequest);\nCompletableFuture future = listJobsPaginator.subscribe(response -> {\njobSummaries.addAll(response.jobSummaryList());\n});\nfuture.join();\nreturn jobSummaries;\n}\nprivate static BatchAsyncClient getAsyncClient() {\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(100) // Increase max concurrency to handle more\nsimultaneous connections.\n.connectionTimeout(Duration.ofSeconds(60)) // Set the connection\ntimeout.\n.readTimeout(Duration.ofSeconds(60)) // Set the read timeout.\n.writeTimeout(Duration.ofSeconds(60)) // Set the write timeout.\n.build();\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2)) // Set the overall API call\ntimeout.\n.apiCallAttemptTimeout(Duration.ofSeconds(90)) // Set the individual\ncall attempt timeout.\n.retryPolicy(RetryPolicy.builder() // Add a retry policy to handle\ntransient errors.\n.numRetries(3) // Number of retry attempts.\n.build())\n.build();\nif (batchClient == null) {\nbatchClient = BatchAsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn batchClient;\n}\nAWS Batch 610\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see listJobsPaginator in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateComputeEnvironment\nThe following code example shows how to use CreateComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously creates a new compute environment in AWS Batch.", "mimetype": "text/plain", "start_char_idx": 949459, "end_char_idx": 953489, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9c52d7ca-871c-4e4e-b094-6e51e7e242a7": {"__data__": {"id_": "9c52d7ca-871c-4e4e-b094-6e51e7e242a7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b67a7af3-3450-4042-89fa-f7ef60de3b75", "node_type": "1", "metadata": {}, "hash": "5a91e3a0d1bcd6449e16d7b510d880873032fd3b58f443e04747739da7d5c0ea", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fb3ed8d6-77b1-4a97-b398-907695774fda", "node_type": "1", "metadata": {}, "hash": "b0a4cda4d7b20b3563c8640243d97230d57931225bff1151a31c7f2678477a45", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".retryPolicy(RetryPolicy.builder() // Add a retry policy to handle\ntransient errors.\n.numRetries(3) // Number of retry attempts.\n.build())\n.build();\nif (batchClient == null) {\nbatchClient = BatchAsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn batchClient;\n}\nAWS Batch 610\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see listJobsPaginator in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateComputeEnvironment\nThe following code example shows how to use CreateComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously creates a new compute environment in AWS Batch.\n*\n* @param computeEnvironmentName the name of the compute environment to create\n* @param batchIAMRole the IAM role to be used by the compute environment\n* @param subnet the subnet ID to be used for the compute environment\n* @param secGroup the security group ID to be used for the compute environment\n* @return a {@link CompletableFuture} representing the asynchronous operation,\nwhich will complete with the\n* {@link CreateComputeEnvironmentResponse} when the compute environment\nhas been created\n* @throws BatchException if there is an error creating the compute environment\n* @throws RuntimeException if there is an unexpected error during the operation\n*/\npublic CompletableFuture\ncreateComputeEnvironmentAsync(\nActions 611\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString computeEnvironmentName, String batchIAMRole, String subnet, String\nsecGroup) {\nCreateComputeEnvironmentRequest environmentRequest =\nCreateComputeEnvironmentRequest.builder()\n.computeEnvironmentName(computeEnvironmentName)\n.type(CEType.MANAGED)\n.state(CEState.ENABLED)\n.computeResources(ComputeResource.builder()\n.type(CRType.FARGATE)\n.maxvCpus(256)\n.subnets(Collections.singletonList(subnet))\n.securityGroupIds(Collections.singletonList(secGroup))\n.build())\n.serviceRole(batchIAMRole)\n.build();\nCompletableFuture response =\ngetAsyncClient().createComputeEnvironment(environmentRequest);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response;\n}\n\u2022 For API details, see CreateComputeEnvironment in AWS SDK for Java 2.x API Reference.\nCreateJobQueue\nThe following code example shows how to use CreateJobQueue.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 612\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Creates a job queue asynchronously.\n*\n* @param jobQueueName the name of the job queue to create\n* @param computeEnvironmentName the name of the compute environment to\nassociate with the job queue\n* @return a CompletableFuture that completes with the Amazon Resource Name\n(ARN) of the job queue\n*/\npublic CompletableFuture createJobQueueAsync(String jobQueueName, String\ncomputeEnvironmentName) {\nif (jobQueueName == null || jobQueueName.isEmpty()) {\nthrow new IllegalArgumentException(\"Job queue name cannot be null or\nempty\");\n}\nif (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {\nthrow new IllegalArgumentException(\"Compute environment name cannot be\nnull or empty\");\n}\nCreateJobQueueRequest request = CreateJobQueueRequest.builder()\n.jobQueueName(jobQueueName)\n.priority(1)\n.computeEnvironmentOrder(ComputeEnvironmentOrder.builder()\n.computeEnvironment(computeEnvironmentName)\n.order(1)\n.build())\n.build();\nCompletableFuture response =\ngetAsyncClient().createJobQueue(request);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response.thenApply(CreateJobQueueResponse::jobQueueArn);\n}\nActions 613\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see CreateJobQueue in AWS SDK for Java 2.x API Reference.\nDeleteComputeEnvironment\nThe following code example shows how to use DeleteComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 952659, "end_char_idx": 957162, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fb3ed8d6-77b1-4a97-b398-907695774fda": {"__data__": {"id_": "fb3ed8d6-77b1-4a97-b398-907695774fda", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c52d7ca-871c-4e4e-b094-6e51e7e242a7", "node_type": "1", "metadata": {}, "hash": "323d11750aec9388f158ec27e43dfe0a5fc33473d33d69d536c816b455f0d236", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2c90791a-8b60-4b87-b7a9-fb79b21bbc7f", "node_type": "1", "metadata": {}, "hash": "e7efaab390ab6a239f4b82cf3bf9d13c426cf92358dfb63a4a4945539b8f0826", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteComputeEnvironment\nThe following code example shows how to use DeleteComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic CompletableFuture\ndeleteComputeEnvironmentAsync(String computeEnvironmentName) {\nDeleteComputeEnvironmentRequest deleteComputeEnvironment =\nDeleteComputeEnvironmentRequest.builder()\n.computeEnvironment(computeEnvironmentName)\n.build();\nreturn getAsyncClient().deleteComputeEnvironment(deleteComputeEnvironment)\n.whenComplete((response, ex) -> {\nif (ex != null) {\nThrowable cause = ex.getCause();\nif (cause instanceof BatchException) {\nthrow new RuntimeException(cause);\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n}\n});\n}\n\u2022 For API details, see DeleteComputeEnvironment in AWS SDK for Java 2.x API Reference.\nDeleteJobQueue\nThe following code example shows how to use DeleteJobQueue.\nActions 614\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes a Batch job queue asynchronously.\n*\n* @param jobQueueArn The Amazon Resource Name (ARN) of the job queue to delete.\n* @return A CompletableFuture that represents the asynchronous deletion of the\njob queue.\n* The future completes when the job queue has been successfully deleted\nor if an error occurs.\n* If successful, the future will be completed with a {@code Void}\nvalue.\n* If an error occurs, the future will be completed exceptionally with\nthe thrown exception.\n*/\npublic CompletableFuture deleteJobQueueAsync(String jobQueueArn) {\nDeleteJobQueueRequest deleteRequest = DeleteJobQueueRequest.builder()\n.jobQueue(jobQueueArn)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().deleteJobQueue(deleteRequest);\nreturn responseFuture.whenComplete((deleteResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(deleteResponse -> null);\n}\n\u2022 For API details, see DeleteJobQueue in AWS SDK for Java 2.x API Reference.\nActions 615\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeregisterJobDefinition\nThe following code example shows how to use DeregisterJobDefinition.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deregisters a job definition asynchronously.\n*\n* @param jobDefinition the name of the job definition to be deregistered\n* @return a CompletableFuture that completes when the job definition has been\nderegistered\n* or an exception has occurred\n*/\npublic CompletableFuture\nderegisterJobDefinitionAsync(String jobDefinition) {\nDeregisterJobDefinitionRequest jobDefinitionRequest =\nDeregisterJobDefinitionRequest.builder()\n.jobDefinition(jobDefinition)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().deregisterJobDefinition(jobDefinitionRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n});\nreturn responseFuture;\n}\n\u2022 For API details, see DeregisterJobDefinition in AWS SDK for Java 2.x API Reference.\nActions 616\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeComputeEnvironments\nThe following code example shows how to use DescribeComputeEnvironments.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Checks the status of the specified compute environment.", "mimetype": "text/plain", "start_char_idx": 956927, "end_char_idx": 960745, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2c90791a-8b60-4b87-b7a9-fb79b21bbc7f": {"__data__": {"id_": "2c90791a-8b60-4b87-b7a9-fb79b21bbc7f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fb3ed8d6-77b1-4a97-b398-907695774fda", "node_type": "1", "metadata": {}, "hash": "b0a4cda4d7b20b3563c8640243d97230d57931225bff1151a31c7f2678477a45", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fa8e738f-f0bd-4796-82c9-debe907be99a", "node_type": "1", "metadata": {}, "hash": "8d72131edc3b75dccd60f3655259f1ff530cb82cffaf8bc43d7f29366deccaa3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 616\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeComputeEnvironments\nThe following code example shows how to use DescribeComputeEnvironments.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Checks the status of the specified compute environment.\n*\n* @param computeEnvironmentName the name of the compute environment to check\n* @return a CompletableFuture containing the status of the compute environment,\nor \"ERROR\" if an exception occurs\n*/\npublic CompletableFuture checkComputeEnvironmentsStatus(String\ncomputeEnvironmentName) {\nif (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {\nthrow new IllegalArgumentException(\"Compute environment name cannot be\nnull or empty\");\n}\nDescribeComputeEnvironmentsRequest environmentsRequest =\nDescribeComputeEnvironmentsRequest.builder()\n.computeEnvironments(computeEnvironmentName)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeComputeEnvironments(environmentsRequest);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response.thenApply(resp -> resp.computeEnvironments().stream()\n.map(env -> env.statusAsString())\nActions 617\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.findFirst()\n.orElse(\"UNKNOWN\"));\n}\n\u2022 For API details, see DescribeComputeEnvironments in AWS SDK for Java 2.x API Reference.\nDescribeJobQueues\nThe following code example shows how to use DescribeJobQueues.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously describes the job queue associated with the specified compute\nenvironment.\n*\n* @param computeEnvironmentName the name of the compute environment to find the\nassociated job queue for\n* @return a {@link CompletableFuture} that, when completed, contains the job\nqueue ARN associated with the specified compute environment\n* @throws RuntimeException if the job queue description fails\n*/\npublic CompletableFuture describeJobQueueAsync(String\ncomputeEnvironmentName) {\nDescribeJobQueuesRequest describeJobQueuesRequest =\nDescribeJobQueuesRequest.builder()\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobQueues(describeJobQueuesRequest);\nreturn responseFuture.whenComplete((describeJobQueuesResponse, ex) -> {\nif (describeJobQueuesResponse != null) {\nString jobQueueARN;\nfor (JobQueueDetail jobQueueDetail :\ndescribeJobQueuesResponse.jobQueues()) {\nActions 618\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfor (ComputeEnvironmentOrder computeEnvironmentOrder :\njobQueueDetail.computeEnvironmentOrder()) {\nString computeEnvironment =\ncomputeEnvironmentOrder.computeEnvironment();\nString name = getComputeEnvironmentName(computeEnvironment);\nif (name.equals(computeEnvironmentName)) {\njobQueueARN = jobQueueDetail.jobQueueArn();\nlogger.info(\"Job queue ARN associated with the compute\nenvironment: \" + jobQueueARN);\n}\n}\n}\n} else {\nthrow new RuntimeException(\"Failed to describe job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(describeJobQueuesResponse -> {\nString jobQueueARN = \"\";\nfor (JobQueueDetail jobQueueDetail :\ndescribeJobQueuesResponse.jobQueues()) {\nfor (ComputeEnvironmentOrder computeEnvironmentOrder :\njobQueueDetail.computeEnvironmentOrder()) {\nString computeEnvironment =\ncomputeEnvironmentOrder.computeEnvironment();\nString name = getComputeEnvironmentName(computeEnvironment);\nif (name.equals(computeEnvironmentName)) {\njobQueueARN = jobQueueDetail.jobQueueArn();\n}\n}\n}\nreturn jobQueueARN;\n});\n}\n\u2022 For API details, see DescribeJobQueues in AWS SDK for Java 2.x API Reference.\nDescribeJobs\nThe following code example shows how to use DescribeJobs.\nActions 619\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously retrieves the status of a specific job.", "mimetype": "text/plain", "start_char_idx": 960377, "end_char_idx": 964604, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fa8e738f-f0bd-4796-82c9-debe907be99a": {"__data__": {"id_": "fa8e738f-f0bd-4796-82c9-debe907be99a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2c90791a-8b60-4b87-b7a9-fb79b21bbc7f", "node_type": "1", "metadata": {}, "hash": "e7efaab390ab6a239f4b82cf3bf9d13c426cf92358dfb63a4a4945539b8f0826", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a90ca940-500e-42cd-a60b-c6d92577959f", "node_type": "1", "metadata": {}, "hash": "f76e31598686961cc7bb5874112d587a879a51d8bf21e154b4958d0c0bf2e5e9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeJobs\nThe following code example shows how to use DescribeJobs.\nActions 619\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously retrieves the status of a specific job.\n*\n* @param jobId the ID of the job to retrieve the status for\n* @return a CompletableFuture that completes with the job status\n*/\npublic CompletableFuture describeJobAsync(String jobId) {\nDescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()\n.jobs(jobId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobs(describeJobsRequest);\nreturn responseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n}).thenApply(response -> response.jobs().get(0).status().toString());\n}\n\u2022 For API details, see DescribeJobs in AWS SDK for Java 2.x API Reference.\nListJobsPaginator\nThe following code example shows how to use ListJobsPaginator.\nActions 620\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously lists the jobs in the specified job queue with the given job\nstatus.\n*\n* @param jobQueue the name of the job queue to list jobs from\n* @return a List that contains the jobs that succeeded\n*/\npublic List listJobsAsync(String jobQueue) {\nif (jobQueue == null || jobQueue.isEmpty()) {\nthrow new IllegalArgumentException(\"Job queue cannot be null or empty\");\n}\nListJobsRequest listJobsRequest = ListJobsRequest.builder()\n.jobQueue(jobQueue)\n.jobStatus(JobStatus.SUCCEEDED) // Filter jobs by status.\n.build();\nList jobSummaries = new ArrayList<>();\nListJobsPublisher listJobsPaginator =\ngetAsyncClient().listJobsPaginator(listJobsRequest);\nCompletableFuture future = listJobsPaginator.subscribe(response -> {\njobSummaries.addAll(response.jobSummaryList());\n});\nfuture.join();\nreturn jobSummaries;\n}\n\u2022 For API details, see ListJobsPaginator in AWS SDK for Java 2.x API Reference.\nRegisterJobDefinition\nThe following code example shows how to use RegisterJobDefinition.\nActions 621\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Registers a new job definition asynchronously in AWS Batch.\n*

\n* When using Fargate as the compute environment, it is crucial to set the\n* {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to\n* ensure proper networking configuration for the Fargate tasks. This\n* allows the tasks to communicate with external services, access the\n* internet, or communicate within a VPC.", "mimetype": "text/plain", "start_char_idx": 964267, "end_char_idx": 967221, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a90ca940-500e-42cd-a60b-c6d92577959f": {"__data__": {"id_": "a90ca940-500e-42cd-a60b-c6d92577959f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fa8e738f-f0bd-4796-82c9-debe907be99a", "node_type": "1", "metadata": {}, "hash": "8d72131edc3b75dccd60f3655259f1ff530cb82cffaf8bc43d7f29366deccaa3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ce338694-235d-4b75-a875-08cfef1cea84", "node_type": "1", "metadata": {}, "hash": "3d7cee0b73ae2885494e5335efefe50a56f2152179c5a60e9cc9b31d4a357b8f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "RegisterJobDefinition\nThe following code example shows how to use RegisterJobDefinition.\nActions 621\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Registers a new job definition asynchronously in AWS Batch.\n*

\n* When using Fargate as the compute environment, it is crucial to set the\n* {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to\n* ensure proper networking configuration for the Fargate tasks. This\n* allows the tasks to communicate with external services, access the\n* internet, or communicate within a VPC.\n*\n* @param jobDefinitionName the name of the job definition to be registered\n* @param executionRoleARN the ARN (Amazon Resource Name) of the execution role\n* that provides permissions for the containers in the\njob\n* @param cpuArch a value of either X86_64 or ARM64 required for the service\ncall\n* @return a CompletableFuture that completes with the ARN of the registered\n* job definition upon successful execution, or completes exceptionally\nwith\n* an error if the registration fails\n*/\npublic CompletableFuture registerJobDefinitionAsync(String\njobDefinitionName, String executionRoleARN, String image, String cpuArch) {\nNetworkConfiguration networkConfiguration = NetworkConfiguration.builder()\n.assignPublicIp(AssignPublicIp.ENABLED)\n.build();\nContainerProperties containerProperties = ContainerProperties.builder()\n.image(image)\n.executionRoleArn(executionRoleARN)\n.resourceRequirements(\nArrays.asList(\nResourceRequirement.builder()\n.type(ResourceType.VCPU)\n.value(\"1\")\nActions 622\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build(),\nResourceRequirement.builder()\n.type(ResourceType.MEMORY)\n.value(\"2048\")\n.build()\n)\n)\n.networkConfiguration(networkConfiguration)\n.runtimePlatform(b -> b\n.cpuArchitecture(cpuArch)\n.operatingSystemFamily(\"LINUX\"))\n.build();\nRegisterJobDefinitionRequest request =\nRegisterJobDefinitionRequest.builder()\n.jobDefinitionName(jobDefinitionName)\n.type(JobDefinitionType.CONTAINER)\n.containerProperties(containerProperties)\n.platformCapabilities(PlatformCapability.FARGATE)\n.build();\nCompletableFuture future = new CompletableFuture<>();\ngetAsyncClient().registerJobDefinition(request)\n.thenApply(RegisterJobDefinitionResponse::jobDefinitionArn)\n.whenComplete((result, ex) -> {\nif (ex != null) {\nfuture.completeExceptionally(ex);\n} else {\nfuture.complete(result);\n}\n});\nreturn future;\n}\n\u2022 For API details, see RegisterJobDefinition in AWS SDK for Java 2.x API Reference.\nSubmitJob\nThe following code example shows how to use SubmitJob.\nActions 623\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Submits a job asynchronously to the AWS Batch service.\n*\n* @param jobDefinitionName the name of the job definition to use\n* @param jobQueueName the name of the job queue to submit the job to\n* @param jobARN the Amazon Resource Name (ARN) of the job definition\n* @return a CompletableFuture that, when completed, contains the job ID of the\nsubmitted job\n*/\npublic CompletableFuture submitJobAsync(String jobDefinitionName, String\njobQueueName, String jobARN) {\nSubmitJobRequest jobRequest = SubmitJobRequest.builder()\n.jobDefinition(jobARN)\n.jobName(jobDefinitionName)\n.jobQueue(jobQueueName)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().submitJob(jobRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n});\nreturn responseFuture.thenApply(SubmitJobResponse::jobId);\n}\n\u2022 For API details, see SubmitJob in AWS SDK for Java 2.x API Reference.\nActions 624\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUpdateComputeEnvironment\nThe following code example shows how to use UpdateComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Disables the specified compute environment asynchronously.", "mimetype": "text/plain", "start_char_idx": 966532, "end_char_idx": 970781, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ce338694-235d-4b75-a875-08cfef1cea84": {"__data__": {"id_": "ce338694-235d-4b75-a875-08cfef1cea84", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a90ca940-500e-42cd-a60b-c6d92577959f", "node_type": "1", "metadata": {}, "hash": "f76e31598686961cc7bb5874112d587a879a51d8bf21e154b4958d0c0bf2e5e9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0a91000f-30be-4a5a-b93a-969cef413cc2", "node_type": "1", "metadata": {}, "hash": "099a2c1cab0ac55aeb0adb6528f6465491a8ca0efcf378d05cf2b82d8cb8eca2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 624\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUpdateComputeEnvironment\nThe following code example shows how to use UpdateComputeEnvironment.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Disables the specified compute environment asynchronously.\n*\n* @param computeEnvironmentName the name of the compute environment to disable\n* @return a CompletableFuture that completes when the compute environment is\ndisabled\n*/\npublic CompletableFuture\ndisableComputeEnvironmentAsync(String computeEnvironmentName) {\nUpdateComputeEnvironmentRequest updateRequest =\nUpdateComputeEnvironmentRequest.builder()\n.computeEnvironment(computeEnvironmentName)\n.state(CEState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateComputeEnvironment(updateRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to disable compute environment: \"\n+ ex.getMessage(), ex);\n}\n});\nreturn responseFuture;\n}\n\u2022 For API details, see UpdateComputeEnvironment in AWS SDK for Java 2.x API Reference.\nActions 625\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUpdateJobQueue\nThe following code example shows how to use UpdateJobQueue.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Disables the specified job queue asynchronously.\n*\n* @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be\ndisabled\n* @return a {@link CompletableFuture} that completes when the job queue update\noperation is complete,\n* or completes exceptionally if an error occurs during the operation\n*/\npublic CompletableFuture disableJobQueueAsync(String jobQueueArn) {\nUpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()\n.jobQueue(jobQueueArn)\n.state(JQState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateJobQueue(updateRequest);\nreturn responseFuture.whenComplete((updateResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to update job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(updateResponse -> null);\n}\n\u2022 For API details, see UpdateJobQueue in AWS SDK for Java 2.x API Reference.\nActions 626\nAWS SDK for Java 2.x Developer Guide for version 2.x\nScenarios\nLearn AWS Batch core operations\nThe following code example shows how to:\n\u2022 Create an AWS Batch compute environment.\n\u2022 Check the status of the compute environment.\n\u2022 Set up an AWS Batch job queue and job definition.\n\u2022 Register a job definition.\n\u2022 Submit an AWS Batch Job.\n\u2022 Get a list of jobs applicable to the job queue.\n\u2022 Check the status of job.\n\u2022 Delete AWS Batch resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun an interactive scenario demonstrating AWS Batch features.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.batch.model.BatchException;\nimport software.amazon.awssdk.services.batch.model.ClientException;\nimport software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentResponse;\nimport software.amazon.awssdk.services.batch.model.JobSummary;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeSubnetsRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeSubnetsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest;\nimport software.amazon.awssdk.services.ec2.model.Filter;\nimport software.amazon.awssdk.services.ec2.model.SecurityGroup;\nScenarios 627\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.ec2.model.Subnet;\nimport software.amazon.awssdk.services.ec2.model.Vpc;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.UUID;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* NOTE\n* This scenario submits a job that pulls a Docker image named echo-text from Amazon\nECR to Amazon Fargate.", "mimetype": "text/plain", "start_char_idx": 970416, "end_char_idx": 975192, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0a91000f-30be-4a5a-b93a-969cef413cc2": {"__data__": {"id_": "0a91000f-30be-4a5a-b93a-969cef413cc2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ce338694-235d-4b75-a875-08cfef1cea84", "node_type": "1", "metadata": {}, "hash": "3d7cee0b73ae2885494e5335efefe50a56f2152179c5a60e9cc9b31d4a357b8f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c2733677-9c87-4b0a-9039-eba8db290368", "node_type": "1", "metadata": {}, "hash": "0caceaaf7c4f5d16489e39efd9a5ca0cc1e763db8bf52516355476c1acce0d17", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* NOTE\n* This scenario submits a job that pulls a Docker image named echo-text from Amazon\nECR to Amazon Fargate.\n*\n* To place this Docker image on Amazon ECR, run the following Basics scenario.\n*\n* https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr\n*\n*/\npublic class BatchScenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\n// Define two stacks used in this Basics Scenario.\nprivate static final String ROLES_STACK = \"RolesStack\";\nprivate static String defaultSubnet;\nprivate static String defaultSecurityGroup;\nprivate static final Logger logger =\nLoggerFactory.getLogger(BatchScenario.class);\npublic static void main(String[] args) throws InterruptedException {\nBatchActions batchActions = new BatchActions();\nScanner scanner = new Scanner(System.in);\nString computeEnvironmentName = \"my-compute-environment\";\nScenarios 628\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString jobQueueName = \"my-job-queue\";\nString jobDefinitionName = \"my-job-definition\";\n// See the NOTE in this Java code example (at start).\nString dockerImage = \"dkr.ecr.us-east-1.amazonaws.com/echo-text:echo-text\";\nlogger.info(\"\"\"\nAWS Batch is a fully managed batch processing service that dynamically\nprovisions the required compute\nresources for batch computing workloads. The Java V2 `BatchAsyncClient`\nallows\ndevelopers to automate the submission, monitoring, and management of\nbatch jobs.\nThis scenario provides an example of setting up a compute environment,\njob queue and job definition,\nand then submitting a job.\nThis scenario submits a job that pulls a Docker image named echo-text\nfrom Amazon ECR to Amazon Fargate.\nTo place this Docker image on Amazon ECR, run the following Basics\nscenario.\nhttps://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/\nexample_code/ecr\nLet's get started...\nYou have two choices:\n1 - Run the entire program.\n2 - Delete an existing Compute Environment (created from a previous\nexecution of\nthis program that did not complete).\n\"\"\");\nwhile (true) {\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"1\")) {\nlogger.info(\"Continuing with the program...\");\n// logger.info(\"\");\nbreak;\nScenarios 629\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else if (input.trim().equalsIgnoreCase(\"2\")) {\nString jobQueueARN = String.valueOf(batchActions.\ndescribeJobQueueAsync(computeEnvironmentName));\nif (!jobQueueARN.isEmpty()) {\nbatchActions.disableJobQueueAsync(jobQueueARN);\ncountdown(1);\nbatchActions.deleteJobQueueAsync(jobQueueARN);\n}\ntry {\nbatchActions.disableComputeEnvironmentAsync(computeEnvironmentName)\n.exceptionally(ex -> {\nlogger.info(\"Disable compute environment failed: \" +\nex.getMessage());\nreturn null;\n})\n.join();\n} catch (CompletionException ex) {\nlogger.info(\"Failed to disable compute environment: \" +\nex.getMessage());\n}\ncountdown(2);\nbatchActions.deleteComputeEnvironmentAsync(computeEnvironmentName).join();\nreturn;\n} else {\n// Handle invalid input.\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\nSystem.out.println(DASHES);\nwaitForInputToContinue(scanner);\n// Get an AWS Account id used to retrieve the docker image from Amazon ECR.\n// Create a single-element array to store the `accountId` value.\nString[] accId = new String[1];\nCompletableFuture accountIdFuture = batchActions.getAccountId();\naccountIdFuture.thenAccept(accountId -> {\nlogger.info(\"Account ID: \" + accountId);\naccId[0] = accountId;\n}).join();\ndockerImage = accId[0]+\".\"+dockerImage;\nScenarios 630\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Get a default subnet and default security associated with the default\nVPC.\ngetSubnetSecurityGroup();\nlogger.info(\"Use AWS CloudFormation to create two IAM roles that are\nrequired for this scenario.\");\nCloudFormationHelper.deployCloudFormationStack(ROLES_STACK);\nMap stackOutputs =\nCloudFormationHelper.getStackOutputs(ROLES_STACK);\nString batchIAMRole = stackOutputs.get(\"BatchRoleArn\");\nString executionRoleARN = stackOutputs.get(\"EcsRoleArn\");\nlogger.info(\"The IAM role needed to interact with AWS Batch is\n\"+batchIAMRole);\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"1. Create a Batch compute environment\");\nlogger.info(\"\"\"\nA compute environment is a resource where you can run your batch jobs.\nAfter creating a compute environment, you can define job queues and job\ndefinitions to submit jobs for\nexecution.", "mimetype": "text/plain", "start_char_idx": 974927, "end_char_idx": 979505, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c2733677-9c87-4b0a-9039-eba8db290368": {"__data__": {"id_": "c2733677-9c87-4b0a-9039-eba8db290368", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0a91000f-30be-4a5a-b93a-969cef413cc2", "node_type": "1", "metadata": {}, "hash": "099a2c1cab0ac55aeb0adb6528f6465491a8ca0efcf378d05cf2b82d8cb8eca2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5f05a5f2-c568-46b3-acae-a0458dc291b3", "node_type": "1", "metadata": {}, "hash": "4e892e89d04f96e18690dcbbf7ab855e150a8330a6e58072e74fa0a97a6db921", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "getSubnetSecurityGroup();\nlogger.info(\"Use AWS CloudFormation to create two IAM roles that are\nrequired for this scenario.\");\nCloudFormationHelper.deployCloudFormationStack(ROLES_STACK);\nMap stackOutputs =\nCloudFormationHelper.getStackOutputs(ROLES_STACK);\nString batchIAMRole = stackOutputs.get(\"BatchRoleArn\");\nString executionRoleARN = stackOutputs.get(\"EcsRoleArn\");\nlogger.info(\"The IAM role needed to interact with AWS Batch is\n\"+batchIAMRole);\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"1. Create a Batch compute environment\");\nlogger.info(\"\"\"\nA compute environment is a resource where you can run your batch jobs.\nAfter creating a compute environment, you can define job queues and job\ndefinitions to submit jobs for\nexecution.\nThe benefit of creating a compute environment is it allows you to easily\nconfigure and manage the compute\nresources that will be used to run your Batch jobs. By separating the\ncompute environment from the job definitions,\nyou can easily scale your compute resources up or down as needed,\nwithout having to modify your job definitions.\nThis makes it easier to manage your Batch workloads and ensures that\nyour jobs have the necessary\ncompute resources to run efficiently.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nbatchActions.createComputeEnvironmentAsync(computeEnvironmentName, batchIAMRole,\ndefaultSubnet, defaultSecurityGroup);\nCreateComputeEnvironmentResponse response = future.join();\nScenarios 631\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Compute Environment ARN: \" +\nresponse.computeEnvironmentArn());\n} catch (RuntimeException rte) {\nThrowable cause = rte.getCause();\nif (cause instanceof ClientException batchExceptionEx) {\nString myErrorCode =\nbatchExceptionEx.awsErrorDetails().errorMessage();\nif (\"Object already exists\".contains(myErrorCode)) {\nlogger.info(\"The compute environment '\" + computeEnvironmentName\n+ \"' already exists. Moving on...\");\n} else {\nlogger.info(\"Batch error occurred: {} (Code: {})\",\nbatchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());\nreturn;\n}\n} else {\nlogger.info(\"An unexpected error occurred: {}\", (cause != null ?\ncause.getMessage() : rte.getMessage()));\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"2. Check the status of the \"+computeEnvironmentName +\" Compute\nEnvironment.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nbatchActions.checkComputeEnvironmentsStatus(computeEnvironmentName);\nString status = future.join();\nlogger.info(\"Compute Environment Status: \" + status);\n} catch (RuntimeException rte) {\nThrowable cause = rte.getCause();\nif (cause instanceof ClientException batchExceptionEx) {\nlogger.info(\"Batch error occurred: {} (Code: {})\",\nbatchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: \" + (cause != null ?\ncause.getMessage() : rte.getMessage()));\nreturn;\n}\nScenarios 632\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"3. Create a job queue\");\nlogger.info(\"\"\"\nA job queue is an essential component that helps manage the execution\nof your batch jobs.\nIt acts as a buffer, where jobs are placed and then scheduled for\nexecution based on their\npriority and the available resources in the compute environment.\n\"\"\");\nwaitForInputToContinue(scanner);\nString jobQueueArn = null;\ntry {\nCompletableFuture jobQueueFuture =\nbatchActions.createJobQueueAsync(jobQueueName, computeEnvironmentName);\njobQueueArn = jobQueueFuture.join();\nlogger.info(\"Job Queue ARN: \" + jobQueueArn);\n} catch (RuntimeException rte) {\nThrowable cause = rte.getCause();\nif (cause instanceof BatchException batchExceptionEx) {\nString myErrorCode =\nbatchExceptionEx.awsErrorDetails().errorMessage();\nif (\"Object already exists\".contains(myErrorCode)) {\nlogger.info(\"The job queue '\" + jobQueueName + \"' already\nexists. Moving on...\");\n// Retrieve the ARN of the job queue.\nCompletableFuture jobQueueArnFuture =\nbatchActions.getJobQueueARN(jobQueueName);\njobQueueArn = jobQueueArnFuture.join();\nlogger.info(\"Job Queue ARN: \" + jobQueueArn);\n} else {\nlogger.info(\"Batch error occurred: {} (Code: {})\",\nbatchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());\nreturn;\n}\n} else {\nlogger.info(\"An unexpected error occurred: \" + (cause != null ?", "mimetype": "text/plain", "start_char_idx": 978730, "end_char_idx": 983286, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5f05a5f2-c568-46b3-acae-a0458dc291b3": {"__data__": {"id_": "5f05a5f2-c568-46b3-acae-a0458dc291b3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c2733677-9c87-4b0a-9039-eba8db290368", "node_type": "1", "metadata": {}, "hash": "0caceaaf7c4f5d16489e39efd9a5ca0cc1e763db8bf52516355476c1acce0d17", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c4faae1-3dc6-4d2f-8f08-5439bbfcebb0", "node_type": "1", "metadata": {}, "hash": "7302848249891f8bd58407a4d21b031660067af43e659261d033215d63d6bf73", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Moving on...\");\n// Retrieve the ARN of the job queue.\nCompletableFuture jobQueueArnFuture =\nbatchActions.getJobQueueARN(jobQueueName);\njobQueueArn = jobQueueArnFuture.join();\nlogger.info(\"Job Queue ARN: \" + jobQueueArn);\n} else {\nlogger.info(\"Batch error occurred: {} (Code: {})\",\nbatchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());\nreturn;\n}\n} else {\nlogger.info(\"An unexpected error occurred: \" + (cause != null ?\ncause.getMessage() : rte.getMessage()));\nreturn; // End the execution\nScenarios 633\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"4. Register a Job Definition.\");\nlogger.info(\"\"\"\nRegistering a job in AWS Batch using the Fargate launch type ensures\nthat all\nnecessary parameters, such as the execution role, command to run, and so\non\nare specified and reused across multiple job submissions.\nThe job definition pulls a Docker image from Amazon ECR and executes\nthe Docker image.\n\"\"\");\nwaitForInputToContinue(scanner);\nString jobARN;\ntry {\nString platform = \"\";\nwhile (true) {\nlogger.info(\"\"\"\nOn which platform/CPU architecture combination did you build the\nDocker image?:\n1. Windows X86_64\n2. Mac or Linux ARM64\n3. Mac or Linux X86_64\nPlease select 1, 2, or 3.\n\"\"\");\nString platAns = scanner.nextLine().trim();\nif (platAns.equals(\"1\")) {\nplatform = \"X86_64\";\nbreak; // Exit loop since a valid option is selected\n} else if (platAns.equals(\"2\")) {\nplatform = \"ARM64\";\nbreak; // Exit loop since a valid option is selected\n} else if (platAns.equals(\"3\")) {\nplatform = \"X86_64\";\nbreak; // Exit loop since a valid option is selected\n} else {\nSystem.out.println(\"Invalid input. Please select either 1 or\n2.\");\nScenarios 634\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\njobARN = batchActions.registerJobDefinitionAsync(jobDefinitionName,\nexecutionRoleARN, dockerImage, platform)\n.exceptionally(ex -> {\nSystem.err.println(\"Register job definition failed: \" +\nex.getMessage());\nreturn null;\n})\n.join();\nif (jobARN != null) {\nlogger.info(\"Job ARN: \" + jobARN);\n}\n} catch (RuntimeException rte) {\nlogger.error(\"A Batch exception occurred while registering the job: {}\",\nrte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"5. Submit an AWS Batch job from a job definition.\");\nwaitForInputToContinue(scanner);\nString jobId;\ntry {\njobId = batchActions.submitJobAsync(jobDefinitionName, jobQueueName,\njobARN)\n.exceptionally(ex -> {\nSystem.err.println(\"Submit job failed: \" + ex.getMessage());\nreturn null;\n})\n.join();\nlogger.info(\"The job id is \"+jobId);\nlogger.info(\"Let's wait 2 minutes for the job to complete\");\ncountdown(2);\n} catch (RuntimeException rte) {\nlogger.error(\"A Batch exception occurred while submitting the job: {}\",\nrte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nScenarios 635\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nlogger.info(DASHES);\nlogger.info(\"6. Get a list of jobs applicable to the job queue.\");\nwaitForInputToContinue(scanner);\ntry {\nList jobs = batchActions.listJobsAsync(jobQueueName);\njobs.forEach(job ->\nlogger.info(\"Job ID: {}, Job Name: {}, Job Status: {}\", job.jobId(),\njob.jobName(), job.status()));\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred while submitting the job: {}\",\nrte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"7. Check the status of job \"+jobId);\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future = batchActions.describeJobAsync(jobId);\nString jobStatus = future.join();\nlogger.info(\"Job Status: \" + jobStatus);\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred while submitting the job: {}\",\nrte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nlogger.info(\"8.", "mimetype": "text/plain", "start_char_idx": 982835, "end_char_idx": 986971, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5c4faae1-3dc6-4d2f-8f08-5439bbfcebb0": {"__data__": {"id_": "5c4faae1-3dc6-4d2f-8f08-5439bbfcebb0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5f05a5f2-c568-46b3-acae-a0458dc291b3", "node_type": "1", "metadata": {}, "hash": "4e892e89d04f96e18690dcbbf7ab855e150a8330a6e58072e74fa0a97a6db921", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "31b31038-b6d5-4bf2-b9f8-4a063ea4e8ac", "node_type": "1", "metadata": {}, "hash": "f1c3ef4bd24ff34ffa7bc9445a0821b0eadd59bd5b1064ef7b142e814cb4dc9f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"7. Check the status of job \"+jobId);\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future = batchActions.describeJobAsync(jobId);\nString jobStatus = future.join();\nlogger.info(\"Job Status: \" + jobStatus);\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred while submitting the job: {}\",\nrte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nlogger.info(\"8. Delete Batch resources\");\nlogger.info(\n\"\"\"\nWhen deleting an AWS Batch compute environment, it does not happen\ninstantaneously.\nThere is typically a delay, similar to some other AWS resources.\nScenarios 636\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAWS Batch starts the deletion process.\n\"\"\");\nlogger.info(\"Would you like to delete the AWS Batch resources such as the\ncompute environment? (y/n)\");\nString delAns = scanner.nextLine().trim();\nif (delAns.equalsIgnoreCase(\"y\")) {\nlogger.info(\"You selected to delete the AWS ECR resources.\");\nlogger.info(\"First, we will deregister the Job Definition.\");\nwaitForInputToContinue(scanner);\ntry {\nbatchActions.deregisterJobDefinitionAsync(jobARN)\n.exceptionally(ex -> {\nlogger.info(\"Deregister job definition failed: \" +\nex.getMessage());\nreturn null;\n})\n.join();\nlogger.info(jobARN + \" was deregistered\");\n} catch (RuntimeException rte) {\nlogger.error(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nlogger.info(\"Second, we will disable and then delete the Job Queue.\");\nwaitForInputToContinue(scanner);\ntry {\nbatchActions.disableJobQueueAsync(jobQueueArn)\n.exceptionally(ex -> {\nlogger.info(\"Disable job queue failed: \" + ex.getMessage());\nreturn null;\n})\n.join();\nlogger.info(jobQueueArn + \" was disabled\");\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nbatchActions.waitForJobQueueToBeDisabledAsync(jobQueueArn);\ntry {\nCompletableFuture future =\nbatchActions.waitForJobQueueToBeDisabledAsync(jobQueueArn);\nScenarios 637\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfuture.join();\nlogger.info(\"Job queue is now disabled.\");\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\ntry {\nbatchActions.deleteJobQueueAsync(jobQueueArn);\nlogger.info(jobQueueArn +\" was deleted\");\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nlogger.info(\"Let's wait 2 minutes for the job queue to be deleted\");\ncountdown(2);\nwaitForInputToContinue(scanner);\nlogger.info(\"Third, we will delete the Compute Environment.\");\nwaitForInputToContinue(scanner);\ntry {\nbatchActions.disableComputeEnvironmentAsync(computeEnvironmentName)\n.exceptionally(ex -> {\nSystem.err.println(\"Disable compute environment failed: \" +\nex.getMessage());\nreturn null;\n})\n.join();\nlogger.info(\"Compute environment disabled\") ;\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nbatchActions.checkComputeEnvironmentsStatus(computeEnvironmentName).thenAccept(state\n-> {\nlogger.info(\"Current State: \" + state);\n}).join();\nScenarios 638\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Lets wait 1 min for the compute environment to be\ndeleted\");\ncountdown(1);\ntry {\nbatchActions.deleteComputeEnvironmentAsync(computeEnvironmentName).join();\nlogger.info(computeEnvironmentName +\" was deleted.\");\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ?", "mimetype": "text/plain", "start_char_idx": 986336, "end_char_idx": 990362, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "31b31038-b6d5-4bf2-b9f8-4a063ea4e8ac": {"__data__": {"id_": "31b31038-b6d5-4bf2-b9f8-4a063ea4e8ac", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5c4faae1-3dc6-4d2f-8f08-5439bbfcebb0", "node_type": "1", "metadata": {}, "hash": "7302848249891f8bd58407a4d21b031660067af43e659261d033215d63d6bf73", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "38cbb6c9-b411-4bb7-affc-7094cf098f01", "node_type": "1", "metadata": {}, "hash": "dae5d254107f1baf7df79ba6d66e7ef145358543accb724bf6d6c29c6e6c5c9e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nbatchActions.checkComputeEnvironmentsStatus(computeEnvironmentName).thenAccept(state\n-> {\nlogger.info(\"Current State: \" + state);\n}).join();\nScenarios 638\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Lets wait 1 min for the compute environment to be\ndeleted\");\ncountdown(1);\ntry {\nbatchActions.deleteComputeEnvironmentAsync(computeEnvironmentName).join();\nlogger.info(computeEnvironmentName +\" was deleted.\");\n} catch (RuntimeException rte) {\nlogger.info(\"A Batch exception occurred: {}\", rte.getCause() !=\nnull ? rte.getCause().getMessage() : rte.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nCloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);\n}\nlogger.info(DASHES);\nlogger.info(\"This concludes the AWS Batch SDK scenario\");\nlogger.info(DASHES);\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\n// Handle invalid input.\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\npublic static void countdown(int minutes) throws InterruptedException {\nint seconds = 0;\nfor (int i = minutes * 60 + seconds; i >= 0; i--) {\nint displayMinutes = i / 60;\nScenarios 639\nAWS SDK for Java 2.x Developer Guide for version 2.x\nint displaySeconds = i % 60;\nSystem.out.print(String.format(\"\\r%02d:%02d\", displayMinutes,\ndisplaySeconds));\nThread.sleep(1000); // Wait for 1 second\n}\nlogger.info(\"Countdown complete!\");\n}\nprivate static void getSubnetSecurityGroup() {\ntry (Ec2AsyncClient ec2Client = Ec2AsyncClient.create()) {\nCompletableFuture defaultVpcFuture =\nec2Client.describeVpcs(DescribeVpcsRequest.builder()\n.filters(Filter.builder()\n.name(\"is-default\")\n.values(\"true\")\n.build())\n.build())\n.thenApply(response -> response.vpcs().stream()\n.findFirst()\n.orElseThrow(() -> new RuntimeException(\"Default VPC not\nfound\")));\nCompletableFuture defaultSubnetFuture = defaultVpcFuture\n.thenCompose(vpc ->\nec2Client.describeSubnets(DescribeSubnetsRequest.builder()\n.filters(Filter.builder()\n.name(\"vpc-id\")\n.values(vpc.vpcId())\n.build(),\nFilter.builder()\n.name(\"default-for-az\")\n.values(\"true\")\n.build())\n.build())\n.thenApply(DescribeSubnetsResponse::subnets)\n.thenApply(subnets -> subnets.stream()\n.findFirst()\n.map(Subnet::subnetId)\n.orElseThrow(() -> new RuntimeException(\"No\ndefault subnet found\"))));\nCompletableFuture defaultSecurityGroupFuture = defaultVpcFuture\n.thenCompose(vpc ->\nec2Client.describeSecurityGroups(DescribeSecurityGroupsRequest.builder()\nScenarios 640\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.filters(Filter.builder()\n.name(\"group-name\")\n.values(\"default\")\n.build(),\nFilter.builder()\n.name(\"vpc-id\")\n.values(vpc.vpcId())\n.build())\n.build())\n.thenApply(DescribeSecurityGroupsResponse::securityGroups)\n.thenApply(securityGroups -> securityGroups.stream()\n.findFirst()\n.map(SecurityGroup::groupId)\n.orElseThrow(() -> new RuntimeException(\"No\ndefault security group found\"))));\ndefaultSubnet = defaultSubnetFuture.join();\ndefaultSecurityGroup = defaultSecurityGroupFuture.join();\n}\n}\n}\nA wrapper class for AWS Batch SDK methods.", "mimetype": "text/plain", "start_char_idx": 989769, "end_char_idx": 993099, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "38cbb6c9-b411-4bb7-affc-7094cf098f01": {"__data__": {"id_": "38cbb6c9-b411-4bb7-affc-7094cf098f01", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "31b31038-b6d5-4bf2-b9f8-4a063ea4e8ac", "node_type": "1", "metadata": {}, "hash": "f1c3ef4bd24ff34ffa7bc9445a0821b0eadd59bd5b1064ef7b142e814cb4dc9f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ef8b5ade-7c63-4c3a-96f4-4efb948dc40f", "node_type": "1", "metadata": {}, "hash": "891278ba59e95a5041b7825ec625c9f7d39f366d30e2c0c842c62eafc99ab4be", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;\nimport software.amazon.awssdk.core.retry.RetryPolicy;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.batch.BatchAsyncClient;\nimport software.amazon.awssdk.services.batch.BatchClient;\nimport software.amazon.awssdk.services.batch.model.AssignPublicIp;\nimport software.amazon.awssdk.services.batch.model.BatchException;\nimport software.amazon.awssdk.services.batch.model.CEState;\nimport software.amazon.awssdk.services.batch.model.CEType;\nimport software.amazon.awssdk.services.batch.model.CRType;\nimport software.amazon.awssdk.services.batch.model.ComputeEnvironmentOrder;\nimport software.amazon.awssdk.services.batch.model.ComputeResource;\nimport software.amazon.awssdk.services.batch.model.ContainerProperties;\nScenarios 641\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentRequest;\nimport software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentResponse;\nimport software.amazon.awssdk.services.batch.model.CreateJobQueueRequest;\nimport software.amazon.awssdk.services.batch.model.DeleteComputeEnvironmentRequest;\nimport software.amazon.awssdk.services.batch.model.DeleteComputeEnvironmentResponse;\nimport software.amazon.awssdk.services.batch.model.DeleteJobQueueRequest;\nimport software.amazon.awssdk.services.batch.model.DeleteJobQueueResponse;\nimport software.amazon.awssdk.services.batch.model.DeregisterJobDefinitionRequest;\nimport software.amazon.awssdk.services.batch.model.DeregisterJobDefinitionResponse;\nimport\nsoftware.amazon.awssdk.services.batch.model.DescribeComputeEnvironmentsRequest;\nimport\nsoftware.amazon.awssdk.services.batch.model.DescribeComputeEnvironmentsResponse;\nimport software.amazon.awssdk.services.batch.model.DescribeJobQueuesRequest;\nimport software.amazon.awssdk.services.batch.model.DescribeJobQueuesResponse;\nimport software.amazon.awssdk.services.batch.model.DescribeJobsRequest;\nimport software.amazon.awssdk.services.batch.model.DescribeJobsResponse;\nimport software.amazon.awssdk.services.batch.model.JQState;\nimport software.amazon.awssdk.services.batch.model.JobDefinitionType;\nimport software.amazon.awssdk.services.batch.model.JobDetail;\nimport software.amazon.awssdk.services.batch.model.JobQueueDetail;\nimport software.amazon.awssdk.services.batch.model.JobStatus;\nimport software.amazon.awssdk.services.batch.model.JobSummary;\nimport software.amazon.awssdk.services.batch.model.ListJobsRequest;\nimport software.amazon.awssdk.services.batch.model.RegisterJobDefinitionResponse;\nimport software.amazon.awssdk.services.batch.model.NetworkConfiguration;\nimport software.amazon.awssdk.services.batch.model.PlatformCapability;\nimport software.amazon.awssdk.services.batch.model.RegisterJobDefinitionRequest;\nimport software.amazon.awssdk.services.batch.model.ResourceRequirement;\nimport software.amazon.awssdk.services.batch.model.ResourceType;\nimport software.amazon.awssdk.services.batch.model.RuntimePlatform;\nimport software.amazon.awssdk.services.batch.model.SubmitJobRequest;\nimport software.amazon.awssdk.services.batch.model.CreateJobQueueResponse;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport\nsoftware.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;\nimport software.amazon.awssdk.services.batch.model.SubmitJobResponse;\nimport software.amazon.awssdk.services.batch.model.UpdateComputeEnvironmentRequest;\nScenarios 642\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.batch.model.UpdateComputeEnvironmentResponse;\nimport software.amazon.awssdk.services.batch.model.UpdateJobQueueRequest;\nimport software.amazon.awssdk.services.batch.model.UpdateJobQueueResponse;\nimport software.amazon.awssdk.services.batch.paginators.ListJobsPublisher;\nimport software.amazon.awssdk.services.sts.StsAsyncClient;\nimport software.amazon.awssdk.services.sts.model.GetCallerIdentityResponse;\npublic class BatchActions {\nprivate static BatchAsyncClient batchClient;\nprivate static final Logger logger =\nLoggerFactory.getLogger(BatchActions.class);\nprivate static BatchAsyncClient getAsyncClient() {\nif (batchClient == null) {\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(100)\n.connectionTimeout(Duration.ofSeconds(60))\n.readTimeout(Duration.ofSeconds(60))\n.writeTimeout(Duration.ofSeconds(60))\n.build();\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2))\n.apiCallAttemptTimeout(Duration.ofSeconds(90))\n.retryPolicy(RetryPolicy.builder()\n.numRetries(3)\n.build())\n.build();\nbatchClient = BatchAsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn batchClient;\n}\n/**\n* Asynchronously creates a new compute environment in AWS Batch.", "mimetype": "text/plain", "start_char_idx": 993100, "end_char_idx": 998394, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ef8b5ade-7c63-4c3a-96f4-4efb948dc40f": {"__data__": {"id_": "ef8b5ade-7c63-4c3a-96f4-4efb948dc40f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "38cbb6c9-b411-4bb7-affc-7094cf098f01", "node_type": "1", "metadata": {}, "hash": "dae5d254107f1baf7df79ba6d66e7ef145358543accb724bf6d6c29c6e6c5c9e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "26edbf00-cde8-46a8-959c-b31e5fe1f008", "node_type": "1", "metadata": {}, "hash": "5fae2b4c43333c12bbff15849b60faa15fb0e438008617d614240b416bfc6465", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param computeEnvironmentName the name of the compute environment to create\nScenarios 643\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param batchIAMRole the IAM role to be used by the compute environment\n* @param subnet the subnet ID to be used for the compute environment\n* @param secGroup the security group ID to be used for the compute environment\n* @return a {@link CompletableFuture} representing the asynchronous operation,\nwhich will complete with the\n* {@link CreateComputeEnvironmentResponse} when the compute environment\nhas been created\n* @throws BatchException if there is an error creating the compute environment\n* @throws RuntimeException if there is an unexpected error during the operation\n*/\npublic CompletableFuture\ncreateComputeEnvironmentAsync(\nString computeEnvironmentName, String batchIAMRole, String subnet, String\nsecGroup) {\nCreateComputeEnvironmentRequest environmentRequest =\nCreateComputeEnvironmentRequest.builder()\n.computeEnvironmentName(computeEnvironmentName)\n.type(CEType.MANAGED)\n.state(CEState.ENABLED)\n.computeResources(ComputeResource.builder()\n.type(CRType.FARGATE)\n.maxvCpus(256)\n.subnets(Collections.singletonList(subnet))\n.securityGroupIds(Collections.singletonList(secGroup))\n.build())\n.serviceRole(batchIAMRole)\n.build();\nCompletableFuture response =\ngetAsyncClient().createComputeEnvironment(environmentRequest);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response;\n}\npublic CompletableFuture\ndeleteComputeEnvironmentAsync(String computeEnvironmentName) {\nScenarios 644\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteComputeEnvironmentRequest deleteComputeEnvironment =\nDeleteComputeEnvironmentRequest.builder()\n.computeEnvironment(computeEnvironmentName)\n.build();\nreturn getAsyncClient().deleteComputeEnvironment(deleteComputeEnvironment)\n.whenComplete((response, ex) -> {\nif (ex != null) {\nThrowable cause = ex.getCause();\nif (cause instanceof BatchException) {\nthrow new RuntimeException(cause);\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n}\n});\n}\n/**\n* Checks the status of the specified compute environment.\n*\n* @param computeEnvironmentName the name of the compute environment to check\n* @return a CompletableFuture containing the status of the compute environment,\nor \"ERROR\" if an exception occurs\n*/\npublic CompletableFuture checkComputeEnvironmentsStatus(String\ncomputeEnvironmentName) {\nif (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {\nthrow new IllegalArgumentException(\"Compute environment name cannot be\nnull or empty\");\n}\nDescribeComputeEnvironmentsRequest environmentsRequest =\nDescribeComputeEnvironmentsRequest.builder()\n.computeEnvironments(computeEnvironmentName)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeComputeEnvironments(environmentsRequest);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nScenarios 645\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response.thenApply(resp -> resp.computeEnvironments().stream()\n.map(env -> env.statusAsString())\n.findFirst()\n.orElse(\"UNKNOWN\"));\n}\n/**\n* Creates a job queue asynchronously.\n*\n* @param jobQueueName the name of the job queue to create\n* @param computeEnvironmentName the name of the compute environment to\nassociate with the job queue\n* @return a CompletableFuture that completes with the Amazon Resource Name\n(ARN) of the job queue\n*/\npublic CompletableFuture createJobQueueAsync(String jobQueueName, String\ncomputeEnvironmentName) {\nif (jobQueueName == null || jobQueueName.isEmpty()) {\nthrow new IllegalArgumentException(\"Job queue name cannot be null or\nempty\");\n}\nif (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {\nthrow new IllegalArgumentException(\"Compute environment name cannot be\nnull or empty\");\n}\nCreateJobQueueRequest request = CreateJobQueueRequest.builder()\n.jobQueueName(jobQueueName)\n.priority(1)\n.computeEnvironmentOrder(ComputeEnvironmentOrder.builder()\n.computeEnvironment(computeEnvironmentName)\n.order(1)\n.build())\n.build();\nCompletableFuture response =\ngetAsyncClient().createJobQueue(request);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nScenarios 646\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n});\nreturn response.thenApply(CreateJobQueueResponse::jobQueueArn);\n}\n/**\n* Asynchronously lists the jobs in the specified job queue with the given job\nstatus.", "mimetype": "text/plain", "start_char_idx": 998395, "end_char_idx": 1003350, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "26edbf00-cde8-46a8-959c-b31e5fe1f008": {"__data__": {"id_": "26edbf00-cde8-46a8-959c-b31e5fe1f008", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ef8b5ade-7c63-4c3a-96f4-4efb948dc40f", "node_type": "1", "metadata": {}, "hash": "891278ba59e95a5041b7825ec625c9f7d39f366d30e2c0c842c62eafc99ab4be", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "823c20a6-e08e-42ab-b578-20f0047e95c7", "node_type": "1", "metadata": {}, "hash": "cf6f1c5101c5dacb541f83ea3baad92f607565226a3dcc79470301bf9d7aff0e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param jobQueue the name of the job queue to list jobs from\n* @return a List that contains the jobs that succeeded\n*/\npublic List listJobsAsync(String jobQueue) {\nif (jobQueue == null || jobQueue.isEmpty()) {\nthrow new IllegalArgumentException(\"Job queue cannot be null or empty\");\n}\nListJobsRequest listJobsRequest = ListJobsRequest.builder()\n.jobQueue(jobQueue)\n.jobStatus(JobStatus.SUCCEEDED) // Filter jobs by status.\n.build();\nList jobSummaries = new ArrayList<>();\nListJobsPublisher listJobsPaginator =\ngetAsyncClient().listJobsPaginator(listJobsRequest);\nCompletableFuture future = listJobsPaginator.subscribe(response -> {\njobSummaries.addAll(response.jobSummaryList());\n});\nfuture.join();\nreturn jobSummaries;\n}\n/**\n* Registers a new job definition asynchronously in AWS Batch.\n*

\n* When using Fargate as the compute environment, it is crucial to set the\n* {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to\n* ensure proper networking configuration for the Fargate tasks. This\n* allows the tasks to communicate with external services, access the\n* internet, or communicate within a VPC.\nScenarios 647\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* @param jobDefinitionName the name of the job definition to be registered\n* @param executionRoleARN the ARN (Amazon Resource Name) of the execution role\n* that provides permissions for the containers in the\njob\n* @param cpuArch a value of either X86_64 or ARM64 required for the service\ncall\n* @return a CompletableFuture that completes with the ARN of the registered\n* job definition upon successful execution, or completes exceptionally\nwith\n* an error if the registration fails\n*/\npublic CompletableFuture registerJobDefinitionAsync(String\njobDefinitionName, String executionRoleARN, String image, String cpuArch) {\nNetworkConfiguration networkConfiguration = NetworkConfiguration.builder()\n.assignPublicIp(AssignPublicIp.ENABLED)\n.build();\nContainerProperties containerProperties = ContainerProperties.builder()\n.image(image)\n.executionRoleArn(executionRoleARN)\n.resourceRequirements(\nArrays.asList(\nResourceRequirement.builder()\n.type(ResourceType.VCPU)\n.value(\"1\")\n.build(),\nResourceRequirement.builder()\n.type(ResourceType.MEMORY)\n.value(\"2048\")\n.build()\n)\n)\n.networkConfiguration(networkConfiguration)\n.runtimePlatform(b -> b\n.cpuArchitecture(cpuArch)\n.operatingSystemFamily(\"LINUX\"))\n.build();\nRegisterJobDefinitionRequest request =\nRegisterJobDefinitionRequest.builder()\n.jobDefinitionName(jobDefinitionName)\n.type(JobDefinitionType.CONTAINER)\n.containerProperties(containerProperties)\nScenarios 648\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.platformCapabilities(PlatformCapability.FARGATE)\n.build();\nCompletableFuture future = new CompletableFuture<>();\ngetAsyncClient().registerJobDefinition(request)\n.thenApply(RegisterJobDefinitionResponse::jobDefinitionArn)\n.whenComplete((result, ex) -> {\nif (ex != null) {\nfuture.completeExceptionally(ex);\n} else {\nfuture.complete(result);\n}\n});\nreturn future;\n}\n/**\n* Deregisters a job definition asynchronously.\n*\n* @param jobDefinition the name of the job definition to be deregistered\n* @return a CompletableFuture that completes when the job definition has been\nderegistered\n* or an exception has occurred\n*/\npublic CompletableFuture\nderegisterJobDefinitionAsync(String jobDefinition) {\nDeregisterJobDefinitionRequest jobDefinitionRequest =\nDeregisterJobDefinitionRequest.builder()\n.jobDefinition(jobDefinition)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().deregisterJobDefinition(jobDefinitionRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n});\nreturn responseFuture;\n}\nScenarios 649\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Disables the specified job queue asynchronously.\n*\n* @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be\ndisabled\n* @return a {@link CompletableFuture} that completes when the job queue update\noperation is complete,\n* or completes exceptionally if an error occurs during the operation\n*/\npublic CompletableFuture disableJobQueueAsync(String jobQueueArn) {\nUpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()\n.jobQueue(jobQueueArn)\n.state(JQState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateJobQueue(updateRequest);\nreturn responseFuture.whenComplete((updateResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to update job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(updateResponse -> null);\n}\n/**\n* Deletes a Batch job queue asynchronously.", "mimetype": "text/plain", "start_char_idx": 1003351, "end_char_idx": 1008173, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "823c20a6-e08e-42ab-b578-20f0047e95c7": {"__data__": {"id_": "823c20a6-e08e-42ab-b578-20f0047e95c7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "26edbf00-cde8-46a8-959c-b31e5fe1f008", "node_type": "1", "metadata": {}, "hash": "5fae2b4c43333c12bbff15849b60faa15fb0e438008617d614240b416bfc6465", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fbd578cc-4c00-43ec-9abc-ae50f8312684", "node_type": "1", "metadata": {}, "hash": "199084ae124b92d4eaaf83541088dbea58d893db84a812cb791509a299065421", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be\ndisabled\n* @return a {@link CompletableFuture} that completes when the job queue update\noperation is complete,\n* or completes exceptionally if an error occurs during the operation\n*/\npublic CompletableFuture disableJobQueueAsync(String jobQueueArn) {\nUpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()\n.jobQueue(jobQueueArn)\n.state(JQState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateJobQueue(updateRequest);\nreturn responseFuture.whenComplete((updateResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to update job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(updateResponse -> null);\n}\n/**\n* Deletes a Batch job queue asynchronously.\n*\n* @param jobQueueArn The Amazon Resource Name (ARN) of the job queue to delete.\n* @return A CompletableFuture that represents the asynchronous deletion of the\njob queue.\n* The future completes when the job queue has been successfully deleted\nor if an error occurs.\n* If successful, the future will be completed with a {@code Void}\nvalue.\n* If an error occurs, the future will be completed exceptionally with\nthe thrown exception.\n*/\npublic CompletableFuture deleteJobQueueAsync(String jobQueueArn) {\nDeleteJobQueueRequest deleteRequest = DeleteJobQueueRequest.builder()\n.jobQueue(jobQueueArn)\n.build();\nScenarios 650\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture responseFuture =\ngetAsyncClient().deleteJobQueue(deleteRequest);\nreturn responseFuture.whenComplete((deleteResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(deleteResponse -> null);\n}\n/**\n* Asynchronously describes the job queue associated with the specified compute\nenvironment.\n*\n* @param computeEnvironmentName the name of the compute environment to find the\nassociated job queue for\n* @return a {@link CompletableFuture} that, when completed, contains the job\nqueue ARN associated with the specified compute environment\n* @throws RuntimeException if the job queue description fails\n*/\npublic CompletableFuture describeJobQueueAsync(String\ncomputeEnvironmentName) {\nDescribeJobQueuesRequest describeJobQueuesRequest =\nDescribeJobQueuesRequest.builder()\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobQueues(describeJobQueuesRequest);\nreturn responseFuture.whenComplete((describeJobQueuesResponse, ex) -> {\nif (describeJobQueuesResponse != null) {\nString jobQueueARN;\nfor (JobQueueDetail jobQueueDetail :\ndescribeJobQueuesResponse.jobQueues()) {\nfor (ComputeEnvironmentOrder computeEnvironmentOrder :\njobQueueDetail.computeEnvironmentOrder()) {\nString computeEnvironment =\ncomputeEnvironmentOrder.computeEnvironment();\nString name = getComputeEnvironmentName(computeEnvironment);\nif (name.equals(computeEnvironmentName)) {\njobQueueARN = jobQueueDetail.jobQueueArn();\nlogger.info(\"Job queue ARN associated with the compute\nenvironment: \" + jobQueueARN);\n}\n}\nScenarios 651\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n} else {\nthrow new RuntimeException(\"Failed to describe job queue: \" +\nex.getMessage(), ex);\n}\n}).thenApply(describeJobQueuesResponse -> {\nString jobQueueARN = \"\";\nfor (JobQueueDetail jobQueueDetail :\ndescribeJobQueuesResponse.jobQueues()) {\nfor (ComputeEnvironmentOrder computeEnvironmentOrder :\njobQueueDetail.computeEnvironmentOrder()) {\nString computeEnvironment =\ncomputeEnvironmentOrder.computeEnvironment();\nString name = getComputeEnvironmentName(computeEnvironment);\nif (name.equals(computeEnvironmentName)) {\njobQueueARN = jobQueueDetail.jobQueueArn();\n}\n}\n}\nreturn jobQueueARN;\n});\n}\n/**\n* Disables the specified compute environment asynchronously.\n*\n* @param computeEnvironmentName the name of the compute environment to disable\n* @return a CompletableFuture that completes when the compute environment is\ndisabled\n*/\npublic CompletableFuture\ndisableComputeEnvironmentAsync(String computeEnvironmentName) {\nUpdateComputeEnvironmentRequest updateRequest =\nUpdateComputeEnvironmentRequest.builder()\n.computeEnvironment(computeEnvironmentName)\n.state(CEState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateComputeEnvironment(updateRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to disable compute environment: \"\n+ ex.getMessage(), ex);\nScenarios 652\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n});\nreturn responseFuture;\n}\n/**\n* Submits a job asynchronously to the AWS Batch service.", "mimetype": "text/plain", "start_char_idx": 1007354, "end_char_idx": 1012133, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fbd578cc-4c00-43ec-9abc-ae50f8312684": {"__data__": {"id_": "fbd578cc-4c00-43ec-9abc-ae50f8312684", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "823c20a6-e08e-42ab-b578-20f0047e95c7", "node_type": "1", "metadata": {}, "hash": "cf6f1c5101c5dacb541f83ea3baad92f607565226a3dcc79470301bf9d7aff0e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "059d64f8-83d7-4b00-8124-3e8dccc2bd94", "node_type": "1", "metadata": {}, "hash": "d868414a5e25798c6c6fe78cd356e7a805a10369f152c6dabde476b24cf68507", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param computeEnvironmentName the name of the compute environment to disable\n* @return a CompletableFuture that completes when the compute environment is\ndisabled\n*/\npublic CompletableFuture\ndisableComputeEnvironmentAsync(String computeEnvironmentName) {\nUpdateComputeEnvironmentRequest updateRequest =\nUpdateComputeEnvironmentRequest.builder()\n.computeEnvironment(computeEnvironmentName)\n.state(CEState.DISABLED)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().updateComputeEnvironment(updateRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to disable compute environment: \"\n+ ex.getMessage(), ex);\nScenarios 652\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n});\nreturn responseFuture;\n}\n/**\n* Submits a job asynchronously to the AWS Batch service.\n*\n* @param jobDefinitionName the name of the job definition to use\n* @param jobQueueName the name of the job queue to submit the job to\n* @param jobARN the Amazon Resource Name (ARN) of the job definition\n* @return a CompletableFuture that, when completed, contains the job ID of the\nsubmitted job\n*/\npublic CompletableFuture submitJobAsync(String jobDefinitionName, String\njobQueueName, String jobARN) {\nSubmitJobRequest jobRequest = SubmitJobRequest.builder()\n.jobDefinition(jobARN)\n.jobName(jobDefinitionName)\n.jobQueue(jobQueueName)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().submitJob(jobRequest);\nresponseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n});\nreturn responseFuture.thenApply(SubmitJobResponse::jobId);\n}\n/**\n* Asynchronously retrieves the status of a specific job.\n*\n* @param jobId the ID of the job to retrieve the status for\n* @return a CompletableFuture that completes with the job status\n*/\npublic CompletableFuture describeJobAsync(String jobId) {\nDescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()\n.jobs(jobId)\nScenarios 653\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobs(describeJobsRequest);\nreturn responseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n}).thenApply(response -> response.jobs().get(0).status().toString());\n}\n/**\n* Disables the specific job queue using the asynchronous Java client.", "mimetype": "text/plain", "start_char_idx": 1011227, "end_char_idx": 1013826, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "059d64f8-83d7-4b00-8124-3e8dccc2bd94": {"__data__": {"id_": "059d64f8-83d7-4b00-8124-3e8dccc2bd94", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fbd578cc-4c00-43ec-9abc-ae50f8312684", "node_type": "1", "metadata": {}, "hash": "199084ae124b92d4eaaf83541088dbea58d893db84a812cb791509a299065421", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "de04f443-e141-406b-97cf-552bbccc19d2", "node_type": "1", "metadata": {}, "hash": "0fe83dea90a98dc54590cce2fd7300b52b6090f1c66c516e3c121a2cf7f7b30c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param jobId the ID of the job to retrieve the status for\n* @return a CompletableFuture that completes with the job status\n*/\npublic CompletableFuture describeJobAsync(String jobId) {\nDescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()\n.jobs(jobId)\nScenarios 653\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobs(describeJobsRequest);\nreturn responseFuture.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Unexpected error occurred: \" +\nex.getMessage(), ex);\n}\n}).thenApply(response -> response.jobs().get(0).status().toString());\n}\n/**\n* Disables the specific job queue using the asynchronous Java client.\n*\n* @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to wait\nfor\n* @return a {@link CompletableFuture} that completes when the job queue is\ndisabled\n*/\npublic CompletableFuture waitForJobQueueToBeDisabledAsync(String\njobQueueArn) {\nAtomicBoolean isDisabled = new AtomicBoolean(false);\nreturn CompletableFuture.runAsync(() -> {\nwhile (!isDisabled.get()) {\nDescribeJobQueuesRequest describeRequest =\nDescribeJobQueuesRequest.builder()\n.jobQueues(jobQueueArn)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().describeJobQueues(describeRequest);\nresponseFuture.whenComplete((describeResponse, ex) -> {\nif (describeResponse != null) {\nfor (JobQueueDetail jobQueue : describeResponse.jobQueues())\n{\nif (jobQueue.jobQueueArn().equals(jobQueueArn) &&\njobQueue.state() == JQState.DISABLED) {\nisDisabled.set(true);\nbreak;\n}\n}\n} else {\nScenarios 654\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow new RuntimeException(\"Error describing job queues\",\nex);\n}\n}).join();\nif (!isDisabled.get()) {\ntry {\nlogger.info(\"Waiting for job queue to be disabled...\");\nThread.sleep(5000);\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\nthrow new RuntimeException(\"Thread interrupted while waiting\nfor job queue to be disabled\", e);\n}\n}\n}\n}).whenComplete((result, throwable) -> {\nif (throwable != null) {\nthrow new RuntimeException(\"Error while waiting for job queue to be\ndisabled\", throwable);\n}\n});\n}\npublic CompletableFuture getJobQueueARN(String jobQueueName) {\n// Describe the job queue asynchronously\nCompletableFuture describeJobQueuesFuture =\nbatchClient.describeJobQueues(\nDescribeJobQueuesRequest.builder()\n.jobQueues(jobQueueName)\n.build()\n);\n// Handle the asynchronous response and return the Job Queue ARN in the\nCompletableFuture\nCompletableFuture jobQueueArnFuture = new CompletableFuture<>();\ndescribeJobQueuesFuture.whenComplete((response, error) -> {\nif (error != null) {\nif (error instanceof BatchException) {\nlogger.info(\"Batch error: \" + ((BatchException)\nerror).awsErrorDetails().errorMessage());\n} else {\nlogger.info(\"Error describing job queue: \" +\nerror.getMessage());\nScenarios 655\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\njobQueueArnFuture.completeExceptionally(new RuntimeException(\"Failed\nto retrieve Job Queue ARN\", error));\n} else {\nif (response.jobQueues().isEmpty()) {\njobQueueArnFuture.completeExceptionally(new\nRuntimeException(\"Job queue not found: \" + jobQueueName));\n} else {\n// Assuming only one job queue is returned for the given name\nString jobQueueArn = response.jobQueues().get(0).jobQueueArn();\njobQueueArnFuture.complete(jobQueueArn);\n}\n}\n});\nreturn jobQueueArnFuture;\n}\nprivate static String getComputeEnvironmentName(String computeEnvironment) {\nString[] parts = computeEnvironment.split(\"/\");\nif (parts.length == 2) {\nreturn parts[1];\n}\nreturn null;\n}\npublic CompletableFuture getAccountId() {\nStsAsyncClient stsAsyncClient = StsAsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\nreturn stsAsyncClient.getCallerIdentity()\n.thenApply(GetCallerIdentityResponse::account);\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1013058, "end_char_idx": 1017086, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "de04f443-e141-406b-97cf-552bbccc19d2": {"__data__": {"id_": "de04f443-e141-406b-97cf-552bbccc19d2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "059d64f8-83d7-4b00-8124-3e8dccc2bd94", "node_type": "1", "metadata": {}, "hash": "d868414a5e25798c6c6fe78cd356e7a805a10369f152c6dabde476b24cf68507", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8fa2618c-f204-45dd-a785-c617658af805", "node_type": "1", "metadata": {}, "hash": "8066ccd18e31564f8106ed070dd0c4623e649990fbacdfd38d04a3d25a399fc2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 CreateComputeEnvironment\n\u2022 CreateJobQueue\nScenarios 656\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 DeleteComputeEnvironment\n\u2022 DeleteJobQueue\n\u2022 DeregisterJobDefinition\n\u2022 DescribeComputeEnvironments\n\u2022 DescribeJobQueues\n\u2022 DescribeJobs\n\u2022 ListJobsPaginator\n\u2022 RegisterJobDefinition\n\u2022 SubmitJob\n\u2022 UpdateComputeEnvironment\n\u2022 UpdateJobQueue\nAmazon Bedrock examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon Bedrock.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nActions\nGetFoundationModel\nThe following code example shows how to use GetFoundationModel.\nAmazon Bedrock 657\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nGet details about a foundation model using the synchronous Amazon Bedrock client.\n/**\n* Get details about an Amazon Bedrock foundation model.\n*\n* @param bedrockClient The service client for accessing Amazon Bedrock.\n* @param modelIdentifier The model identifier.\n* @return An object containing the foundation model's details.\n*/\npublic static FoundationModelDetails getFoundationModel(BedrockClient\nbedrockClient, String modelIdentifier) {\ntry {\nGetFoundationModelResponse response = bedrockClient.getFoundationModel(\nr -> r.modelIdentifier(modelIdentifier)\n);\nFoundationModelDetails model = response.modelDetails();\nSystem.out.println(\" Model ID: \" + model.modelId());\nSystem.out.println(\" Model ARN: \" +\nmodel.modelArn());\nSystem.out.println(\" Model Name: \" +\nmodel.modelName());\nSystem.out.println(\" Provider Name: \" +\nmodel.providerName());\nSystem.out.println(\" Lifecycle status: \" +\nmodel.modelLifecycle().statusAsString());\nSystem.out.println(\" Input modalities: \" +\nmodel.inputModalities());\nSystem.out.println(\" Output modalities: \" +\nmodel.outputModalities());\nSystem.out.println(\" Supported customizations: \" +\nmodel.customizationsSupported());\nSystem.out.println(\" Supported inference types: \" +\nmodel.inferenceTypesSupported());\nActions 658\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\" Response streaming supported: \" +\nmodel.responseStreamingSupported());\nreturn model;\n} catch (ValidationException e) {\nthrow new IllegalArgumentException(e.getMessage());\n} catch (SdkException e) {\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n}\n}\nGet details about a foundation model using the asynchronous Amazon Bedrock client.\n/**\n* Get details about an Amazon Bedrock foundation model.\n*\n* @param bedrockClient The async service client for accessing Amazon Bedrock.\n* @param modelIdentifier The model identifier.\n* @return An object containing the foundation model's details.\n*/\npublic static FoundationModelDetails getFoundationModel(BedrockAsyncClient\nbedrockClient, String modelIdentifier) {\ntry {\nCompletableFuture future =\nbedrockClient.getFoundationModel(\nr -> r.modelIdentifier(modelIdentifier)\n);\nFoundationModelDetails model = future.get().modelDetails();\nSystem.out.println(\" Model ID: \" + model.modelId());\nSystem.out.println(\" Model ARN: \" +\nmodel.modelArn());\nSystem.out.println(\" Model Name: \" +\nmodel.modelName());\nSystem.out.println(\" Provider Name: \" +\nmodel.providerName());\nSystem.out.println(\" Lifecycle status: \" +\nmodel.modelLifecycle().statusAsString());\nActions 659\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\" Input modalities: \" +\nmodel.inputModalities());\nSystem.out.println(\" Output modalities: \" +\nmodel.outputModalities());\nSystem.out.println(\" Supported customizations: \" +\nmodel.customizationsSupported());\nSystem.out.println(\" Supported inference types: \" +\nmodel.inferenceTypesSupported());\nSystem.out.println(\" Response streaming supported: \" +\nmodel.responseStreamingSupported());\nreturn model;\n} catch (ExecutionException e) {\nif (e.getMessage().contains(\"ValidationException\")) {\nthrow new IllegalArgumentException(e.getMessage());\n} else {\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n}\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n}\n}\n\u2022 For API details, see GetFoundationModel in AWS SDK for Java 2.x API Reference.\nListFoundationModels\nThe following code example shows how to use ListFoundationModels.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1017087, "end_char_idx": 1021895, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8fa2618c-f204-45dd-a785-c617658af805": {"__data__": {"id_": "8fa2618c-f204-45dd-a785-c617658af805", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "de04f443-e141-406b-97cf-552bbccc19d2", "node_type": "1", "metadata": {}, "hash": "0fe83dea90a98dc54590cce2fd7300b52b6090f1c66c516e3c121a2cf7f7b30c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "665a0869-0eea-4bb9-a8f5-0aa4cc126f8b", "node_type": "1", "metadata": {}, "hash": "17f44cdb8906359ce2d9a69f01208ea592765e7ef5aa1c49102aa6e87774fdab", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ListFoundationModels\nThe following code example shows how to use ListFoundationModels.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 660\nAWS SDK for Java 2.x Developer Guide for version 2.x\nList the available Amazon Bedrock foundation models using the synchronous Amazon Bedrock\nclient.\n/**\n* Lists Amazon Bedrock foundation models that you can use.\n* You can filter the results with the request parameters.\n*\n* @param bedrockClient The service client for accessing Amazon Bedrock.\n* @return A list of objects containing the foundation models' details\n*/\npublic static List listFoundationModels(BedrockClient\nbedrockClient) {\ntry {\nListFoundationModelsResponse response =\nbedrockClient.listFoundationModels(r -> {});\nList models = response.modelSummaries();\nif (models.isEmpty()) {\nSystem.out.println(\"No available foundation models in \" +\nregion.toString());\n} else {\nfor (FoundationModelSummary model : models) {\nSystem.out.println(\"Model ID: \" + model.modelId());\nSystem.out.println(\"Provider: \" + model.providerName());\nSystem.out.println(\"Name: \" + model.modelName());\nSystem.out.println();\n}\n}\nreturn models;\n} catch (SdkClientException e) {\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n}\n}\nList the available Amazon Bedrock foundation models using the asynchronous Amazon Bedrock\nclient.\nActions 661\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Lists Amazon Bedrock foundation models that you can use.\n* You can filter the results with the request parameters.\n*\n* @param bedrockClient The async service client for accessing Amazon Bedrock.\n* @return A list of objects containing the foundation models' details\n*/\npublic static List\nlistFoundationModels(BedrockAsyncClient bedrockClient) {\ntry {\nCompletableFuture future =\nbedrockClient.listFoundationModels(r -> {});\nList models = future.get().modelSummaries();\nif (models.isEmpty()) {\nSystem.out.println(\"No available foundation models in \" +\nregion.toString());\n} else {\nfor (FoundationModelSummary model : models) {\nSystem.out.println(\"Model ID: \" + model.modelId());\nSystem.out.println(\"Provider: \" + model.providerName());\nSystem.out.println(\"Name: \" + model.modelName());\nSystem.out.println();\n}\n}\nreturn models;\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n} catch (ExecutionException e) {\nSystem.err.println(e.getMessage());\nthrow new RuntimeException(e);\n}\n}\n\u2022 For API details, see ListFoundationModels in AWS SDK for Java 2.x API Reference.\nActions 662\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAmazon Bedrock Runtime examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon Bedrock Runtime.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Scenarios\n\u2022 AI21 Labs Jurassic-2\n\u2022 Amazon Titan Image Generator\n\u2022 Amazon Titan Text\n\u2022 Amazon Titan Text Embeddings\n\u2022 Anthropic Claude\n\u2022 Cohere Command\n\u2022 Meta Llama\n\u2022 Mistral AI\n\u2022 Stable Diffusion\nScenarios\nCreate a playground application to interact with Amazon Bedrock foundation models\nThe following code example shows how to create playgrounds to interact with Amazon Bedrock\nfoundation models through different modalities.\nSDK for Java 2.x\nThe Java Foundation Model (FM) Playground is a Spring Boot sample application that showcases\nhow to use Amazon Bedrock with Java. This example shows how Java developers can use\nAmazon Bedrock to build generative AI-enabled applications. You can test and interact with\nAmazon Bedrock foundation models by using the following three playgrounds:\n\u2022 A text playground.\nAmazon Bedrock Runtime 663\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 A chat playground.\n\u2022 An image playground.\nThe example also lists and displays the foundation models you have access to, along with their\ncharacteristics. For source code and deployment instructions, see the project in GitHub.\nServices used in this example\n\u2022 Amazon Bedrock Runtime\nAI21 Labs Jurassic-2\nConverse\nThe following code example shows how to send a text message to AI21 Labs Jurassic-2, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1021763, "end_char_idx": 1026468, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "665a0869-0eea-4bb9-a8f5-0aa4cc126f8b": {"__data__": {"id_": "665a0869-0eea-4bb9-a8f5-0aa4cc126f8b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8fa2618c-f204-45dd-a785-c617658af805", "node_type": "1", "metadata": {}, "hash": "8066ccd18e31564f8106ed070dd0c4623e649990fbacdfd38d04a3d25a399fc2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a7fee9b2-020e-49dc-bc00-128f305a3e69", "node_type": "1", "metadata": {}, "hash": "b3c2dc7e30b0da3c4f044440eecab4bbddf59fa538618ae9995063098cc8d483", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This example shows how Java developers can use\nAmazon Bedrock to build generative AI-enabled applications. You can test and interact with\nAmazon Bedrock foundation models by using the following three playgrounds:\n\u2022 A text playground.\nAmazon Bedrock Runtime 663\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 A chat playground.\n\u2022 An image playground.\nThe example also lists and displays the foundation models you have access to, along with their\ncharacteristics. For source code and deployment instructions, see the project in GitHub.\nServices used in this example\n\u2022 Amazon Bedrock Runtime\nAI21 Labs Jurassic-2\nConverse\nThe following code example shows how to send a text message to AI21 Labs Jurassic-2, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to AI21 Labs Jurassic-2, using Bedrock's Converse API.\n// Use the Converse API to send a text message to AI21 Labs Jurassic-2.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\nAI21 Labs Jurassic-2 664\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Jurassic-2 Mid.\nvar modelId = \"ai21.j2-mid-v1\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)));\n// Retrieve the generated text from Bedrock's response object.\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nAI21 Labs Jurassic-2 665\nAWS SDK for Java 2.x Developer Guide for version 2.x\nconverse();\n}\n}\nSend a text message to AI21 Labs Jurassic-2, using Bedrock's Converse API with the async Java\nclient.\n// Use the Converse API to send a text message to AI21 Labs Jurassic-2\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Jurassic-2 Mid.\nvar modelId = \"ai21.j2-mid-v1\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.", "mimetype": "text/plain", "start_char_idx": 1025681, "end_char_idx": 1030089, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a7fee9b2-020e-49dc-bc00-128f305a3e69": {"__data__": {"id_": "a7fee9b2-020e-49dc-bc00-128f305a3e69", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "665a0869-0eea-4bb9-a8f5-0aa4cc126f8b", "node_type": "1", "metadata": {}, "hash": "17f44cdb8906359ce2d9a69f01208ea592765e7ef5aa1c49102aa6e87774fdab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9974e4aa-3591-4bb0-ab46-b2459a666951", "node_type": "1", "metadata": {}, "hash": "aad10b13556d2b91dc954edcc45290f05e4d3af4830a7f8ac9bf0a8d94ad66ff", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Jurassic-2 Mid.\nvar modelId = \"ai21.j2-mid-v1\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\nAI21 Labs Jurassic-2 666\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\ntry {\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\nAI21 Labs Jurassic-2 667\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nInvokeModel\nThe following code example shows how to send a text message to AI21 Labs Jurassic-2, using the\nInvoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to AI21 Labs Jurassic-2.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\nAI21 Labs Jurassic-2 668\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Set the model ID, e.g., Jurassic-2 Mid.\nvar modelId = \"ai21.j2-mid-v1\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\njurassic2.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/completions/0/data/\ntext\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'.", "mimetype": "text/plain", "start_char_idx": 1029632, "end_char_idx": 1033867, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9974e4aa-3591-4bb0-ab46-b2459a666951": {"__data__": {"id_": "9974e4aa-3591-4bb0-ab46-b2459a666951", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a7fee9b2-020e-49dc-bc00-128f305a3e69", "node_type": "1", "metadata": {}, "hash": "b3c2dc7e30b0da3c4f044440eecab4bbddf59fa538618ae9995063098cc8d483", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "29138787-7d9e-4289-a03a-3a67a08db26e", "node_type": "1", "metadata": {}, "hash": "a93349de3bfc50e3f3d49f1d740d0010a65e663228f8e44259b22638e0d99d65", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/completions/0/data/\ntext\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\nAI21 Labs Jurassic-2 669\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nAmazon Titan Image Generator\nInvokeModel\nThe following code example shows how to invoke Amazon Titan Image on Amazon Bedrock to\ngenerate an image.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nCreate an image with the Amazon Titan Image Generator.\n// Create an image with the Amazon Titan Image Generator.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport static com.example.bedrockruntime.libs.ImageTools.displayImage;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\nAmazon Titan Image Generator 670\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Image G1.\nvar modelId = \"amazon.titan-image-generator-v1\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ntitan-image.html\nvar nativeRequestTemplate = \"\"\"\n{\n\"taskType\": \"TEXT_IMAGE\",\n\"textToImageParams\": { \"text\": \"{{prompt}}\" },\n\"imageGenerationConfig\": { \"seed\": {{seed}} }\n}\"\"\";\n// Define the prompt for the image generation.\nvar prompt = \"A stylized picture of a cute old steampunk robot\";\n// Get a random 31-bit seed for the image generation (max. 2,147,483,647).\nvar seed = new BigInteger(31, new SecureRandom());\n// Embed the prompt and seed in the model's native request payload.\nvar nativeRequest = nativeRequestTemplate\n.replace(\"{{prompt}}\", prompt)\n.replace(\"{{seed}}\", seed.toString());\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated image data from the model's response.\nAmazon Titan Image Generator 671\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar base64ImageData = new JSONPointer(\"/\nimages/0\").queryFrom(responseBody).toString();\nreturn base64ImageData;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nSystem.out.println(\"Generating image. This may take a few seconds...\");\nString base64ImageData = invokeModel();\ndisplayImage(base64ImageData);\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nAmazon Titan Text\nConverse\nThe following code example shows how to send a text message to Amazon Titan Text, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1033112, "end_char_idx": 1037528, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "29138787-7d9e-4289-a03a-3a67a08db26e": {"__data__": {"id_": "29138787-7d9e-4289-a03a-3a67a08db26e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9974e4aa-3591-4bb0-ab46-b2459a666951", "node_type": "1", "metadata": {}, "hash": "aad10b13556d2b91dc954edcc45290f05e4d3af4830a7f8ac9bf0a8d94ad66ff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1240a006-3da2-4c1c-b75c-99b5df422140", "node_type": "1", "metadata": {}, "hash": "e90a3383f7b6af205d1ca35a8347bdacd64d85508126ecbdc2a0e986463adaca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Amazon Titan Image Generator 671\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar base64ImageData = new JSONPointer(\"/\nimages/0\").queryFrom(responseBody).toString();\nreturn base64ImageData;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nSystem.out.println(\"Generating image. This may take a few seconds...\");\nString base64ImageData = invokeModel();\ndisplayImage(base64ImageData);\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nAmazon Titan Text\nConverse\nThe following code example shows how to send a text message to Amazon Titan Text, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Amazon Titan Text, using Bedrock's Converse API.\n// Use the Converse API to send a text message to Amazon Titan Text.\nAmazon Titan Text 672\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)));\nAmazon Titan Text 673\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Retrieve the generated text from Bedrock's response object.\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverse();\n}\n}\nSend a text message to Amazon Titan Text, using Bedrock's Converse API with the async Java\nclient.\n// Use the Converse API to send a text message to Amazon Titan Text\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\nAmazon Titan Text 674\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.", "mimetype": "text/plain", "start_char_idx": 1036732, "end_char_idx": 1041246, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1240a006-3da2-4c1c-b75c-99b5df422140": {"__data__": {"id_": "1240a006-3da2-4c1c-b75c-99b5df422140", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "29138787-7d9e-4289-a03a-3a67a08db26e", "node_type": "1", "metadata": {}, "hash": "a93349de3bfc50e3f3d49f1d740d0010a65e663228f8e44259b22638e0d99d65", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9f7bdf7e-fed2-4a0b-8df5-4b22f791383f", "node_type": "1", "metadata": {}, "hash": "aa31657bbd0727ee39a1d117c13ddbbce36b460f75817d440bb374c120944094", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Amazon Titan Text 674\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\nAmazon Titan Text 675\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Amazon Titan Text, using\nBedrock's Converse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Amazon Titan Text, using Bedrock's Converse API and process the\nresponse stream in real-time.\n// Use the Converse API to send a text message to Amazon Titan Text\n// and print the response stream.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nAmazon Titan Text 676\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseStream {\npublic static void main(String[] args) {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\nAmazon Titan Text 677\nAWS SDK for Java 2.x Developer Guide for version 2.x\n).build();\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.", "mimetype": "text/plain", "start_char_idx": 1040694, "end_char_idx": 1045081, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9f7bdf7e-fed2-4a0b-8df5-4b22f791383f": {"__data__": {"id_": "9f7bdf7e-fed2-4a0b-8df5-4b22f791383f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1240a006-3da2-4c1c-b75c-99b5df422140", "node_type": "1", "metadata": {}, "hash": "e90a3383f7b6af205d1ca35a8347bdacd64d85508126ecbdc2a0e986463adaca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "350cd722-3cf2-4bac-bf75-42d21d49c70d", "node_type": "1", "metadata": {}, "hash": "c91bee10cbb77885064cefb4762569a1ef36898c7bdb9263c0c1d0afe7ef5591", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\nAmazon Titan Text 677\nAWS SDK for Java 2.x Developer Guide for version 2.x\n).build();\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.\nclient.converseStream(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)\n), responseStreamHandler).get();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\n}\n}\n}\n\u2022 For API details, see ConverseStream in AWS SDK for Java 2.x API Reference.\nInvokeModel\nThe following code example shows how to send a text message to Amazon Titan Text, using the\nInvoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Amazon Titan Text.\nimport org.json.JSONObject;\nAmazon Titan Text 678\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ntitan-text.html\nvar nativeRequestTemplate = \"{ \\\"inputText\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\nAmazon Titan Text 679\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/results/0/\noutputText\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream\nThe following code example shows how to send a text message to Amazon Titan Text models,\nusing the Invoke Model API, and print the response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\n// Use the native inference API to send a text message to Amazon Titan Text\n// and print the response stream.", "mimetype": "text/plain", "start_char_idx": 1044308, "end_char_idx": 1048656, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "350cd722-3cf2-4bac-bf75-42d21d49c70d": {"__data__": {"id_": "350cd722-3cf2-4bac-bf75-42d21d49c70d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9f7bdf7e-fed2-4a0b-8df5-4b22f791383f", "node_type": "1", "metadata": {}, "hash": "aa31657bbd0727ee39a1d117c13ddbbce36b460f75817d440bb374c120944094", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f4525ee1-312b-4f8c-b85e-f2c39a05e12b", "node_type": "1", "metadata": {}, "hash": "94dfcf17f2f690a94a2402c8e66cc004fdcc684fc60a74383cfd4f78fce5e702", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream\nThe following code example shows how to send a text message to Amazon Titan Text models,\nusing the Invoke Model API, and print the response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\n// Use the native inference API to send a text message to Amazon Titan Text\n// and print the response stream.\nimport org.json.JSONObject;\nAmazon Titan Text 680\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() throws ExecutionException,\nInterruptedException {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Premier.\nvar modelId = \"amazon.titan-text-premier-v1:0\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ntitan-text.html\nvar nativeRequestTemplate = \"{ \\\"inputText\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\nAmazon Titan Text 681\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\n// Extract and print the text from the model's native response.\nvar response = new JSONObject(chunk.bytes().asUtf8String());\nvar text = new JSONPointer(\"/outputText\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\n}).build()).build();\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\nAmazon Titan Text 682\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see InvokeModelWithResponseStream in AWS SDK for Java 2.x API Reference.\nAmazon Titan Text Embeddings\nInvokeModel\nThe following code example shows how to:\n\u2022 Get started creating your first embedding.\n\u2022 Create embeddings configuring the number of dimensions and normalization (V2 only).\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nCreate your first embedding with Titan Text Embeddings V2.\n// Generate and print an embedding with Amazon Titan Text Embeddings.", "mimetype": "text/plain", "start_char_idx": 1047926, "end_char_idx": 1052633, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f4525ee1-312b-4f8c-b85e-f2c39a05e12b": {"__data__": {"id_": "f4525ee1-312b-4f8c-b85e-f2c39a05e12b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "350cd722-3cf2-4bac-bf75-42d21d49c70d", "node_type": "1", "metadata": {}, "hash": "c91bee10cbb77885064cefb4762569a1ef36898c7bdb9263c0c1d0afe7ef5591", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e912467-1ab7-427e-b67d-4ca3486dbf9b", "node_type": "1", "metadata": {}, "hash": "0f719d637c85acdc401ad37e92dc6f425e2121069ac1cfff41bfb48eb3ab51df", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Amazon Titan Text Embeddings\nInvokeModel\nThe following code example shows how to:\n\u2022 Get started creating your first embedding.\n\u2022 Create embeddings configuring the number of dimensions and normalization (V2 only).\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nCreate your first embedding with Titan Text Embeddings V2.\n// Generate and print an embedding with Amazon Titan Text Embeddings.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nAmazon Titan Text Embeddings 683\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Titan Text Embeddings V2.\nvar modelId = \"amazon.titan-embed-text-v2:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ntitan-embed-text.html\nvar nativeRequestTemplate = \"{ \\\"inputText\\\": \\\"{{inputText}}\\\" }\";\n// The text to convert into an embedding.\nvar inputText = \"Please recommend books with a theme similar to the movie\n'Inception'.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{inputText}}\",\ninputText);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/\nembedding\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\nAmazon Titan Text Embeddings 684\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\nInvoke Titan Text Embeddings V2 configuring the number of dimensions and normalization.\n/**\n* Invoke Amazon Titan Text Embeddings V2 with additional inference parameters.\n*\n* @param inputText - The text to convert to an embedding.\n* @param dimensions - The number of dimensions the output embeddings should\nhave.\n* Values accepted by the model: 256, 512, 1024.\n* @param normalize - A flag indicating whether or not to normalize the output\nembeddings.\n* @return The {@link JSONObject} representing the model's response.\n*/\npublic static JSONObject invokeModel(String inputText, int dimensions, boolean\nnormalize) {\n// Create a Bedrock Runtime client in the AWS Region of your choice.\nvar client = BedrockRuntimeClient.builder()\n.region(Region.US_WEST_2)\n.build();\n// Set the model ID, e.g., Titan Embed Text v2.0.\nvar modelId = \"amazon.titan-embed-text-v2:0\";\n// Create the request for the model.\nvar nativeRequest = \"\"\"\n{\n\"inputText\": \"%s\",\n\"dimensions\": %d,\n\"normalize\": %b\n}\n\"\"\".formatted(inputText, dimensions, normalize);\nAmazon Titan Text Embeddings 685\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Encode and send the request.\nvar response = client.invokeModel(request -> {\nrequest.body(SdkBytes.fromUtf8String(nativeRequest));\nrequest.modelId(modelId);\n});\n// Decode the model's response.\nvar modelResponse = new JSONObject(response.body().asUtf8String());\n// Extract and print the generated embedding and the input text token count.\nvar embedding = modelResponse.getJSONArray(\"embedding\");\nvar inputTokenCount = modelResponse.getBigInteger(\"inputTextTokenCount\");\nSystem.out.println(\"Embedding: \" + embedding);\nSystem.out.println(\"\\nInput token count: \" + inputTokenCount);\n// Return the model's native response.\nreturn modelResponse;\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1052151, "end_char_idx": 1056689, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5e912467-1ab7-427e-b67d-4ca3486dbf9b": {"__data__": {"id_": "5e912467-1ab7-427e-b67d-4ca3486dbf9b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f4525ee1-312b-4f8c-b85e-f2c39a05e12b", "node_type": "1", "metadata": {}, "hash": "94dfcf17f2f690a94a2402c8e66cc004fdcc684fc60a74383cfd4f78fce5e702", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "853e229f-0a1a-4b8e-b2d4-b0eac7d10747", "node_type": "1", "metadata": {}, "hash": "ac74cc527a76340a591a9107d9ca1bc9d3ba5dcf38ff3b2e338aacf3d4557d7b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var response = client.invokeModel(request -> {\nrequest.body(SdkBytes.fromUtf8String(nativeRequest));\nrequest.modelId(modelId);\n});\n// Decode the model's response.\nvar modelResponse = new JSONObject(response.body().asUtf8String());\n// Extract and print the generated embedding and the input text token count.\nvar embedding = modelResponse.getJSONArray(\"embedding\");\nvar inputTokenCount = modelResponse.getBigInteger(\"inputTextTokenCount\");\nSystem.out.println(\"Embedding: \" + embedding);\nSystem.out.println(\"\\nInput token count: \" + inputTokenCount);\n// Return the model's native response.\nreturn modelResponse;\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nAnthropic Claude\nConverse\nThe following code example shows how to send a text message to Anthropic Claude, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Anthropic Claude, using Bedrock's Converse API.\n// Use the Converse API to send a text message to Anthropic Claude.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nAnthropic Claude 686\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)));\n// Retrieve the generated text from Bedrock's response object.\nAnthropic Claude 687\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverse();\n}\n}\nSend a text message to Anthropic Claude, using Bedrock's Converse API with the async Java\nclient.\n// Use the Converse API to send a text message to Anthropic Claude\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\nAnthropic Claude 688\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.", "mimetype": "text/plain", "start_char_idx": 1056004, "end_char_idx": 1060513, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "853e229f-0a1a-4b8e-b2d4-b0eac7d10747": {"__data__": {"id_": "853e229f-0a1a-4b8e-b2d4-b0eac7d10747", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e912467-1ab7-427e-b67d-4ca3486dbf9b", "node_type": "1", "metadata": {}, "hash": "0f719d637c85acdc401ad37e92dc6f425e2121069ac1cfff41bfb48eb3ab51df", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b0485739-31d0-4f75-adf3-ac80d3c6a481", "node_type": "1", "metadata": {}, "hash": "dc882e866158f625d0f1ef171e31201dff3e180671456c2915cc7c0c8f4a4443", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\nAnthropic Claude 688\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\ntry {\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nAnthropic Claude 689\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Anthropic Claude, using\nBedrock's Converse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Anthropic Claude, using Bedrock's Converse API and process the\nresponse stream in real-time.\n// Use the Converse API to send a text message to Anthropic Claude\n// and print the response stream.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nAnthropic Claude 690\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseStream {\npublic static void main(String[] args) {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\n).build();\ntry {\nAnthropic Claude 691\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Send the message with a basic inference configuration and attach the\nhandler.", "mimetype": "text/plain", "start_char_idx": 1060036, "end_char_idx": 1064424, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b0485739-31d0-4f75-adf3-ac80d3c6a481": {"__data__": {"id_": "b0485739-31d0-4f75-adf3-ac80d3c6a481", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "853e229f-0a1a-4b8e-b2d4-b0eac7d10747", "node_type": "1", "metadata": {}, "hash": "ac74cc527a76340a591a9107d9ca1bc9d3ba5dcf38ff3b2e338aacf3d4557d7b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "87f2c27d-d610-4d5c-be6f-20717d7eb9aa", "node_type": "1", "metadata": {}, "hash": "6e91d7d398fafb74bedd77a11870a49772f00742d65d71bcd3d785b524f5afd2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\n).build();\ntry {\nAnthropic Claude 691\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Send the message with a basic inference configuration and attach the\nhandler.\nclient.converseStream(request -> request.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)\n), responseStreamHandler).get();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\n}\n}\n}\n\u2022 For API details, see ConverseStream in AWS SDK for Java 2.x API Reference.\nInvokeModel\nThe following code example shows how to send a text message to Anthropic Claude, using the\nInvoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Anthropic Claude.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nAnthropic Claude 692\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nanthropic-claude-messages.html\nvar nativeRequestTemplate = \"\"\"\n{\n\"anthropic_version\": \"bedrock-2023-05-31\",\n\"max_tokens\": 512,\n\"temperature\": 0.5,\n\"messages\": [{\n\"role\": \"user\",\n\"content\": \"{{prompt}}\"\n}]\n}\"\"\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\nAnthropic Claude 693\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/content/0/\ntext\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream\nThe following code example shows how to send a text message to Anthropic Claude models, using\nthe Invoke Model API, and print the response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.", "mimetype": "text/plain", "start_char_idx": 1063652, "end_char_idx": 1068011, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "87f2c27d-d610-4d5c-be6f-20717d7eb9aa": {"__data__": {"id_": "87f2c27d-d610-4d5c-be6f-20717d7eb9aa", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b0485739-31d0-4f75-adf3-ac80d3c6a481", "node_type": "1", "metadata": {}, "hash": "dc882e866158f625d0f1ef171e31201dff3e180671456c2915cc7c0c8f4a4443", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ad4def69-3dab-40f4-b11a-311e5f6ac54e", "node_type": "1", "metadata": {}, "hash": "ae670ff7ef7d5ef5742eebe119a799fadd4f0fb982a9ecd7f72e723e7f0a4a13", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var text = new JSONPointer(\"/content/0/\ntext\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream\nThe following code example shows how to send a text message to Anthropic Claude models, using\nthe Invoke Model API, and print the response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\nAnthropic Claude 694\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the native inference API to send a text message to Anthropic Claude\n// and print the response stream.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.Objects;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() throws ExecutionException,\nInterruptedException {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Claude 3 Haiku.\nvar modelId = \"anthropic.claude-3-haiku-20240307-v1:0\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nanthropic-claude-messages.html\nvar nativeRequestTemplate = \"\"\"\n{\nAnthropic Claude 695\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"anthropic_version\": \"bedrock-2023-05-31\",\n\"max_tokens\": 512,\n\"temperature\": 0.5,\n\"messages\": [{\n\"role\": \"user\",\n\"content\": \"{{prompt}}\"\n}]\n}\"\"\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\nvar response = new JSONObject(chunk.bytes().asUtf8String());\n// Extract and print the text from the content blocks.\nif (Objects.equals(response.getString(\"type\"),\n\"content_block_delta\")) {\nvar text = new JSONPointer(\"/delta/\ntext\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\n}\n}).build()).build();\nAnthropic Claude 696\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModelWithResponseStream in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1067192, "end_char_idx": 1071838, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ad4def69-3dab-40f4-b11a-311e5f6ac54e": {"__data__": {"id_": "ad4def69-3dab-40f4-b11a-311e5f6ac54e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "87f2c27d-d610-4d5c-be6f-20717d7eb9aa", "node_type": "1", "metadata": {}, "hash": "6e91d7d398fafb74bedd77a11870a49772f00742d65d71bcd3d785b524f5afd2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d082242a-df8a-4e5f-9a6f-044c682247e9", "node_type": "1", "metadata": {}, "hash": "402133ce28a1f0eda752461c4fbdd8babef936509ff5a14422b962ff64b5fcdc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "completeResponseTextBuffer.append(text);\n}\n}).build()).build();\nAnthropic Claude 696\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModelWithResponseStream in AWS SDK for Java 2.x API Reference.\nCohere Command\nConverse\nThe following code example shows how to send a text message to Cohere Command, using\nBedrock's Converse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Cohere Command, using Bedrock's Converse API.\n// Use the Converse API to send a text message to Cohere Command.\nCohere Command 697\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)));\nCohere Command 698\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Retrieve the generated text from Bedrock's response object.\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverse();\n}\n}\nSend a text message to Cohere Command, using Bedrock's Converse API with the async Java\nclient.\n// Use the Converse API to send a text message to Cohere Command\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nCohere Command 699\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.", "mimetype": "text/plain", "start_char_idx": 1071076, "end_char_idx": 1075678, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d082242a-df8a-4e5f-9a6f-044c682247e9": {"__data__": {"id_": "d082242a-df8a-4e5f-9a6f-044c682247e9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ad4def69-3dab-40f4-b11a-311e5f6ac54e", "node_type": "1", "metadata": {}, "hash": "ae670ff7ef7d5ef5742eebe119a799fadd4f0fb982a9ecd7f72e723e7f0a4a13", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c0a0648-7ec8-48f8-809d-da65dfb4e917", "node_type": "1", "metadata": {}, "hash": "9f47395be07e9ae9fdc72888cb13626dcef43cc466b4087b2e012db0b9a9b2a3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nCohere Command 699\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\ntry {\nCohere Command 700\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Cohere Command, using\nBedrock's Converse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Cohere Command, using Bedrock's Converse API and process the\nresponse stream in real-time.\n// Use the Converse API to send a text message to Cohere Command\n// and print the response stream.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nCohere Command 701\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseStream {\npublic static void main(String[] args) {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\n).build();\nCohere Command 702\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.", "mimetype": "text/plain", "start_char_idx": 1075147, "end_char_idx": 1079477, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5c0a0648-7ec8-48f8-809d-da65dfb4e917": {"__data__": {"id_": "5c0a0648-7ec8-48f8-809d-da65dfb4e917", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d082242a-df8a-4e5f-9a6f-044c682247e9", "node_type": "1", "metadata": {}, "hash": "402133ce28a1f0eda752461c4fbdd8babef936509ff5a14422b962ff64b5fcdc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9f1c83bb-c862-4ba5-a41d-64a370c45fa9", "node_type": "1", "metadata": {}, "hash": "93873f0001a0ddeca086768ff8a44a8b009183a11409f6bb54c50faf4c9c7df5", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\n).build();\nCohere Command 702\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.\nclient.converseStream(request -> request.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)\n), responseStreamHandler).get();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\n}\n}\n}\n\u2022 For API details, see ConverseStream in AWS SDK for Java 2.x API Reference.\nInvokeModel: Command R and R+\nThe following code example shows how to send a text message to Cohere Command R and R+,\nusing the Invoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Cohere Command R.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nCohere Command 703\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class Command_R_InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ncohere-command-r-plus.html\nvar nativeRequestTemplate = \"{ \\\"message\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nCohere Command 704\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar text = new JSONPointer(\"/text\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModel: Command and Command Light\nThe following code example shows how to send a text message to Cohere Command, using the\nInvoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Cohere Command.", "mimetype": "text/plain", "start_char_idx": 1078707, "end_char_idx": 1082939, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9f1c83bb-c862-4ba5-a41d-64a370c45fa9": {"__data__": {"id_": "9f1c83bb-c862-4ba5-a41d-64a370c45fa9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5c0a0648-7ec8-48f8-809d-da65dfb4e917", "node_type": "1", "metadata": {}, "hash": "9f47395be07e9ae9fdc72888cb13626dcef43cc466b4087b2e012db0b9a9b2a3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1687d876-9b43-4608-b7de-fad565823d6f", "node_type": "1", "metadata": {}, "hash": "6dc6326b0de014b686bee06e3c7ec9c374b95a563e9a222a6e4486b38ebcd0db", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModel: Command and Command Light\nThe following code example shows how to send a text message to Cohere Command, using the\nInvoke Model API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Cohere Command.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nCohere Command 705\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class Command_InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command Light.\nvar modelId = \"cohere.command-light-text-v14\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ncohere-command.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/generations/0/\ntext\").queryFrom(responseBody).toString();\nCohere Command 706\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream: Command R and R+\nThe following code example shows how to send a text message to Cohere Command, using the\nInvoke Model API with a response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\n// Use the native inference API to send a text message to Cohere Command R\n// and print the response stream.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nCohere Command 707\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class Command_R_InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() throws ExecutionException,\nInterruptedException {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.", "mimetype": "text/plain", "start_char_idx": 1082322, "end_char_idx": 1086769, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1687d876-9b43-4608-b7de-fad565823d6f": {"__data__": {"id_": "1687d876-9b43-4608-b7de-fad565823d6f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9f1c83bb-c862-4ba5-a41d-64a370c45fa9", "node_type": "1", "metadata": {}, "hash": "93873f0001a0ddeca086768ff8a44a8b009183a11409f6bb54c50faf4c9c7df5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5212e8fa-0739-4d04-afef-dd6d2de7b63f", "node_type": "1", "metadata": {}, "hash": "3b9cfda41ea99167ece7a8ccdd68824b7d9785f66b98d06703bc95c684b0d211", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command R.\nvar modelId = \"cohere.command-r-v1:0\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ncohere-command-r-plus.html\nvar nativeRequestTemplate = \"{ \\\"message\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\nCohere Command 708\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\n// Extract and print the text from the model's native response.\nvar response = new JSONObject(chunk.bytes().asUtf8String());\nvar text = new JSONPointer(\"/text\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\n}).build()).build();\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nCohere Command 709\nAWS SDK for Java 2.x Developer Guide for version 2.x\nInvokeModelWithResponseStream: Command and Command Light\nThe following code example shows how to send a text message to Cohere Command, using the\nInvoke Model API with a response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\n// Use the native inference API to send a text message to Cohere Command\n// and print the response stream.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class Command_InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() throws ExecutionException,\nInterruptedException {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\nCohere Command 710\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command Light.\nvar modelId = \"cohere.command-light-text-v14\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ncohere-command.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.", "mimetype": "text/plain", "start_char_idx": 1086686, "end_char_idx": 1091471, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5212e8fa-0739-4d04-afef-dd6d2de7b63f": {"__data__": {"id_": "5212e8fa-0739-4d04-afef-dd6d2de7b63f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1687d876-9b43-4608-b7de-fad565823d6f", "node_type": "1", "metadata": {}, "hash": "6dc6326b0de014b686bee06e3c7ec9c374b95a563e9a222a6e4486b38ebcd0db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "103c322c-4989-4332-b737-6d45c4b85ec3", "node_type": "1", "metadata": {}, "hash": "9d561cdb78d94f508a87f6d491e2ff1d25c143531c659274f0b08e359a768dd0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\nCohere Command 710\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Command Light.\nvar modelId = \"cohere.command-light-text-v14\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ncohere-command.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{prompt}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in the model's native request payload.\nString nativeRequest = nativeRequestTemplate.replace(\"{{prompt}}\", prompt);\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\n// Extract and print the text from the model's native response.\nvar response = new JSONObject(chunk.bytes().asUtf8String());\nvar text = new JSONPointer(\"/generations/0/\ntext\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\n}).build()).build();\nCohere Command 711\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nMeta Llama\nConverse\nThe following code example shows how to send a text message to Meta Llama, using Bedrock's\nConverse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Meta Llama, using Bedrock's Converse API.\nMeta Llama 712\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the Converse API to send a text message to Meta Llama.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Llama 3 8b Instruct.\nvar modelId = \"meta.llama3-8b-instruct-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\nMeta Llama 713\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.temperature(0.5F)\n.topP(0.9F)));\n// Retrieve the generated text from Bedrock's response object.", "mimetype": "text/plain", "start_char_idx": 1090603, "end_char_idx": 1095223, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "103c322c-4989-4332-b737-6d45c4b85ec3": {"__data__": {"id_": "103c322c-4989-4332-b737-6d45c4b85ec3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5212e8fa-0739-4d04-afef-dd6d2de7b63f", "node_type": "1", "metadata": {}, "hash": "3b9cfda41ea99167ece7a8ccdd68824b7d9785f66b98d06703bc95c684b0d211", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ce4cbfdf-8e53-47a5-a2e1-eb3fa374ebed", "node_type": "1", "metadata": {}, "hash": "6ce4876363d2aa9266257923066939ef8805c31a8e26eb09cb4b574aba4de1db", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var modelId = \"meta.llama3-8b-instruct-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\nMeta Llama 713\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.temperature(0.5F)\n.topP(0.9F)));\n// Retrieve the generated text from Bedrock's response object.\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverse();\n}\n}\nSend a text message to Meta Llama, using Bedrock's Converse API with the async Java client.\n// Use the Converse API to send a text message to Meta Llama\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\nMeta Llama 714\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Llama 3 8b Instruct.\nvar modelId = \"meta.llama3-8b-instruct-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\nMeta Llama 715\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Meta Llama, using Bedrock's\nConverse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Meta Llama, using Bedrock's Converse API and process the response\nstream in real-time.\n// Use the Converse API to send a text message to Meta Llama\n// and print the response stream.", "mimetype": "text/plain", "start_char_idx": 1094527, "end_char_idx": 1098799, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ce4cbfdf-8e53-47a5-a2e1-eb3fa374ebed": {"__data__": {"id_": "ce4cbfdf-8e53-47a5-a2e1-eb3fa374ebed", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "103c322c-4989-4332-b737-6d45c4b85ec3", "node_type": "1", "metadata": {}, "hash": "9d561cdb78d94f508a87f6d491e2ff1d25c143531c659274f0b08e359a768dd0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1db28704-c9a6-46e5-89ec-81e37ba20044", "node_type": "1", "metadata": {}, "hash": "106f419056946b8c16f222d0ce3327fb3ef3ca1420afe17cf2e12376be59ab49", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ConverseStream\nThe following code example shows how to send a text message to Meta Llama, using Bedrock's\nConverse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Meta Llama, using Bedrock's Converse API and process the response\nstream in real-time.\n// Use the Converse API to send a text message to Meta Llama\n// and print the response stream.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nMeta Llama 716\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseStream {\npublic static void main(String[] args) {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Llama 3 8b Instruct.\nvar modelId = \"meta.llama3-8b-instruct-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\nMeta Llama 717\nAWS SDK for Java 2.x Developer Guide for version 2.x\n).build();\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.\nclient.converseStream(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)\n), responseStreamHandler).get();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\n}\n}\n}\n\u2022 For API details, see ConverseStream in AWS SDK for Java 2.x API Reference.\nInvokeModel: Llama 3\nThe following code example shows how to send a text message to Meta Llama 3, using the Invoke\nModel API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Meta Llama 3.\nimport org.json.JSONObject;\nMeta Llama 718\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class Llama3_InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_WEST_2)\n.build();\n// Set the model ID, e.g., Llama 3 70b Instruct.\nvar modelId = \"meta.llama3-70b-instruct-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmeta.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.", "mimetype": "text/plain", "start_char_idx": 1098289, "end_char_idx": 1102748, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1db28704-c9a6-46e5-89ec-81e37ba20044": {"__data__": {"id_": "1db28704-c9a6-46e5-89ec-81e37ba20044", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ce4cbfdf-8e53-47a5-a2e1-eb3fa374ebed", "node_type": "1", "metadata": {}, "hash": "6ce4876363d2aa9266257923066939ef8805c31a8e26eb09cb4b574aba4de1db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0f8c38c2-7420-43b1-a364-5ce207090d0e", "node_type": "1", "metadata": {}, "hash": "c4a3321d3b1949a5ba21fcf0c6e4101e8aaa6d03030a94049677b69cd7f99907", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_WEST_2)\n.build();\n// Set the model ID, e.g., Llama 3 70b Instruct.\nvar modelId = \"meta.llama3-70b-instruct-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmeta.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in Llama 3's instruction format.\nvar instruction = (\n\"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\\\n\" +\n\"{{prompt}} <|eot_id|>\\\\n\" +\n\"<|start_header_id|>assistant<|end_header_id|>\\\\n\"\n).replace(\"{{prompt}}\", prompt);\n// Embed the instruction in the the native request payload.\nvar nativeRequest = nativeRequestTemplate.replace(\"{{instruction}}\",\ninstruction);\ntry {\nMeta Llama 719\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/\ngeneration\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream: Llama 3\nThe following code example shows how to send a text message to Meta Llama 3, using the Invoke\nModel API, and print the response stream.\nMeta Llama 720\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\n// Use the native inference API to send a text message to Meta Llama 3\n// and print the response stream.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class Llama3_InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_WEST_2)\n.build();\n// Set the model ID, e.g., Llama 3 70b Instruct.\nvar modelId = \"meta.llama3-70b-instruct-v1:0\";\nMeta Llama 721\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmeta.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in Llama 3's instruction format.", "mimetype": "text/plain", "start_char_idx": 1102109, "end_char_idx": 1106324, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0f8c38c2-7420-43b1-a364-5ce207090d0e": {"__data__": {"id_": "0f8c38c2-7420-43b1-a364-5ce207090d0e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1db28704-c9a6-46e5-89ec-81e37ba20044", "node_type": "1", "metadata": {}, "hash": "106f419056946b8c16f222d0ce3327fb3ef3ca1420afe17cf2e12376be59ab49", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e0c50cd-08cc-414d-982b-b5b47b4d51c2", "node_type": "1", "metadata": {}, "hash": "4d498ac806ce88e5767fb69367fb5bd838432160e626e03462060865d9af31f4", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_WEST_2)\n.build();\n// Set the model ID, e.g., Llama 3 70b Instruct.\nvar modelId = \"meta.llama3-70b-instruct-v1:0\";\nMeta Llama 721\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmeta.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in Llama 3's instruction format.\nvar instruction = (\n\"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\\\n\" +\n\"{{prompt}} <|eot_id|>\\\\n\" +\n\"<|start_header_id|>assistant<|end_header_id|>\\\\n\"\n).replace(\"{{prompt}}\", prompt);\n// Embed the instruction in the the native request payload.\nvar nativeRequest = nativeRequestTemplate.replace(\"{{instruction}}\",\ninstruction);\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\n// Extract and print the text from the model's native response.\nvar response = new JSONObject(chunk.bytes().asUtf8String());\nvar text = new JSONPointer(\"/generation\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\nMeta Llama 722\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}).build()).build();\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModelWithResponseStream in AWS SDK for Java 2.x API Reference.\nMistral AI\nConverse\nThe following code example shows how to send a text message to Mistral, using Bedrock's\nConverse API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Mistral, using Bedrock's Converse API.\nMistral AI 723\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the Converse API to send a text message to Mistral.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\npublic class Converse {\npublic static String converse() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.", "mimetype": "text/plain", "start_char_idx": 1105548, "end_char_idx": 1110019, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5e0c50cd-08cc-414d-982b-b5b47b4d51c2": {"__data__": {"id_": "5e0c50cd-08cc-414d-982b-b5b47b4d51c2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0f8c38c2-7420-43b1-a364-5ce207090d0e", "node_type": "1", "metadata": {}, "hash": "c4a3321d3b1949a5ba21fcf0c6e4101e8aaa6d03030a94049677b69cd7f99907", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "335ba7e1-8f90-448d-9252-3f1e0469e6c3", "node_type": "1", "metadata": {}, "hash": "8545adc96a65e160820b0b1bb2e299dedba2d74cb6aa873842a45df2f2820a11", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\ntry {\n// Send the message with a basic inference configuration.\nConverseResponse response = client.converse(request -> request\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\nMistral AI 724\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.temperature(0.5F)\n.topP(0.9F)));\n// Retrieve the generated text from Bedrock's response object.\nvar responseText = response.output().message().content().get(0).text();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverse();\n}\n}\nSend a text message to Mistral, using Bedrock's Converse API with the async Java client.\n// Use the Converse API to send a text message to Mistral\n// with the async Java client.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseAsync {\npublic static String converseAsync() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\nMistral AI 725\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Send the message with a basic inference configuration.\nvar request = client.converse(params -> params\n.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F))\n);\n// Prepare a future object to handle the asynchronous response.\nCompletableFuture future = new CompletableFuture<>();\n// Handle the response or error using the future object.\nrequest.whenComplete((response, error) -> {\nif (error == null) {\n// Extract the generated text from Bedrock's response object.\nString responseText =\nresponse.output().message().content().get(0).text();\nfuture.complete(responseText);\n} else {\nfuture.completeExceptionally(error);\n}\n});\nMistral AI 726\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Wait for the future object to complete and retrieve the generated\ntext.\nString responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Mistral, using Bedrock's\nConverse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Mistral, using Bedrock's Converse API and process the response stream\nin real-time.", "mimetype": "text/plain", "start_char_idx": 1109371, "end_char_idx": 1113800, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "335ba7e1-8f90-448d-9252-3f1e0469e6c3": {"__data__": {"id_": "335ba7e1-8f90-448d-9252-3f1e0469e6c3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e0c50cd-08cc-414d-982b-b5b47b4d51c2", "node_type": "1", "metadata": {}, "hash": "4d498ac806ce88e5767fb69367fb5bd838432160e626e03462060865d9af31f4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aa1b2fe5-9889-4420-a499-94ee22cc3029", "node_type": "1", "metadata": {}, "hash": "13218e17142afbb69521884c2f3ab030d93589e18fa78e3abdc878dbd7c80f3f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "String responseText = future.get();\nSystem.out.println(responseText);\nreturn responseText;\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId, e.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nconverseAsync();\n}\n}\n\u2022 For API details, see Converse in AWS SDK for Java 2.x API Reference.\nConverseStream\nThe following code example shows how to send a text message to Mistral, using Bedrock's\nConverse API and process the response stream in real-time.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nSend a text message to Mistral, using Bedrock's Converse API and process the response stream\nin real-time.\n// Use the Converse API to send a text message to Mistral\n// and print the response stream.\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nMistral AI 727\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;\nimport software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;\nimport software.amazon.awssdk.services.bedrockruntime.model.Message;\nimport java.util.concurrent.ExecutionException;\npublic class ConverseStream {\npublic static void main(String[] args) {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// Create the input text and embed it in a message object with the user\nrole.\nvar inputText = \"Describe the purpose of a 'hello world' program in one\nline.\";\nvar message = Message.builder()\n.content(ContentBlock.fromText(inputText))\n.role(ConversationRole.USER)\n.build();\n// Create a handler to extract and print the response text in real-time.\nvar responseStreamHandler = ConverseStreamResponseHandler.builder()\n.subscriber(ConverseStreamResponseHandler.Visitor.builder()\n.onContentBlockDelta(chunk -> {\nString responseText = chunk.delta().text();\nSystem.out.print(responseText);\n}).build()\n).onError(err ->\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\nerr.getMessage())\nMistral AI 728\nAWS SDK for Java 2.x Developer Guide for version 2.x\n).build();\ntry {\n// Send the message with a basic inference configuration and attach the\nhandler.\nclient.converseStream(request -> request.modelId(modelId)\n.messages(message)\n.inferenceConfig(config -> config\n.maxTokens(512)\n.temperature(0.5F)\n.topP(0.9F)\n), responseStreamHandler).get();\n} catch (ExecutionException | InterruptedException e) {\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\n}\n}\n}\n\u2022 For API details, see ConverseStream in AWS SDK for Java 2.x API Reference.\nInvokeModel\nThe following code example shows how to send a text message to Mistral models, using the Invoke\nModel API.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Mistral.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nMistral AI 729\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.", "mimetype": "text/plain", "start_char_idx": 1113007, "end_char_idx": 1117442, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "aa1b2fe5-9889-4420-a499-94ee22cc3029": {"__data__": {"id_": "aa1b2fe5-9889-4420-a499-94ee22cc3029", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "335ba7e1-8f90-448d-9252-3f1e0469e6c3", "node_type": "1", "metadata": {}, "hash": "8545adc96a65e160820b0b1bb2e299dedba2d74cb6aa873842a45df2f2820a11", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8936efc7-eea6-4fcf-9309-15f097965a0b", "node_type": "1", "metadata": {}, "hash": "c03d7e6ee2a796dbbc86bc24f9b29eb83bc21f7147d0abee17641913af15ba36", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Use the Invoke Model API to send a text message.\n// Use the native inference API to send a text message to Mistral.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nMistral AI 729\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmistral-text-completion.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in Mistral's instruction format.\nvar instruction = \"[INST] {{prompt}} [/INST]\\\\n\".replace(\"{{prompt}}\",\nprompt);\n// Embed the instruction in the the native request payload.\nvar nativeRequest = nativeRequestTemplate.replace(\"{{instruction}}\",\ninstruction);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\nMistral AI 730\nAWS SDK for Java 2.x Developer Guide for version 2.x\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated text from the model's response.\nvar text = new JSONPointer(\"/outputs/0/\ntext\").queryFrom(responseBody).toString();\nSystem.out.println(text);\nreturn text;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\ninvokeModel();\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nInvokeModelWithResponseStream\nThe following code example shows how to send a text message to Mistral AI models, using the\nInvoke Model API, and print the response stream.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the Invoke Model API to send a text message and process the response stream in real-time.\nMistral AI 731\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the native inference API to send a text message to Mistral\n// and print the response stream.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;\nimport\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;\nimport java.util.concurrent.ExecutionException;\nimport static\nsoftware.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;\npublic class InvokeModelWithResponseStream {\npublic static String invokeModelWithResponseStream() throws ExecutionException,\nInterruptedException {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmistral-text-completion.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.", "mimetype": "text/plain", "start_char_idx": 1116497, "end_char_idx": 1121145, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8936efc7-eea6-4fcf-9309-15f097965a0b": {"__data__": {"id_": "8936efc7-eea6-4fcf-9309-15f097965a0b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aa1b2fe5-9889-4420-a499-94ee22cc3029", "node_type": "1", "metadata": {}, "hash": "13218e17142afbb69521884c2f3ab030d93589e18fa78e3abdc878dbd7c80f3f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8d34144b-cbab-4ce2-b5ac-993ed741ad5a", "node_type": "1", "metadata": {}, "hash": "9ea52b8547e045287f1f47e5b024f9d63a69b4ac1d87b74de5181a0c1ff048e8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeAsyncClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Mistral Large.\nvar modelId = \"mistral.mistral-large-2402-v1:0\";\n// The InvokeModelWithResponseStream API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\nmistral-text-completion.html\nvar nativeRequestTemplate = \"{ \\\"prompt\\\": \\\"{{instruction}}\\\" }\";\n// Define the prompt for the model.\nMistral AI 732\nAWS SDK for Java 2.x Developer Guide for version 2.x\nvar prompt = \"Describe the purpose of a 'hello world' program in one line.\";\n// Embed the prompt in Mistral's instruction format.\nvar instruction = \"[INST] {{prompt}} [/INST]\\\\n\".replace(\"{{prompt}}\",\nprompt);\n// Embed the instruction in the the native request payload.\nvar nativeRequest = nativeRequestTemplate.replace(\"{{instruction}}\",\ninstruction);\n// Create a request with the model ID and the model's native request\npayload.\nvar request = InvokeModelWithResponseStreamRequest.builder()\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n.build();\n// Prepare a buffer to accumulate the generated response text.\nvar completeResponseTextBuffer = new StringBuilder();\n// Prepare a handler to extract, accumulate, and print the response text in\nreal-time.\nvar responseStreamHandler =\nInvokeModelWithResponseStreamResponseHandler.builder()\n.subscriber(Visitor.builder().onChunk(chunk -> {\n// Extract and print the text from the model's native response.\nvar response = new JSONObject(chunk.bytes().asUtf8String());\nvar text = new JSONPointer(\"/outputs/0/\ntext\").queryFrom(response);\nSystem.out.print(text);\n// Append the text to the response text buffer.\ncompleteResponseTextBuffer.append(text);\n}).build()).build();\ntry {\n// Send the request and wait for the handler to process the response.\nclient.invokeModelWithResponseStream(request,\nresponseStreamHandler).get();\n// Return the complete response text.\nreturn completeResponseTextBuffer.toString();\n} catch (ExecutionException | InterruptedException e) {\nMistral AI 733\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.printf(\"Can't invoke '%s': %s\", modelId,\ne.getCause().getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) throws ExecutionException,\nInterruptedException {\ninvokeModelWithResponseStream();\n}\n}\n\u2022 For API details, see InvokeModelWithResponseStream in AWS SDK for Java 2.x API Reference.\nStable Diffusion\nInvokeModel\nThe following code example shows how to invoke Stability.ai Stable Diffusion XL on Amazon\nBedrock to generate an image.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nCreate an image with Stable Diffusion.\n// Create an image with Stable Diffusion.\nimport org.json.JSONObject;\nimport org.json.JSONPointer;\nimport software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;\nStable Diffusion 734\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport static com.example.bedrockruntime.libs.ImageTools.displayImage;\npublic class InvokeModel {\npublic static String invokeModel() {\n// Create a Bedrock Runtime client in the AWS Region you want to use.\n// Replace the DefaultCredentialsProvider with your preferred credentials\nprovider.\nvar client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Stable Diffusion XL v1.\nvar modelId = \"stability.stable-diffusion-xl-v1\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ndiffusion-1-0-text-image.html\nvar nativeRequestTemplate = \"\"\"\n{\n\"text_prompts\": [{ \"text\": \"{{prompt}}\" }],\n\"style_preset\": \"{{style}}\",\n\"seed\": {{seed}}\n}\"\"\";\n// Define the prompt for the image generation.\nvar prompt = \"A stylized picture of a cute old steampunk robot\";\n// Get a random 32-bit seed for the image generation (max.", "mimetype": "text/plain", "start_char_idx": 1120469, "end_char_idx": 1125079, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8d34144b-cbab-4ce2-b5ac-993ed741ad5a": {"__data__": {"id_": "8d34144b-cbab-4ce2-b5ac-993ed741ad5a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8936efc7-eea6-4fcf-9309-15f097965a0b", "node_type": "1", "metadata": {}, "hash": "c03d7e6ee2a796dbbc86bc24f9b29eb83bc21f7147d0abee17641913af15ba36", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b428d621-93c3-446a-b2ff-2eb2d1fb78df", "node_type": "1", "metadata": {}, "hash": "49b6badda541310b50a50e44318cea134b8dbfaa18400c8af3e8e0ac54ab786d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "var client = BedrockRuntimeClient.builder()\n.credentialsProvider(DefaultCredentialsProvider.create())\n.region(Region.US_EAST_1)\n.build();\n// Set the model ID, e.g., Stable Diffusion XL v1.\nvar modelId = \"stability.stable-diffusion-xl-v1\";\n// The InvokeModel API uses the model's native payload.\n// Learn more about the available inference parameters and response fields\nat:\n// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-\ndiffusion-1-0-text-image.html\nvar nativeRequestTemplate = \"\"\"\n{\n\"text_prompts\": [{ \"text\": \"{{prompt}}\" }],\n\"style_preset\": \"{{style}}\",\n\"seed\": {{seed}}\n}\"\"\";\n// Define the prompt for the image generation.\nvar prompt = \"A stylized picture of a cute old steampunk robot\";\n// Get a random 32-bit seed for the image generation (max. 4,294,967,295).\nvar seed = new BigInteger(31, new SecureRandom());\n// Choose a style preset.\nvar style = \"cinematic\";\n// Embed the prompt, seed, and style in the model's native request payload.\nString nativeRequest = nativeRequestTemplate\n.replace(\"{{prompt}}\", prompt)\nStable Diffusion 735\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.replace(\"{{seed}}\", seed.toString())\n.replace(\"{{style}}\", style);\ntry {\n// Encode and send the request to the Bedrock Runtime.\nvar response = client.invokeModel(request -> request\n.body(SdkBytes.fromUtf8String(nativeRequest))\n.modelId(modelId)\n);\n// Decode the response body.\nvar responseBody = new JSONObject(response.body().asUtf8String());\n// Retrieve the generated image data from the model's response.\nvar base64ImageData = new JSONPointer(\"/artifacts/0/base64\")\n.queryFrom(responseBody)\n.toString();\nreturn base64ImageData;\n} catch (SdkClientException e) {\nSystem.err.printf(\"ERROR: Can't invoke '%s'. Reason: %s\", modelId,\ne.getMessage());\nthrow new RuntimeException(e);\n}\n}\npublic static void main(String[] args) {\nSystem.out.println(\"Generating image. This may take a few seconds...\");\nString base64ImageData = invokeModel();\ndisplayImage(base64ImageData);\n}\n}\n\u2022 For API details, see InvokeModel in AWS SDK for Java 2.x API Reference.\nStable Diffusion 736\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCloudFront examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudFront.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateDistribution\nThe following code example shows how to use CreateDistribution.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThe following example uses an Amazon Simple Storage Service (Amazon S3) bucket as a\ncontent origin.\nAfter creating the distribution, the code creates a CloudFrontWaiter to wait until the\ndistribution is deployed before returning the distribution.", "mimetype": "text/plain", "start_char_idx": 1124301, "end_char_idx": 1127630, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b428d621-93c3-446a-b2ff-2eb2d1fb78df": {"__data__": {"id_": "b428d621-93c3-446a-b2ff-2eb2d1fb78df", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8d34144b-cbab-4ce2-b5ac-993ed741ad5a", "node_type": "1", "metadata": {}, "hash": "9ea52b8547e045287f1f47e5b024f9d63a69b4ac1d87b74de5181a0c1ff048e8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5ecdadfe-06a9-4745-bcc4-3b9fd095e939", "node_type": "1", "metadata": {}, "hash": "d28f9d44b53fcf5468a322c5c5087eafb027790f1f798614f8fb2051e4cb00a7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateDistribution\nThe following code example shows how to use CreateDistribution.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThe following example uses an Amazon Simple Storage Service (Amazon S3) bucket as a\ncontent origin.\nAfter creating the distribution, the code creates a CloudFrontWaiter to wait until the\ndistribution is deployed before returning the distribution.\nimport org.slf4j.Logger;\nCloudFront 737\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.internal.waiters.ResponseOrException;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.Distribution;\nimport software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.ItemSelection;\nimport software.amazon.awssdk.services.cloudfront.model.Method;\nimport software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy;\nimport software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport java.time.Instant;\npublic class CreateDistribution {\nprivate static final Logger logger =\nLoggerFactory.getLogger(CreateDistribution.class);\npublic static Distribution createDistribution(CloudFrontClient\ncloudFrontClient, S3Client s3Client,\nfinal String bucketName, final String keyGroupId, final\nString originAccessControlId) {\nfinal String region = s3Client.headBucket(b ->\nb.bucket(bucketName)).sdkHttpResponse().headers()\n.get(\"x-amz-bucket-region\").get(0);\nfinal String originDomain = bucketName + \".s3.\" + region +\n\".amazonaws.com\";\nString originId = originDomain; // Use the originDomain value for\nthe originId.\n// The service API requires some deprecated methods, such as\n// DefaultCacheBehavior.Builder#minTTL and #forwardedValue.\nCreateDistributionResponse createDistResponse =\ncloudFrontClient.createDistribution(builder -> builder\n.distributionConfig(b1 -> b1\n.origins(b2 -> b2\n.quantity(1)\n.items(b3 -> b3\n.domainName(originDomain)\n.id(originId)\nActions 738\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.s3OriginConfig(builder4 -> builder4\n.originAccessIdentity(\n\"\"))\n.originAccessControlId(\noriginAccessControlId)))\n.defaultCacheBehavior(b2 -> b2\n.viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL)\n.targetOriginId(originId)\n.minTTL(200L)\n.forwardedValues(b5\n-> b5\n.cookies(cp -> cp\n.forward(ItemSelection.NONE))\n.queryString(true))\n.trustedKeyGroups(b3\n-> b3\n.quantity(1)\n.items(keyGroupId)\n.enabled(true))\n.allowedMethods(b4 -\n> b4\n.quantity(2)\n.items(Method.HEAD, Method.GET)\n.cachedMethods(b5 -> b5\n.quantity(2)\n.items(Method.HEAD,\nActions 739\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMethod.GET))))\n.cacheBehaviors(b -> b\n.quantity(1)\n.items(b2 -> b2\n.pathPattern(\"/index.html\")\n.viewerProtocolPolicy(\nViewerProtocolPolicy.ALLOW_ALL)\n.targetOriginId(originId)\n.trustedKeyGroups(b3 -> b3\n.quantity(1)\n.items(keyGroupId)\n.enabled(true))\n.minTTL(200L)\n.forwardedValues(b4 -> b4\n.cookies(cp -> cp\n.forward(ItemSelection.NONE))\n.queryString(true))\n.allowedMethods(b5 -> b5.quantity(2)\n.items(Method.HEAD,\nMethod.GET)\n.cachedMethods(b6 -> b6\n.quantity(2)\n.items(Method.HEAD,\nActions 740\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMethod.GET)))))\n.enabled(true)\n.comment(\"Distribution built with\njava\")\n.callerReference(Instant.now().toString())));\nfinal Distribution distribution = createDistResponse.distribution();\nlogger.info(\"Distribution created.", "mimetype": "text/plain", "start_char_idx": 1126704, "end_char_idx": 1130876, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5ecdadfe-06a9-4745-bcc4-3b9fd095e939": {"__data__": {"id_": "5ecdadfe-06a9-4745-bcc4-3b9fd095e939", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b428d621-93c3-446a-b2ff-2eb2d1fb78df", "node_type": "1", "metadata": {}, "hash": "49b6badda541310b50a50e44318cea134b8dbfaa18400c8af3e8e0ac54ab786d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9f3fcb25-ca3b-487e-8153-17488d5f4a31", "node_type": "1", "metadata": {}, "hash": "5240b1c38169e5e61737afece254d0b16dc49f7a3ff4c320c00ee92243ced072", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DomainName: [{}] Id: [{}]\",\ndistribution.domainName(),\ndistribution.id());\nlogger.info(\"Waiting for distribution to be deployed ...\");\ntry (CloudFrontWaiter cfWaiter =\nCloudFrontWaiter.builder().client(cloudFrontClient).build()) {\nResponseOrException\nresponseOrException = cfWaiter\n.waitUntilDistributionDeployed(builder ->\nbuilder.id(distribution.id()))\n.matched();\nresponseOrException.response()\n.orElseThrow(() -> new\nRuntimeException(\"Distribution not created\"));\nlogger.info(\"Distribution deployed. DomainName: [{}] Id:\n[{}]\", distribution.domainName(),\ndistribution.id());\n}\nreturn distribution;\n}\n}\n\u2022 For API details, see CreateDistribution in AWS SDK for Java 2.x API Reference.\nCreateFunction\nThe following code example shows how to use CreateFunction.\nActions 741\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.core.SdkBytes;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.CloudFrontException;\nimport software.amazon.awssdk.services.cloudfront.model.CreateFunctionRequest;\nimport software.amazon.awssdk.services.cloudfront.model.CreateFunctionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.FunctionConfig;\nimport software.amazon.awssdk.services.cloudfront.model.FunctionRuntime;\nimport java.io.InputStream;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateFunction {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\nfunctionName - The name of the function to create.\\s\nfilePath - The path to a file that contains the application\nlogic for the function.\\s\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nActions 742\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\nString functionName = args[0];\nString filePath = args[1];\nCloudFrontClient cloudFrontClient = CloudFrontClient.builder()\n.region(Region.AWS_GLOBAL)\n.build();\nString funArn = createNewFunction(cloudFrontClient, functionName, filePath);\nSystem.out.println(\"The function ARN is \" + funArn);\ncloudFrontClient.close();\n}\npublic static String createNewFunction(CloudFrontClient cloudFrontClient, String\nfunctionName, String filePath) {\ntry {\nInputStream fileIs =\nCreateFunction.class.getClassLoader().getResourceAsStream(filePath);\nSdkBytes functionCode = SdkBytes.fromInputStream(fileIs);\nFunctionConfig config = FunctionConfig.builder()\n.comment(\"Created by using the CloudFront Java API\")\n.runtime(FunctionRuntime.CLOUDFRONT_JS_1_0)\n.build();\nCreateFunctionRequest functionRequest = CreateFunctionRequest.builder()\n.name(functionName)\n.functionCode(functionCode)\n.functionConfig(config)\n.build();\nCreateFunctionResponse response =\ncloudFrontClient.createFunction(functionRequest);\nreturn response.functionSummary().functionMetadata().functionARN();\n} catch (CloudFrontException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\nActions 743\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see CreateFunction in AWS SDK for Java 2.x API Reference.\nCreateKeyGroup\nThe following code example shows how to use CreateKeyGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nA key group requires at least one public key that is used to verify signed URLs or cookies.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport java.util.UUID;\npublic class CreateKeyGroup {\nprivate static final Logger logger =\nLoggerFactory.getLogger(CreateKeyGroup.class);\npublic static String createKeyGroup(CloudFrontClient cloudFrontClient, String\npublicKeyId) {\nString keyGroupId = cloudFrontClient.createKeyGroup(b -> b.keyGroupConfig(c\n-> c\n.items(publicKeyId)\n.name(\"JavaKeyGroup\" + UUID.randomUUID())))\n.keyGroup().id();\nlogger.info(\"KeyGroup created with ID: [{}]\", keyGroupId);\nreturn keyGroupId;\n}\n}\n\u2022 For API details, see CreateKeyGroup in AWS SDK for Java 2.x API Reference.\nActions 744\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreatePublicKey\nThe following code example shows how to use CreatePublicKey.", "mimetype": "text/plain", "start_char_idx": 1130877, "end_char_idx": 1135537, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9f3fcb25-ca3b-487e-8153-17488d5f4a31": {"__data__": {"id_": "9f3fcb25-ca3b-487e-8153-17488d5f4a31", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5ecdadfe-06a9-4745-bcc4-3b9fd095e939", "node_type": "1", "metadata": {}, "hash": "d28f9d44b53fcf5468a322c5c5087eafb027790f1f798614f8fb2051e4cb00a7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a1d312c4-06af-4c3b-8e0c-90137c63bafd", "node_type": "1", "metadata": {}, "hash": "7a6564e2ba6e88e97f1a60c43773de43df4711531c96ac8649892c7529cec3ca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport java.util.UUID;\npublic class CreateKeyGroup {\nprivate static final Logger logger =\nLoggerFactory.getLogger(CreateKeyGroup.class);\npublic static String createKeyGroup(CloudFrontClient cloudFrontClient, String\npublicKeyId) {\nString keyGroupId = cloudFrontClient.createKeyGroup(b -> b.keyGroupConfig(c\n-> c\n.items(publicKeyId)\n.name(\"JavaKeyGroup\" + UUID.randomUUID())))\n.keyGroup().id();\nlogger.info(\"KeyGroup created with ID: [{}]\", keyGroupId);\nreturn keyGroupId;\n}\n}\n\u2022 For API details, see CreateKeyGroup in AWS SDK for Java 2.x API Reference.\nActions 744\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreatePublicKey\nThe following code example shows how to use CreatePublicKey.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThe following code example reads in a public key and uploads it to Amazon CloudFront.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.CreatePublicKeyResponse;\nimport software.amazon.awssdk.utils.IoUtils;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.UUID;\npublic class CreatePublicKey {\nprivate static final Logger logger =\nLoggerFactory.getLogger(CreatePublicKey.class);\npublic static String createPublicKey(CloudFrontClient cloudFrontClient, String\npublicKeyFileName) {\ntry (InputStream is =\nCreatePublicKey.class.getClassLoader().getResourceAsStream(publicKeyFileName)) {\nString publicKeyString = IoUtils.toUtf8String(is);\nCreatePublicKeyResponse createPublicKeyResponse = cloudFrontClient\n.createPublicKey(b -> b.publicKeyConfig(c -> c\n.name(\"JavaCreatedPublicKey\" + UUID.randomUUID())\n.encodedKey(publicKeyString)\n.callerReference(UUID.randomUUID().toString())));\nString createdPublicKeyId = createPublicKeyResponse.publicKey().id();\nlogger.info(\"Public key created with id: [{}]\", createdPublicKeyId);\nreturn createdPublicKeyId;\n} catch (IOException e) {\nActions 745\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow new RuntimeException(e);\n}\n}\n}\n\u2022 For API details, see CreatePublicKey in AWS SDK for Java 2.x API Reference.\nDeleteDistribution\nThe following code example shows how to use DeleteDistribution.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThe following code example updates a distribution to disabled, uses a waiter that waits for the\nchange to be deployed, then deletes the distribution.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.internal.waiters.ResponseOrException;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.DeleteDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.DistributionConfig;\nimport software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;\npublic class DeleteDistribution {\nprivate static final Logger logger =\nLoggerFactory.getLogger(DeleteDistribution.class);\npublic static void deleteDistribution(final CloudFrontClient\ncloudFrontClient, final String distributionId) {\n// First, disable the distribution by updating it.", "mimetype": "text/plain", "start_char_idx": 1134719, "end_char_idx": 1138251, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a1d312c4-06af-4c3b-8e0c-90137c63bafd": {"__data__": {"id_": "a1d312c4-06af-4c3b-8e0c-90137c63bafd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9f3fcb25-ca3b-487e-8153-17488d5f4a31", "node_type": "1", "metadata": {}, "hash": "5240b1c38169e5e61737afece254d0b16dc49f7a3ff4c320c00ee92243ced072", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8a05d80b-5994-4300-a88f-77394ac0cff8", "node_type": "1", "metadata": {}, "hash": "1a58441f6e0363143fa2d3a22cc3917d2556d780c43158763604d6d8e6cdb467", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThe following code example updates a distribution to disabled, uses a waiter that waits for the\nchange to be deployed, then deletes the distribution.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.internal.waiters.ResponseOrException;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.DeleteDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.DistributionConfig;\nimport software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;\npublic class DeleteDistribution {\nprivate static final Logger logger =\nLoggerFactory.getLogger(DeleteDistribution.class);\npublic static void deleteDistribution(final CloudFrontClient\ncloudFrontClient, final String distributionId) {\n// First, disable the distribution by updating it.\nGetDistributionResponse response =\ncloudFrontClient.getDistribution(b -> b\n.id(distributionId));\nActions 746\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString etag = response.eTag();\nDistributionConfig distConfig =\nresponse.distribution().distributionConfig();\ncloudFrontClient.updateDistribution(builder -> builder\n.id(distributionId)\n.distributionConfig(builder1 -> builder1\n.cacheBehaviors(distConfig.cacheBehaviors())\n.defaultCacheBehavior(distConfig.defaultCacheBehavior())\n.enabled(false)\n.origins(distConfig.origins())\n.comment(distConfig.comment())\n.callerReference(distConfig.callerReference())\n.defaultCacheBehavior(distConfig.defaultCacheBehavior())\n.priceClass(distConfig.priceClass())\n.aliases(distConfig.aliases())\n.logging(distConfig.logging())\n.defaultRootObject(distConfig.defaultRootObject())\n.customErrorResponses(distConfig.customErrorResponses())\n.httpVersion(distConfig.httpVersion())\n.isIPV6Enabled(distConfig.isIPV6Enabled())\n.restrictions(distConfig.restrictions())\n.viewerCertificate(distConfig.viewerCertificate())\n.webACLId(distConfig.webACLId())\n.originGroups(distConfig.originGroups()))\n.ifMatch(etag));\nlogger.info(\"Distribution [{}] is DISABLED, waiting for deployment\nbefore deleting ...\",\ndistributionId);\nGetDistributionResponse distributionResponse;\ntry (CloudFrontWaiter cfWaiter =\nCloudFrontWaiter.builder().client(cloudFrontClient).build()) {\nActions 747\nAWS SDK for Java 2.x Developer Guide for version 2.x\nResponseOrException\nresponseOrException = cfWaiter\n.waitUntilDistributionDeployed(builder ->\nbuilder.id(distributionId)).matched();\ndistributionResponse = responseOrException.response()\n.orElseThrow(() -> new\nRuntimeException(\"Could not disable distribution\"));\n}\nDeleteDistributionResponse deleteDistributionResponse =\ncloudFrontClient\n.deleteDistribution(builder -> builder\n.id(distributionId)\n.ifMatch(distributionResponse.eTag()));\nif (deleteDistributionResponse.sdkHttpResponse().isSuccessful()) {\nlogger.info(\"Distribution [{}] DELETED\", distributionId);\n}\n}\n}\n\u2022 For API details, see DeleteDistribution in AWS SDK for Java 2.x API Reference.\nUpdateDistribution\nThe following code example shows how to use UpdateDistribution.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.GetDistributionRequest;\nimport software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;\nimport software.amazon.awssdk.services.cloudfront.model.Distribution;\nimport software.amazon.awssdk.services.cloudfront.model.DistributionConfig;\nActions 748\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.cloudfront.model.UpdateDistributionRequest;\nimport software.amazon.awssdk.services.cloudfront.model.CloudFrontException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ModifyDistribution {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nid - the id value of the distribution.\\s\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString id = args[0];\nCloudFrontClient cloudFrontClient = CloudFrontClient.builder()\n.region(Region.AWS_GLOBAL)\n.build();\nmodDistribution(cloudFrontClient, id);\ncloudFrontClient.close();\n}\npublic static void modDistribution(CloudFrontClient cloudFrontClient, String\nidVal) {\ntry {\n// Get the Distribution to modify.", "mimetype": "text/plain", "start_char_idx": 1137209, "end_char_idx": 1142070, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8a05d80b-5994-4300-a88f-77394ac0cff8": {"__data__": {"id_": "8a05d80b-5994-4300-a88f-77394ac0cff8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a1d312c4-06af-4c3b-8e0c-90137c63bafd", "node_type": "1", "metadata": {}, "hash": "7a6564e2ba6e88e97f1a60c43773de43df4711531c96ac8649892c7529cec3ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "35231165-e92b-4d16-a46c-0bd7d157c53a", "node_type": "1", "metadata": {}, "hash": "1e36c380c577b2b00e670a1362b456699aa1a67db45673f9a39722e997846936", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ModifyDistribution {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nid - the id value of the distribution.\\s\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString id = args[0];\nCloudFrontClient cloudFrontClient = CloudFrontClient.builder()\n.region(Region.AWS_GLOBAL)\n.build();\nmodDistribution(cloudFrontClient, id);\ncloudFrontClient.close();\n}\npublic static void modDistribution(CloudFrontClient cloudFrontClient, String\nidVal) {\ntry {\n// Get the Distribution to modify.\nGetDistributionRequest disRequest = GetDistributionRequest.builder()\n.id(idVal)\n.build();\nActions 749\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetDistributionResponse response =\ncloudFrontClient.getDistribution(disRequest);\nDistribution disObject = response.distribution();\nDistributionConfig config = disObject.distributionConfig();\n// Create a new DistributionConfig object and add new values to comment\nand\n// aliases\nDistributionConfig config1 = DistributionConfig.builder()\n.aliases(config.aliases()) // You can pass in new values here\n.comment(\"New Comment\")\n.cacheBehaviors(config.cacheBehaviors())\n.priceClass(config.priceClass())\n.defaultCacheBehavior(config.defaultCacheBehavior())\n.enabled(config.enabled())\n.callerReference(config.callerReference())\n.logging(config.logging())\n.originGroups(config.originGroups())\n.origins(config.origins())\n.restrictions(config.restrictions())\n.defaultRootObject(config.defaultRootObject())\n.webACLId(config.webACLId())\n.httpVersion(config.httpVersion())\n.viewerCertificate(config.viewerCertificate())\n.customErrorResponses(config.customErrorResponses())\n.build();\nUpdateDistributionRequest updateDistributionRequest =\nUpdateDistributionRequest.builder()\n.distributionConfig(config1)\n.id(disObject.id())\n.ifMatch(response.eTag())\n.build();\ncloudFrontClient.updateDistribution(updateDistributionRequest);\n} catch (CloudFrontException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\nActions 750\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see UpdateDistribution in AWS SDK for Java 2.x API Reference.\nScenarios\nDelete signing resources\nThe following code example shows how to delete resources that are used to gain access to\nrestricted content in an Amazon Simple Storage Service (Amazon S3) bucket.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1141367, "end_char_idx": 1144030, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "35231165-e92b-4d16-a46c-0bd7d157c53a": {"__data__": {"id_": "35231165-e92b-4d16-a46c-0bd7d157c53a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8a05d80b-5994-4300-a88f-77394ac0cff8", "node_type": "1", "metadata": {}, "hash": "1a58441f6e0363143fa2d3a22cc3917d2556d780c43158763604d6d8e6cdb467", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c359e396-535b-4493-a607-e207efa683db", "node_type": "1", "metadata": {}, "hash": "9da04d14349a6424c04222cc627e1ac57c1fad5ae0b0d328e1611439b092657c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Scenarios\nDelete signing resources\nThe following code example shows how to delete resources that are used to gain access to\nrestricted content in an Amazon Simple Storage Service (Amazon S3) bucket.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontClient;\nimport software.amazon.awssdk.services.cloudfront.model.DeleteKeyGroupResponse;\nimport\nsoftware.amazon.awssdk.services.cloudfront.model.DeleteOriginAccessControlResponse;\nimport software.amazon.awssdk.services.cloudfront.model.DeletePublicKeyResponse;\nimport software.amazon.awssdk.services.cloudfront.model.GetKeyGroupResponse;\nimport\nsoftware.amazon.awssdk.services.cloudfront.model.GetOriginAccessControlResponse;\nimport software.amazon.awssdk.services.cloudfront.model.GetPublicKeyResponse;\npublic class DeleteSigningResources {\nprivate static final Logger logger =\nLoggerFactory.getLogger(DeleteSigningResources.class);\npublic static void deleteOriginAccessControl(final CloudFrontClient\ncloudFrontClient,\nfinal String originAccessControlId) {\nGetOriginAccessControlResponse getResponse = cloudFrontClient\n.getOriginAccessControl(b -> b.id(originAccessControlId));\nDeleteOriginAccessControlResponse deleteResponse =\ncloudFrontClient.deleteOriginAccessControl(builder -> builder\n.id(originAccessControlId)\nScenarios 751\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.ifMatch(getResponse.eTag()));\nif (deleteResponse.sdkHttpResponse().isSuccessful()) {\nlogger.info(\"Successfully deleted Origin Access Control [{}]\",\noriginAccessControlId);\n}\n}\npublic static void deleteKeyGroup(final CloudFrontClient cloudFrontClient, final\nString keyGroupId) {\nGetKeyGroupResponse getResponse = cloudFrontClient.getKeyGroup(b ->\nb.id(keyGroupId));\nDeleteKeyGroupResponse deleteResponse =\ncloudFrontClient.deleteKeyGroup(builder -> builder\n.id(keyGroupId)\n.ifMatch(getResponse.eTag()));\nif (deleteResponse.sdkHttpResponse().isSuccessful()) {\nlogger.info(\"Successfully deleted Key Group [{}]\", keyGroupId);\n}\n}\npublic static void deletePublicKey(final CloudFrontClient cloudFrontClient,\nfinal String publicKeyId) {\nGetPublicKeyResponse getResponse = cloudFrontClient.getPublicKey(b ->\nb.id(publicKeyId));\nDeletePublicKeyResponse deleteResponse =\ncloudFrontClient.deletePublicKey(builder -> builder\n.id(publicKeyId)\n.ifMatch(getResponse.eTag()));\nif (deleteResponse.sdkHttpResponse().isSuccessful()) {\nlogger.info(\"Successfully deleted Public Key [{}]\", publicKeyId);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 DeleteKeyGroup\n\u2022 DeleteOriginAccessControl\n\u2022 DeletePublicKey\nScenarios 752\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSign URLs and cookies\nThe following code example shows how to create signed URLs and cookies that allow access to\nrestricted resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUse the CannedSignerRequest class to sign URLs or cookies with a canned policy.\nimport software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest;\nimport java.net.URL;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.Instant;\nimport java.time.temporal.ChronoUnit;\npublic class CreateCannedPolicyRequest {\npublic static CannedSignerRequest createRequestForCannedPolicy(String\ndistributionDomainName,\nString fileNameToUpload,\nString privateKeyFullPath, String publicKeyId) throws Exception {\nString protocol = \"https\";\nString resourcePath = \"/\" + fileNameToUpload;\nString cloudFrontUrl = new URL(protocol, distributionDomainName,\nresourcePath).toString();\nInstant expirationDate = Instant.now().plus(7, ChronoUnit.DAYS);\nPath path = Paths.get(privateKeyFullPath);\nreturn CannedSignerRequest.builder()\n.resourceUrl(cloudFrontUrl)\n.privateKey(path)\n.keyPairId(publicKeyId)\n.expirationDate(expirationDate)\n.build();\nScenarios 753\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\nUse the CustomSignerRequest class to sign URLs or cookies with a custom policy. The\nactiveDate and ipRange are optional methods.", "mimetype": "text/plain", "start_char_idx": 1143691, "end_char_idx": 1147955, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c359e396-535b-4493-a607-e207efa683db": {"__data__": {"id_": "c359e396-535b-4493-a607-e207efa683db", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "35231165-e92b-4d16-a46c-0bd7d157c53a", "node_type": "1", "metadata": {}, "hash": "1e36c380c577b2b00e670a1362b456699aa1a67db45673f9a39722e997846936", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "68c91fbb-859f-4e25-b8c6-dc07e8f1608e", "node_type": "1", "metadata": {}, "hash": "964af22c570fdcd59396a37372fce4a5a2fbf357d1901fb7bbb8c404f10c48ea", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The\nactiveDate and ipRange are optional methods.\nimport software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest;\nimport java.net.URL;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.Instant;\nimport java.time.temporal.ChronoUnit;\npublic class CreateCustomPolicyRequest {\npublic static CustomSignerRequest createRequestForCustomPolicy(String\ndistributionDomainName,\nString fileNameToUpload,\nString privateKeyFullPath, String publicKeyId) throws Exception {\nString protocol = \"https\";\nString resourcePath = \"/\" + fileNameToUpload;\nString cloudFrontUrl = new URL(protocol, distributionDomainName,\nresourcePath).toString();\nInstant expireDate = Instant.now().plus(7, ChronoUnit.DAYS);\n// URL will be accessible tomorrow using the signed URL.\nInstant activeDate = Instant.now().plus(1, ChronoUnit.DAYS);\nPath path = Paths.get(privateKeyFullPath);\nreturn CustomSignerRequest.builder()\n.resourceUrl(cloudFrontUrl)\n.privateKey(path)\n.keyPairId(publicKeyId)\n.expirationDate(expireDate)\n.activeDate(activeDate) // Optional.\n// .ipRange(\"192.168.0.1/24\") // Optional.\n.build();\n}\n}\nScenarios 754\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe following example demonstrates the use of the CloudFrontUtilities class to produce signed\ncookies and URLs. View this code example on GitHub.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudfront.CloudFrontUtilities;\nimport software.amazon.awssdk.services.cloudfront.cookie.CookiesForCannedPolicy;\nimport software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy;\nimport software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest;\nimport software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest;\nimport software.amazon.awssdk.services.cloudfront.url.SignedUrl;\npublic class SigningUtilities {\nprivate static final Logger logger =\nLoggerFactory.getLogger(SigningUtilities.class);\nprivate static final CloudFrontUtilities cloudFrontUtilities =\nCloudFrontUtilities.create();\npublic static SignedUrl signUrlForCannedPolicy(CannedSignerRequest\ncannedSignerRequest) {\nSignedUrl signedUrl =\ncloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedSignerRequest);\nlogger.info(\"Signed URL: [{}]\", signedUrl.url());\nreturn signedUrl;\n}\npublic static SignedUrl signUrlForCustomPolicy(CustomSignerRequest\ncustomSignerRequest) {\nSignedUrl signedUrl =\ncloudFrontUtilities.getSignedUrlWithCustomPolicy(customSignerRequest);\nlogger.info(\"Signed URL: [{}]\", signedUrl.url());\nreturn signedUrl;\n}\npublic static CookiesForCannedPolicy\ngetCookiesForCannedPolicy(CannedSignerRequest cannedSignerRequest) {\nCookiesForCannedPolicy cookiesForCannedPolicy = cloudFrontUtilities\n.getCookiesForCannedPolicy(cannedSignerRequest);\nlogger.info(\"Cookie EXPIRES header [{}]\",\ncookiesForCannedPolicy.expiresHeaderValue());\nlogger.info(\"Cookie KEYPAIR header [{}]\",\ncookiesForCannedPolicy.keyPairIdHeaderValue());\nScenarios 755\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Cookie SIGNATURE header [{}]\",\ncookiesForCannedPolicy.signatureHeaderValue());\nreturn cookiesForCannedPolicy;\n}\npublic static CookiesForCustomPolicy\ngetCookiesForCustomPolicy(CustomSignerRequest customSignerRequest) {\nCookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities\n.getCookiesForCustomPolicy(customSignerRequest);\nlogger.info(\"Cookie POLICY header [{}]\",\ncookiesForCustomPolicy.policyHeaderValue());\nlogger.info(\"Cookie KEYPAIR header [{}]\",\ncookiesForCustomPolicy.keyPairIdHeaderValue());\nlogger.info(\"Cookie SIGNATURE header [{}]\",\ncookiesForCustomPolicy.signatureHeaderValue());\nreturn cookiesForCustomPolicy;\n}\n}\n\u2022 For API details, see CloudFrontUtilities in AWS SDK for Java 2.x API Reference.\nCloudWatch examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello CloudWatch\nThe following code examples show how to get started using CloudWatch.", "mimetype": "text/plain", "start_char_idx": 1147907, "end_char_idx": 1152528, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "68c91fbb-859f-4e25-b8c6-dc07e8f1608e": {"__data__": {"id_": "68c91fbb-859f-4e25-b8c6-dc07e8f1608e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c359e396-535b-4493-a607-e207efa683db", "node_type": "1", "metadata": {}, "hash": "9da04d14349a6424c04222cc627e1ac57c1fad5ae0b0d328e1611439b092657c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "71f897b3-3dd4-4056-9f33-a988fa552dfb", "node_type": "1", "metadata": {}, "hash": "1ade72c958ee40bd476a6606b5ebd8384c0a8286d6f6d102022f374e36a761a7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CloudWatch examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello CloudWatch\nThe following code examples show how to get started using CloudWatch.\nCloudWatch 756\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest;\nimport software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class HelloService {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nnamespace - The namespace to filter against (for example, AWS/\nEC2).\\s\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString namespace = args[0];\nRegion region = Region.US_EAST_1;\nCloudWatchClient cw = CloudWatchClient.builder()\nCloudWatch 757\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(region)\n.build();\nlistMets(cw, namespace);\ncw.close();\n}\npublic static void listMets(CloudWatchClient cw, String namespace) {\ntry {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.build();\nListMetricsIterable listRes = cw.listMetricsPaginator(request);\nlistRes.stream()\n.flatMap(r -> r.metrics().stream())\n.forEach(metrics -> System.out.println(\" Retrieved metric is: \"\n+ metrics.metricName()));\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListMetrics in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 List CloudWatch namespaces and metrics.\nBasics 758\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Get statistics for a metric and for estimated billing.\n\u2022 Create and update a dashboard.\n\u2022 Create and add data to a metric.\n\u2022 Create and trigger an alarm, then view alarm history.\n\u2022 Add an anomaly detector.\n\u2022 Get a metric image, then clean up resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun an interactive scenario demonstrating CloudWatch features.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport\nsoftware.amazon.awssdk.services.cloudwatch.model.DashboardInvalidInputErrorException;\nimport software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsResponse;\nimport\nsoftware.amazon.awssdk.services.cloudwatch.model.DeleteAnomalyDetectorResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.DeleteDashboardsResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.Dimension;\nimport software.amazon.awssdk.services.cloudwatch.model.GetMetricStatisticsResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.LimitExceededException;\nimport software.amazon.awssdk.services.cloudwatch.model.PutDashboardResponse;\nimport software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Scanner;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1151654, "end_char_idx": 1156198, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "71f897b3-3dd4-4056-9f33-a988fa552dfb": {"__data__": {"id_": "71f897b3-3dd4-4056-9f33-a988fa552dfb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "68c91fbb-859f-4e25-b8c6-dc07e8f1608e", "node_type": "1", "metadata": {}, "hash": "964af22c570fdcd59396a37372fce4a5a2fbf357d1901fb7bbb8c404f10c48ea", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8c85056c-ed33-4b4e-9d71-640f855a7d9f", "node_type": "1", "metadata": {}, "hash": "4ce18db9b5da48f2fcf711e06719e5372ff61a44daf9597a9e78bae05a34ec5e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\nBasics 759\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To enable billing metrics and statistics for this example, make sure billing\n* alerts are enabled for your account:\n* https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/\nmonitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics\n*\n* This Java code example performs the following tasks:\n*\n* 1. List available namespaces from Amazon CloudWatch.\n* 2. List available metrics within the selected Namespace.\n* 3. Get statistics for the selected metric over the last day.\n* 4. Get CloudWatch estimated billing for the last week.\n* 5. Create a new CloudWatch dashboard with metrics.\n* 6. List dashboards using a paginator.\n* 7. Create a new custom metric by adding data for it.\n* 8. Add the custom metric to the dashboard.\n* 9. Create an alarm for the custom metric.\n* 10. Describe current alarms.\n* 11. Get current data for the new custom metric.\n* 12. Push data into the custom metric to trigger the alarm.\n* 13. Check the alarm state using the action DescribeAlarmsForMetric.\n* 14. Get alarm history for the new alarm.\n* 15. Add an anomaly detector for the custom metric.\n* 16. Describe current anomaly detectors.\n* 17. Get a metric image for the custom metric.\n* 18. Clean up the Amazon CloudWatch resources.\n*/\npublic class CloudWatchScenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\nstatic CloudWatchActions cwActions = new CloudWatchActions();\nprivate static final Logger logger =\nLoggerFactory.getLogger(CloudWatchScenario.class);\nstatic Scanner scanner = new Scanner(System.in);\npublic static void main(String[] args) throws Throwable {\nfinal String usage = \"\"\"\nUsage:\nBasics 760\nAWS SDK for Java 2.x Developer Guide for version 2.x\n \n \\s\nWhere:\nmyDate - The start date to use to get metric statistics. (For example,\n2023-01-11T18:35:24.00Z.)\\s\ncostDateWeek - The start date to use to get AWS/Billing statistics.\n(For example, 2023-01-11T18:35:24.00Z.)\\s\ndashboardName - The name of the dashboard to create.\\s\ndashboardJson - The location of a JSON file to use to create a\ndashboard. (See jsonWidgets.json in javav2/example_code/cloudwatch.)\\s\ndashboardAdd - The location of a JSON file to use to update a\ndashboard. (See CloudDashboard.json in javav2/example_code/cloudwatch.)\\s\nsettings - The location of a JSON file from which various values are\nread. (See settings.json in javav2/example_code/cloudwatch.)\\s\nmetricImage - The location of a BMP file that is used to create a\ngraph.\\s\n\"\"\";\nif (args.length != 7) {\nlogger.info(usage);\nreturn;\n}\nString myDate = args[0];\nString costDateWeek = args[1];\nString dashboardName = args[2];\nString dashboardJson = args[3];\nString dashboardAdd = args[4];\nString settings = args[5];\nString metricImage = args[6];\nlogger.info(DASHES);\nlogger.info(\"Welcome to the Amazon CloudWatch Basics scenario.\");\nlogger.info(\"\"\"\nAmazon CloudWatch is a comprehensive monitoring and observability\nservice\nprovided by Amazon Web Services (AWS). It is designed to help you\nmonitor your\nAWS resources, applications, and services, as well as on-premises\nresources,\nin real-time.\nCloudWatch collects and tracks various types of data, including\nmetrics,\nBasics 761\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogs, and events, from your AWS and on-premises resources. It allows you\nto set\nalarms and automatically respond to changes in your environment,\nenabling you to quickly identify and address issues before they impact\nyour\napplications or services.\nWith CloudWatch, you can gain visibility into your entire\ninfrastructure, from the cloud\nto the edge, and use this information to make informed decisions and\noptimize your\nresource utilization.\nThis scenario guides you through how to perform Amazon CloudWatch tasks\nby using the\nAWS SDK for Java v2.", "mimetype": "text/plain", "start_char_idx": 1156199, "end_char_idx": 1160264, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8c85056c-ed33-4b4e-9d71-640f855a7d9f": {"__data__": {"id_": "8c85056c-ed33-4b4e-9d71-640f855a7d9f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "71f897b3-3dd4-4056-9f33-a988fa552dfb", "node_type": "1", "metadata": {}, "hash": "1ade72c958ee40bd476a6606b5ebd8384c0a8286d6f6d102022f374e36a761a7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d303a5d5-16e6-420c-9f96-05d099df2a3d", "node_type": "1", "metadata": {}, "hash": "cd3d654aa1ee96b8306f67a5bd5f74b8df58d65e6894e8300a4857f09f8c2350", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "It is designed to help you\nmonitor your\nAWS resources, applications, and services, as well as on-premises\nresources,\nin real-time.\nCloudWatch collects and tracks various types of data, including\nmetrics,\nBasics 761\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogs, and events, from your AWS and on-premises resources. It allows you\nto set\nalarms and automatically respond to changes in your environment,\nenabling you to quickly identify and address issues before they impact\nyour\napplications or services.\nWith CloudWatch, you can gain visibility into your entire\ninfrastructure, from the cloud\nto the edge, and use this information to make informed decisions and\noptimize your\nresource utilization.\nThis scenario guides you through how to perform Amazon CloudWatch tasks\nby using the\nAWS SDK for Java v2. Let's get started...\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nrunScenario(myDate, costDateWeek, dashboardName, dashboardJson,\ndashboardAdd, settings, metricImage);\n} catch (RuntimeException e) {\ne.printStackTrace();\n}\nlogger.info(DASHES);\n}\nprivate static void runScenario(String myDate, String costDateWeek, String\ndashboardName, String dashboardJson, String dashboardAdd, String settings, String\nmetricImage ) throws Throwable {\nDouble dataPoint = Double.parseDouble(\"10.0\");\nlogger.info(DASHES);\nlogger.info(\"\"\"\n1. List at least five available unique namespaces from Amazon CloudWatch.\nSelect one from the list.\n\"\"\");\nString selectedNamespace;\nString selectedMetrics;\nint num;\ntry {\nCompletableFuture> future =\ncwActions.listNameSpacesAsync();\nArrayList list = future.join();\nBasics 762\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfor (int z = 0; z < 5; z++) {\nint index = z + 1;\nlogger.info(\" \" + index + \". {}\", list.get(z));\n}\nnum = Integer.parseInt(scanner.nextLine());\nif (1 <= num && num <= 5) {\nselectedNamespace = list.get(num - 1);\n} else {\nlogger.info(\"You did not select a valid option.\");\nreturn;\n}\nlogger.info(\"You selected {}\", selectedNamespace);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"2. List available metrics within the selected namespace.\");\nlogger.info(\"\"\"\nA metric is a measure of the performance or health of your AWS\nresources,\napplications, or custom resources. Metrics are the basic building blocks\nof CloudWatch\nand provide data points that represent a specific aspect of your system\nor application over time.\nSelect a metric from the list.\n\"\"\");\nDimension myDimension = null;\ntry {\nCompletableFuture> future =\ncwActions.listMetsAsync(selectedNamespace);\nBasics 763\nAWS SDK for Java 2.x Developer Guide for version 2.x\nArrayList metList = future.join();\nlogger.info(\"Metrics successfully retrieved. Total metrics: {}\",\nmetList.size());\nfor (int z = 0; z < 5; z++) {\nint index = z + 1;\nlogger.info(\" \" + index + \". \" + metList.get(z));\n}\nnum = Integer.parseInt(scanner.nextLine());\nif (1 <= num && num <= 5) {\nselectedMetrics = metList.get(num - 1);\n} else {\nlogger.info(\"You did not select a valid option.\");\nreturn;\n}\nlogger.info(\"You selected {}\", selectedMetrics);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\ntry {\nmyDimension = cwActions.getSpecificMetAsync(selectedNamespace).join();\nlogger.info(\"Metric statistics successfully retrieved and displayed.", "mimetype": "text/plain", "start_char_idx": 1159450, "end_char_idx": 1163394, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d303a5d5-16e6-420c-9f96-05d099df2a3d": {"__data__": {"id_": "d303a5d5-16e6-420c-9f96-05d099df2a3d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8c85056c-ed33-4b4e-9d71-640f855a7d9f", "node_type": "1", "metadata": {}, "hash": "4ce18db9b5da48f2fcf711e06719e5372ff61a44daf9597a9e78bae05a34ec5e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b0846b50-1c46-4ad0-b6d8-13c9900dd84d", "node_type": "1", "metadata": {}, "hash": "bd135723ee35296c91090d024efe073f7fbef066940f5915f1e8a0457cee67aa", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "+ metList.get(z));\n}\nnum = Integer.parseInt(scanner.nextLine());\nif (1 <= num && num <= 5) {\nselectedMetrics = metList.get(num - 1);\n} else {\nlogger.info(\"You did not select a valid option.\");\nreturn;\n}\nlogger.info(\"You selected {}\", selectedMetrics);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\ntry {\nmyDimension = cwActions.getSpecificMetAsync(selectedNamespace).join();\nlogger.info(\"Metric statistics successfully retrieved and displayed.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nBasics 764\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(DASHES);\nlogger.info(\"3. Get statistics for the selected metric over the last day.\");\nlogger.info(\"\"\"\nStatistics refer to the various mathematical calculations that can be\nperformed on the\ncollected metrics to derive meaningful insights. Statistics provide a\nway to summarize and\nanalyze the data collected for a specific metric over a specified time\nperiod.\n\"\"\");\nwaitForInputToContinue(scanner);\nString metricOption = \"\";\nArrayList statTypes = new ArrayList<>();\nstatTypes.add(\"SampleCount\");\nstatTypes.add(\"Average\");\nstatTypes.add(\"Sum\");\nstatTypes.add(\"Minimum\");\nstatTypes.add(\"Maximum\");\nfor (int t = 0; t < 5; t++) {\nlogger.info(\" \" + (t + 1) + \". {}\", statTypes.get(t));\n}\nlogger.info(\"Select a metric statistic by entering a number from the\npreceding list:\");\nnum = Integer.parseInt(scanner.nextLine());\nif (1 <= num && num <= 5) {\nmetricOption = statTypes.get(num - 1);\n} else {\nlogger.info(\"You did not select a valid option.\");\nreturn;\n}\nlogger.info(\"You selected \" + metricOption);\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.getAndDisplayMetricStatisticsAsync(selectedNamespace, selectedMetrics,\nmetricOption, myDate, myDimension);\nfuture.join();\nlogger.info(\"Metric statistics retrieved successfully.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nBasics 765\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"4. Get CloudWatch estimated billing for the last week.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.getMetricStatisticsAsync(costDateWeek);\nfuture.join();\nlogger.info(\"Metric statistics successfully retrieved and displayed.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"5. Create a new CloudWatch dashboard with metrics.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.createDashboardWithMetricsAsync(dashboardName, dashboardJson);\nfuture.join();\n} catch (RuntimeException | IOException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof DashboardInvalidInputErrorException cwEx) {\nBasics 766\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Invalid CloudWatch data. Error message: {}, Error code\n{}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"6. List dashboards using a paginator.", "mimetype": "text/plain", "start_char_idx": 1162660, "end_char_idx": 1167142, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b0846b50-1c46-4ad0-b6d8-13c9900dd84d": {"__data__": {"id_": "b0846b50-1c46-4ad0-b6d8-13c9900dd84d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d303a5d5-16e6-420c-9f96-05d099df2a3d", "node_type": "1", "metadata": {}, "hash": "cd3d654aa1ee96b8306f67a5bd5f74b8df58d65e6894e8300a4857f09f8c2350", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b6fb1377-9005-403b-84c2-4fb3f12d09bf", "node_type": "1", "metadata": {}, "hash": "012e755910c60b9ee17d796d8240abf85e22fbb7490fe57fbd029d17031d8cb8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Create a new CloudWatch dashboard with metrics.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.createDashboardWithMetricsAsync(dashboardName, dashboardJson);\nfuture.join();\n} catch (RuntimeException | IOException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof DashboardInvalidInputErrorException cwEx) {\nBasics 766\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Invalid CloudWatch data. Error message: {}, Error code\n{}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"6. List dashboards using a paginator.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future = cwActions.listDashboardsAsync();\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"7. Create a new custom metric by adding data to it.\");\nlogger.info(\"\"\"\nThe primary benefit of using a custom metric in Amazon CloudWatch is the\nability to\nmonitor and collect data that is specific to your application or\ninfrastructure.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.createNewCustomMetricAsync(dataPoint);\nfuture.join();\nBasics 767\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"8. Add an additional metric to the dashboard.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.addMetricToDashboardAsync(dashboardAdd, dashboardName);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof DashboardInvalidInputErrorException cwEx) {\nlogger.info(\"Invalid CloudWatch data. Error message: {}, Error code\n{}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"9. Create an alarm for the custom metric.\");\nwaitForInputToContinue(scanner);\nString alarmName = \"\" ;\ntry {\nCompletableFuture future = cwActions.createAlarmAsync(settings);\nalarmName = future.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof LimitExceededException cwEx) {\nBasics 768\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"The quota for alarms has been reached: Error message:\n{}, Error code {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"10. Describe ten current alarms.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future = cwActions.describeAlarmsAsync();\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"11. Get current data for new custom metric.", "mimetype": "text/plain", "start_char_idx": 1166361, "end_char_idx": 1170535, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b6fb1377-9005-403b-84c2-4fb3f12d09bf": {"__data__": {"id_": "b6fb1377-9005-403b-84c2-4fb3f12d09bf", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b0846b50-1c46-4ad0-b6d8-13c9900dd84d", "node_type": "1", "metadata": {}, "hash": "bd135723ee35296c91090d024efe073f7fbef066940f5915f1e8a0457cee67aa", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b207a3fc-9bcc-42b1-bd56-e1db4a50ab41", "node_type": "1", "metadata": {}, "hash": "f59a54915f2d669f67a5df492102e80baf55a3cbb1cb2812d09e72740961e0c9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Describe ten current alarms.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future = cwActions.describeAlarmsAsync();\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"11. Get current data for new custom metric.\");\ntry {\nCompletableFuture future =\ncwActions.getCustomMetricDataAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\nBasics 769\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"12. Push data into the custom metric to trigger the alarm.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.addMetricDataForAlarmAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"13. Check the alarm state using the action\nDescribeAlarmsForMetric.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.checkForMetricAlarmAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nBasics 770\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"14. Get alarm history for the new alarm.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.getAlarmHistoryAsync(settings, myDate);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"15. Add an anomaly detector for the custom metric.\");\nlogger.info(\"\"\"\nAn anomaly detector is a feature that automatically detects unusual\npatterns or deviations in your\nmonitored metrics. It uses machine learning algorithms to analyze the\nhistorical behavior\nof your metrics and establish a baseline.\nThe anomaly detector then compares the current metric values against\nthis baseline and\nidentifies any anomalies or outliers that may indicate potential issues\nor unexpected changes\nin your system's performance or behavior.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nBasics 771\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture future =\ncwActions.addAnomalyDetectorAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"16. Describe current anomaly detectors.", "mimetype": "text/plain", "start_char_idx": 1169915, "end_char_idx": 1174223, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b207a3fc-9bcc-42b1-bd56-e1db4a50ab41": {"__data__": {"id_": "b207a3fc-9bcc-42b1-bd56-e1db4a50ab41", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b6fb1377-9005-403b-84c2-4fb3f12d09bf", "node_type": "1", "metadata": {}, "hash": "012e755910c60b9ee17d796d8240abf85e22fbb7490fe57fbd029d17031d8cb8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2cb90d0b-73ba-4cb0-bf67-0888fc6af683", "node_type": "1", "metadata": {}, "hash": "4a92f01c33f9c96acf6b1af510d2ec3be39c2ba57d9832d04132d75769b83298", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The anomaly detector then compares the current metric values against\nthis baseline and\nidentifies any anomalies or outliers that may indicate potential issues\nor unexpected changes\nin your system's performance or behavior.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nBasics 771\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture future =\ncwActions.addAnomalyDetectorAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"16. Describe current anomaly detectors.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\ncwActions.describeAnomalyDetectorsAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"17. Get a metric image for the custom metric.\");\ntry {\nCompletableFuture future =\ncwActions.downloadAndSaveMetricImageAsync(metricImage);\nfuture.join();\nBasics 772\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"18. Clean up the Amazon CloudWatch resources.\");\ntry {\nlogger.info(\". Delete the Dashboard.\");\nwaitForInputToContinue(scanner);\nCompletableFuture future =\ncwActions.deleteDashboardAsync(dashboardName);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\ntry {\nlogger.info(\"Delete the alarm.\");\nwaitForInputToContinue(scanner);\nCompletableFuture future =\ncwActions.deleteCWAlarmAsync(alarmName);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nBasics 773\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\ntry {\nlogger.info(\"Delete the anomaly detector.\");\nwaitForInputToContinue(scanner);\nCompletableFuture future =\ncwActions.deleteAnomalyDetectorAsync(settings);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof CloudWatchException cwEx) {\nlogger.info(\"CloudWatch error occurred: Error message: {}, Error\ncode {}\", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: {}\", rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"The Amazon CloudWatch example scenario is complete.\");\nlogger.info(DASHES);\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\n// Handle invalid input.\nBasics 774\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nA wrapper class for CloudWatch SDK methods.\npublic class CloudWatchActions {\nprivate static CloudWatchAsyncClient cloudWatchAsyncClient;\nprivate static final Logger logger =\nLoggerFactory.getLogger(CloudWatchActions.class);\n/**\n* Retrieves an asynchronous CloudWatch client instance.", "mimetype": "text/plain", "start_char_idx": 1173334, "end_char_idx": 1178011, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2cb90d0b-73ba-4cb0-bf67-0888fc6af683": {"__data__": {"id_": "2cb90d0b-73ba-4cb0-bf67-0888fc6af683", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b207a3fc-9bcc-42b1-bd56-e1db4a50ab41", "node_type": "1", "metadata": {}, "hash": "f59a54915f2d669f67a5df492102e80baf55a3cbb1cb2812d09e72740961e0c9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fc83aa8c-bd53-4fa1-81ba-da06c9ffe75e", "node_type": "1", "metadata": {}, "hash": "c381e5726600de4b2a823bc15262f5e6190514a33e953b0daadcc2cd4e8b4011", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nlogger.info(DASHES);\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\n// Handle invalid input.\nBasics 774\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nA wrapper class for CloudWatch SDK methods.\npublic class CloudWatchActions {\nprivate static CloudWatchAsyncClient cloudWatchAsyncClient;\nprivate static final Logger logger =\nLoggerFactory.getLogger(CloudWatchActions.class);\n/**\n* Retrieves an asynchronous CloudWatch client instance.\n*\n*

\n* This method ensures that the CloudWatch client is initialized with the\nfollowing configurations:\n*

    \n*
  • Maximum concurrency: 100
  • \n*
  • Connection timeout: 60 seconds
  • \n*
  • Read timeout: 60 seconds
  • \n*
  • Write timeout: 60 seconds
  • \n*
  • API call timeout: 2 minutes
  • \n*
  • API call attempt timeout: 90 seconds
  • \n*
  • Retry strategy: STANDARD
  • \n*
\n*

\n*\n* @return the asynchronous CloudWatch client instance\n*/\nprivate static CloudWatchAsyncClient getAsyncClient() {\nif (cloudWatchAsyncClient == null) {\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(100)\n.connectionTimeout(Duration.ofSeconds(60))\n.readTimeout(Duration.ofSeconds(60))\n.writeTimeout(Duration.ofSeconds(60))\n.build();\nBasics 775\nAWS SDK for Java 2.x Developer Guide for version 2.x\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2))\n.apiCallAttemptTimeout(Duration.ofSeconds(90))\n.retryStrategy(RetryMode.STANDARD)\n.build();\ncloudWatchAsyncClient = CloudWatchAsyncClient.builder()\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn cloudWatchAsyncClient;\n}\n/**\n* Deletes an Anomaly Detector.\n*\n* @param fileName the name of the file containing the Anomaly Detector\nconfiguration\n* @return a CompletableFuture that represents the asynchronous deletion of the\nAnomaly Detector\n*/\npublic CompletableFuture\ndeleteAnomalyDetectorAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser); // Return the root node\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nreturn readFileFuture.thenCompose(rootNode -> {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nBasics 776\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSingleMetricAnomalyDetector singleMetricAnomalyDetector =\nSingleMetricAnomalyDetector.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.stat(\"Maximum\")\n.build();\nDeleteAnomalyDetectorRequest request =\nDeleteAnomalyDetectorRequest.builder()\n.singleMetricAnomalyDetector(singleMetricAnomalyDetector)\n.build();\nreturn getAsyncClient().deleteAnomalyDetector(request);\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the Anomaly Detector\",\nexception);\n} else {\nlogger.info(\"Successfully deleted the Anomaly Detector.\");\n}\n});\n}\n/**\n* Deletes a CloudWatch alarm.\n*\n* @param alarmName the name of the alarm to be deleted\n* @return a {@link CompletableFuture} representing the asynchronous operation\nto delete the alarm\n* the {@link DeleteAlarmsResponse} is returned when the operation completes\nsuccessfully,\n* or a {@link RuntimeException} is thrown if the operation fails\n*/\npublic CompletableFuture deleteCWAlarmAsync(String\nalarmName) {\nDeleteAlarmsRequest request = DeleteAlarmsRequest.builder()\n.alarmNames(alarmName)\n.build();\nreturn getAsyncClient().deleteAlarms(request)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the alarm:{} \" +\nalarmName, exception);\nBasics 777\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else {\nlogger.info(\"Successfully deleted alarm {} \", alarmName);\n}\n});\n}\n/**\n* Deletes the specified dashboard.", "mimetype": "text/plain", "start_char_idx": 1177245, "end_char_idx": 1181657, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fc83aa8c-bd53-4fa1-81ba-da06c9ffe75e": {"__data__": {"id_": "fc83aa8c-bd53-4fa1-81ba-da06c9ffe75e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2cb90d0b-73ba-4cb0-bf67-0888fc6af683", "node_type": "1", "metadata": {}, "hash": "4a92f01c33f9c96acf6b1af510d2ec3be39c2ba57d9832d04132d75769b83298", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f53c6621-36db-41ea-acb2-aa9b0da17806", "node_type": "1", "metadata": {}, "hash": "9b43a055ef18ce93bb0851acc8d9c67986876d4d139de85c389f63f18ef53a6e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param alarmName the name of the alarm to be deleted\n* @return a {@link CompletableFuture} representing the asynchronous operation\nto delete the alarm\n* the {@link DeleteAlarmsResponse} is returned when the operation completes\nsuccessfully,\n* or a {@link RuntimeException} is thrown if the operation fails\n*/\npublic CompletableFuture deleteCWAlarmAsync(String\nalarmName) {\nDeleteAlarmsRequest request = DeleteAlarmsRequest.builder()\n.alarmNames(alarmName)\n.build();\nreturn getAsyncClient().deleteAlarms(request)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the alarm:{} \" +\nalarmName, exception);\nBasics 777\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else {\nlogger.info(\"Successfully deleted alarm {} \", alarmName);\n}\n});\n}\n/**\n* Deletes the specified dashboard.\n*\n* @param dashboardName the name of the dashboard to be deleted\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof deleting the dashboard\n* @throws RuntimeException if the dashboard deletion fails\n*/\npublic CompletableFuture deleteDashboardAsync(String\ndashboardName) {\nDeleteDashboardsRequest dashboardsRequest =\nDeleteDashboardsRequest.builder()\n.dashboardNames(dashboardName)\n.build();\nreturn getAsyncClient().deleteDashboards(dashboardsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the dashboard: \" +\ndashboardName, exception);\n} else {\nlogger.info(\"{} was successfully deleted.\", dashboardName);\n}\n});\n}\n/**\n* Retrieves and saves a custom metric image to a file.\n*\n* @param fileName the name of the file to save the metric image to\n* @return a {@link CompletableFuture} that completes when the image has been\nsaved to the file\n*/\npublic CompletableFuture downloadAndSaveMetricImageAsync(String fileName)\n{\nlogger.info(\"Getting Image data for custom metric.\");\nString myJSON = \"\"\"\nBasics 778\nAWS SDK for Java 2.x Developer Guide for version 2.x\n{\n\"title\": \"Example Metric Graph\",\n\"view\": \"timeSeries\",\n\"stacked \": false,\n\"period\": 10,\n\"width\": 1400,\n\"height\": 600,\n\"metrics\": [\n[\n\"AWS/Billing\",\n\"EstimatedCharges\",\n\"Currency\",\n\"USD\"\n]\n]\n}\n\"\"\";\nGetMetricWidgetImageRequest imageRequest =\nGetMetricWidgetImageRequest.builder()\n.metricWidget(myJSON)\n.build();\nreturn getAsyncClient().getMetricWidgetImage(imageRequest)\n.thenCompose(response -> {\nSdkBytes sdkBytes = response.metricWidgetImage();\nbyte[] bytes = sdkBytes.asByteArray();\nreturn CompletableFuture.runAsync(() -> {\ntry {\nFile outputFile = new File(fileName);\ntry (FileOutputStream outputStream = new\nFileOutputStream(outputFile)) {\noutputStream.write(bytes);\n}\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to write image to file\",\ne);\n}\n});\n})\n.whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error getting and saving metric\nimage\", exception);\nBasics 779\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else {\nlogger.info(\"Image data saved successfully to {}\", fileName);\n}\n});\n}\n/**\n* Describes the anomaly detectors based on the specified JSON file.", "mimetype": "text/plain", "start_char_idx": 1180791, "end_char_idx": 1183976, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f53c6621-36db-41ea-acb2-aa9b0da17806": {"__data__": {"id_": "f53c6621-36db-41ea-acb2-aa9b0da17806", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fc83aa8c-bd53-4fa1-81ba-da06c9ffe75e", "node_type": "1", "metadata": {}, "hash": "c381e5726600de4b2a823bc15262f5e6190514a33e953b0daadcc2cd4e8b4011", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d7d090e9-9588-4b8b-bf33-be8774ff8d22", "node_type": "1", "metadata": {}, "hash": "ebb237ab71f1fd23417385ca8f36be511840679742c2e10726413ffa1d56b1ac", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param fileName the name of the JSON file containing the custom metric\nnamespace and name\n* @return a {@link CompletableFuture} that completes when the anomaly detectors\nhave been described\n* @throws RuntimeException if there is a failure during the operation, such as\nwhen reading or parsing the JSON file,\n* or when describing the anomaly detectors\n*/\npublic CompletableFuture describeAnomalyDetectorsAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nreturn readFileFuture.thenCompose(rootNode -> {\ntry {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nDescribeAnomalyDetectorsRequest detectorsRequest =\nDescribeAnomalyDetectorsRequest.builder()\n.maxResults(10)\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nBasics 780\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn\ngetAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response ->\n{\nList anomalyDetectorList =\nresponse.anomalyDetectors();\nfor (AnomalyDetector detector : anomalyDetectorList) {\nlogger.info(\"Metric name: {} \",\ndetector.singleMetricAnomalyDetector().metricName());\nlogger.info(\"State: {} \", detector.stateValue());\n}\n});\n} catch (RuntimeException e) {\nthrow new RuntimeException(\"Failed to describe anomaly detectors\",\ne);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error describing anomaly detectors\",\nexception);\n}\n});\n}\n/**\n* Adds an anomaly detector for the given file.\n*\n* @param fileName the name of the file containing the anomaly detector\nconfiguration\n* @return a {@link CompletableFuture} that completes when the anomaly detector\nhas been added\n*/\npublic CompletableFuture addAnomalyDetectorAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser); // Return the root node\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nBasics 781\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn readFileFuture.thenCompose(rootNode -> {\ntry {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nSingleMetricAnomalyDetector singleMetricAnomalyDetector =\nSingleMetricAnomalyDetector.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.stat(\"Maximum\")\n.build();\nPutAnomalyDetectorRequest anomalyDetectorRequest =\nPutAnomalyDetectorRequest.builder()\n.singleMetricAnomalyDetector(singleMetricAnomalyDetector)\n.build();\nreturn\ngetAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response ->\n{\nlogger.info(\"Added anomaly detector for metric {}\",\ncustomMetricName);\n});\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to create anomaly detector\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error adding anomaly detector\",\nexception);\n}\n});\n}\n/**\n* Retrieves the alarm history for a given alarm name and date range.\n*\n* @param fileName the path to the JSON file containing the alarm name\n* @param date the date to start the alarm history search (in the format\n\"yyyy-MM-dd'T'HH:mm:ss'Z'\")\nBasics 782\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@code CompletableFuture} that completes when the alarm\nhistory has been retrieved and processed\n*/\npublic CompletableFuture getAlarmHistoryAsync(String fileName, String\ndate) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.findValue(\"exampleAlarmName\").asText(); // Return\nalarmName from the JSON file\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\n// Use the alarm name to describe alarm history with a paginator.", "mimetype": "text/plain", "start_char_idx": 1183977, "end_char_idx": 1188478, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d7d090e9-9588-4b8b-bf33-be8774ff8d22": {"__data__": {"id_": "d7d090e9-9588-4b8b-bf33-be8774ff8d22", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f53c6621-36db-41ea-acb2-aa9b0da17806", "node_type": "1", "metadata": {}, "hash": "9b43a055ef18ce93bb0851acc8d9c67986876d4d139de85c389f63f18ef53a6e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f0efda7f-74c7-46ba-8676-19d8ac051f22", "node_type": "1", "metadata": {}, "hash": "72472aedf238c8d2db0521b22a8706188223e86bff308e936198e7dfb645a588", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return readFileFuture.thenCompose(alarmName -> {\ntry {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\nDescribeAlarmHistoryRequest historyRequest =\nDescribeAlarmHistoryRequest.builder()\n.startDate(start)\n.endDate(endDate)\n.alarmName(alarmName)\n.historyItemType(HistoryItemType.ACTION)\n.build();\n// Use the paginator to paginate through alarm history pages.\nDescribeAlarmHistoryPublisher historyPublisher =\ngetAsyncClient().describeAlarmHistoryPaginator(historyRequest);\nCompletableFuture future = historyPublisher\n.subscribe(response -> response.alarmHistoryItems().forEach(item\n-> {\nlogger.info(\"History summary: {}\", item.historySummary());\nlogger.info(\"Timestamp: {}\", item.timestamp());\n}))\n.whenComplete((result, exception) -> {\nif (exception != null) {\nBasics 783\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.error(\"Error occurred while getting alarm\nhistory: \" + exception.getMessage(), exception);\n} else {\nlogger.info(\"Successfully retrieved all alarm\nhistory.\");\n}\n});\n// Return the future to the calling code for further handling\nreturn future;\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to process alarm history\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error completing alarm history\nprocessing\", exception);\n}\n});\n}\n/**\n* Checks for a metric alarm in AWS CloudWatch.\n*\n* @param fileName the name of the file containing the JSON configuration for\nthe custom metric\n* @return a {@link CompletableFuture} that completes when the check for the\nmetric alarm is complete\n*/\npublic CompletableFuture checkForMetricAlarmAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\nBasics 784\nAWS SDK for Java 2.x Developer Guide for version 2.x\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nDescribeAlarmsForMetricRequest metricRequest =\nDescribeAlarmsForMetricRequest.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nreturn checkForAlarmAsync(metricRequest, customMetricName, 10);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to parse JSON content\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error checking metric alarm\",\nexception);\n}\n});\n}\n// Recursive method to check for the alarm.\n/**\n* Checks for the existence of an alarm asynchronously for the specified metric.\n*\n* @param metricRequest the request to describe the alarms for the specified\nmetric\n* @param customMetricName the name of the custom metric to check for an alarm\n* @param retries the number of retries to perform if no alarm is found\n* @return a {@link CompletableFuture} that completes when an alarm is found or\nthe maximum number of retries has been reached\n*/\nBasics 785\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static CompletableFuture\ncheckForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String\ncustomMetricName, int retries) {\nif (retries == 0) {\nreturn CompletableFuture.completedFuture(null).thenRun(() ->\nlogger.info(\"No Alarm state found for {} after 10 retries.\",\ncustomMetricName)\n);\n}\nreturn\n(getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> {\nif (response.hasMetricAlarms()) {\nlogger.info(\"Alarm state found for {}\", customMetricName);\nreturn CompletableFuture.completedFuture(null); // Alarm found,\ncomplete the future\n} else {\nreturn CompletableFuture.runAsync(() -> {\ntry {\nThread.sleep(20000);\nlogger.info(\".\");\n} catch (InterruptedException e) {\nthrow new RuntimeException(\"Interrupted while waiting to\nretry\", e);\n}\n}).thenCompose(v -> checkForAlarmAsync(metricRequest,\ncustomMetricName, retries - 1)); // Recursive call\n}\n}));\n}\n/**\n* Adds metric data for an alarm asynchronously.", "mimetype": "text/plain", "start_char_idx": 1188479, "end_char_idx": 1192899, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f0efda7f-74c7-46ba-8676-19d8ac051f22": {"__data__": {"id_": "f0efda7f-74c7-46ba-8676-19d8ac051f22", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d7d090e9-9588-4b8b-bf33-be8774ff8d22", "node_type": "1", "metadata": {}, "hash": "ebb237ab71f1fd23417385ca8f36be511840679742c2e10726413ffa1d56b1ac", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "08094d77-ed64-40a6-94a9-e14bdf7f8650", "node_type": "1", "metadata": {}, "hash": "d8b3fb9d25a92b964d532dbf726b6e3002ce64b19bd79ed1d7668070463d664f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\",\ncustomMetricName)\n);\n}\nreturn\n(getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> {\nif (response.hasMetricAlarms()) {\nlogger.info(\"Alarm state found for {}\", customMetricName);\nreturn CompletableFuture.completedFuture(null); // Alarm found,\ncomplete the future\n} else {\nreturn CompletableFuture.runAsync(() -> {\ntry {\nThread.sleep(20000);\nlogger.info(\".\");\n} catch (InterruptedException e) {\nthrow new RuntimeException(\"Interrupted while waiting to\nretry\", e);\n}\n}).thenCompose(v -> checkForAlarmAsync(metricRequest,\ncustomMetricName, retries - 1)); // Recursive call\n}\n}));\n}\n/**\n* Adds metric data for an alarm asynchronously.\n*\n* @param fileName the name of the JSON file containing the metric data\n* @return a CompletableFuture that asynchronously returns the\nPutMetricDataResponse\n*/\npublic CompletableFuture\naddMetricDataForAlarmAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nBasics 786\nAWS SDK for Java 2.x Developer Guide for version 2.x\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nInstant instant = Instant.now();\n// Create MetricDatum objects.\nMetricDatum datum1 = MetricDatum.builder()\n.metricName(customMetricName)\n.unit(StandardUnit.NONE)\n.value(1001.00)\n.timestamp(instant)\n.build();\nMetricDatum datum2 = MetricDatum.builder()\n.metricName(customMetricName)\n.unit(StandardUnit.NONE)\n.value(1002.00)\n.timestamp(instant)\n.build();\nList metricDataList = new ArrayList<>();\nmetricDataList.add(datum1);\nmetricDataList.add(datum2);\n// Build the PutMetricData request.\nPutMetricDataRequest request = PutMetricDataRequest.builder()\n.namespace(customMetricNamespace)\n.metricData(metricDataList)\nBasics 787\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n// Send the request asynchronously.\nreturn getAsyncClient().putMetricData(request);\n} catch (IOException e) {\nCompletableFuture failedFuture = new\nCompletableFuture<>();\nfailedFuture.completeExceptionally(new RuntimeException(\"Failed to\nparse JSON content\", e));\nreturn failedFuture;\n}\n}).whenComplete((response, exception) -> {\nif (exception != null) {\nlogger.error(\"Failed to put metric data: \" + exception.getMessage(),\nexception);\n} else {\nlogger.info(\"Added metric values for metric.\");\n}\n});\n}\n/**\n* Retrieves custom metric data from the AWS CloudWatch service.\n*\n* @param fileName the name of the file containing the custom metric information\n* @return a {@link CompletableFuture} that completes when the metric data has\nbeen retrieved\n*/\npublic CompletableFuture getCustomMetricDataAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\n// Read values from the JSON file.\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\nBasics 788\nAWS SDK for Java 2.x Developer Guide for version 2.x\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\n// Parse the JSON string to extract relevant values.\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\n// Set the current time and date range for metric query.", "mimetype": "text/plain", "start_char_idx": 1192239, "end_char_idx": 1196408, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "08094d77-ed64-40a6-94a9-e14bdf7f8650": {"__data__": {"id_": "08094d77-ed64-40a6-94a9-e14bdf7f8650", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f0efda7f-74c7-46ba-8676-19d8ac051f22", "node_type": "1", "metadata": {}, "hash": "72472aedf238c8d2db0521b22a8706188223e86bff308e936198e7dfb645a588", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "eee336ac-bf2c-4fff-8e1f-aa8cc7a050ef", "node_type": "1", "metadata": {}, "hash": "519a29a22e801fee2113c257f43da12a88650a5ac89e95ef4aba8b16ff62a475", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "JsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\nBasics 788\nAWS SDK for Java 2.x Developer Guide for version 2.x\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\n// Parse the JSON string to extract relevant values.\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\n// Set the current time and date range for metric query.\nInstant nowDate = Instant.now();\nlong hours = 1;\nlong minutes = 30;\nInstant endTime = nowDate.plus(hours,\nChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES);\nMetric met = Metric.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nMetricStat metStat = MetricStat.builder()\n.stat(\"Maximum\")\n.period(60) // Assuming period in seconds\n.metric(met)\n.build();\nMetricDataQuery dataQuery = MetricDataQuery.builder()\n.metricStat(metStat)\n.id(\"foo2\")\n.returnData(true)\n.build();\nList dq = new ArrayList<>();\ndq.add(dataQuery);\nGetMetricDataRequest getMetricDataRequest =\nGetMetricDataRequest.builder()\n.maxDatapoints(10)\n.scanBy(ScanBy.TIMESTAMP_DESCENDING)\n.startTime(nowDate)\nBasics 789\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.endTime(endTime)\n.metricDataQueries(dq)\n.build();\n// Call the async method for CloudWatch data retrieval.\nreturn getAsyncClient().getMetricData(getMetricDataRequest);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to parse JSON content\", e);\n}\n}).thenAccept(response -> {\nList data = response.metricDataResults();\nfor (MetricDataResult item : data) {\nlogger.info(\"The label is: {}\", item.label());\nlogger.info(\"The status code is: {}\", item.statusCode().toString());\n}\n}).exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to get metric data\", exception);\n});\n}\n/**\n* Describes the CloudWatch alarms of the 'METRIC_ALARM' type.\n*\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of describing the CloudWatch alarms. The future completes when the\n* operation is finished, either successfully or with an error.\n*/\npublic CompletableFuture describeAlarmsAsync() {\nList typeList = new ArrayList<>();\ntypeList.add(AlarmType.METRIC_ALARM);\nDescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder()\n.alarmTypes(typeList)\n.maxRecords(10)\n.build();\nreturn getAsyncClient().describeAlarms(alarmsRequest)\n.thenAccept(response -> {\nList alarmList = response.metricAlarms();\nfor (MetricAlarm alarm : alarmList) {\nlogger.info(\"Alarm name: {}\", alarm.alarmName());\nlogger.info(\"Alarm description: {} \", alarm.alarmDescription());\nBasics 790\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n})\n.whenComplete((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to describe alarms: {}\", ex.getMessage());\n} else {\nlogger.info(\"Successfully described alarms.\");\n}\n});\n}\n/**\n* Creates an alarm based on the configuration provided in a JSON file.\n*\n* @param fileName the name of the JSON file containing the alarm configuration\n* @return a CompletableFuture that represents the asynchronous operation of\ncreating the alarm\n* @throws RuntimeException if an exception occurs while reading the JSON file\nor creating the alarm\n*/\npublic CompletableFuture createAlarmAsync(String fileName) {\ncom.fasterxml.jackson.databind.JsonNode rootNode;\ntry {\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\nrootNode = new ObjectMapper().readTree(parser);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read the alarm configuration\nfile\", e);\n}\n// Extract values from the JSON node.\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName = rootNode.findValue(\"customMetricName\").asText();\nString alarmName = rootNode.findValue(\"exampleAlarmName\").asText();\nString emailTopic = rootNode.findValue(\"emailTopic\").asText();\nString accountId = rootNode.findValue(\"accountId\").asText();\nString region = rootNode.findValue(\"region\").asText();\n// Create a List for alarm actions.", "mimetype": "text/plain", "start_char_idx": 1195601, "end_char_idx": 1200061, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "eee336ac-bf2c-4fff-8e1f-aa8cc7a050ef": {"__data__": {"id_": "eee336ac-bf2c-4fff-8e1f-aa8cc7a050ef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "08094d77-ed64-40a6-94a9-e14bdf7f8650", "node_type": "1", "metadata": {}, "hash": "d8b3fb9d25a92b964d532dbf726b6e3002ce64b19bd79ed1d7668070463d664f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3c9831bd-35a9-44af-9c46-848cc80f9ea0", "node_type": "1", "metadata": {}, "hash": "f880a6300bcd559465f77489d89452d5f5dbb0e657090078f6f3f002a40669e7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "String customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName = rootNode.findValue(\"customMetricName\").asText();\nString alarmName = rootNode.findValue(\"exampleAlarmName\").asText();\nString emailTopic = rootNode.findValue(\"emailTopic\").asText();\nString accountId = rootNode.findValue(\"accountId\").asText();\nString region = rootNode.findValue(\"region\").asText();\n// Create a List for alarm actions.\nList alarmActions = new ArrayList<>();\nalarmActions.add(\"arn:aws:sns:\" + region + \":\" + accountId + \":\" +\nemailTopic);\nBasics 791\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder()\n.alarmActions(alarmActions)\n.alarmDescription(\"Example metric alarm\")\n.alarmName(alarmName)\n.comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD)\n.threshold(100.00)\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.evaluationPeriods(1)\n.period(10)\n.statistic(\"Maximum\")\n.datapointsToAlarm(1)\n.treatMissingData(\"ignore\")\n.build();\n// Call the putMetricAlarm asynchronously and handle the result.\nreturn getAsyncClient().putMetricAlarm(alarmRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to create alarm: {}\", ex.getMessage());\nthrow new RuntimeException(\"Failed to create alarm\", ex);\n} else {\nlogger.info(\"{} was successfully created!\", alarmName);\nreturn alarmName;\n}\n});\n}\n/**\n* Adds a metric to a dashboard asynchronously.\n*\n* @param fileName the name of the file containing the dashboard content\n* @param dashboardName the name of the dashboard to be updated\n* @return a {@link CompletableFuture} representing the asynchronous operation,\nwhich will complete with a\n* {@link PutDashboardResponse} when the dashboard is successfully updated\n*/\npublic CompletableFuture addMetricToDashboardAsync(String\nfileName, String dashboardName) {\nString dashboardBody;\ntry {\ndashboardBody = readFileAsString(fileName);\n} catch (IOException e) {\nBasics 792\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrow new RuntimeException(\"Failed to read the dashboard file\", e);\n}\nPutDashboardRequest dashboardRequest = PutDashboardRequest.builder()\n.dashboardName(dashboardName)\n.dashboardBody(dashboardBody)\n.build();\nreturn getAsyncClient().putDashboard(dashboardRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to update dashboard: {}\", ex.getMessage());\nthrow new RuntimeException(\"Error updating dashboard\", ex);\n} else {\nlogger.info(\"{} was successfully updated.\", dashboardName);\nreturn response;\n}\n});\n}\n/**\n* Creates a new custom metric.\n*\n* @param dataPoint the data point to be added to the custom metric\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof adding the custom metric\n*/\npublic CompletableFuture\ncreateNewCustomMetricAsync(Double dataPoint) {\nDimension dimension = Dimension.builder()\n.name(\"UNIQUE_PAGES\")\n.value(\"URLS\")\n.build();\n// Set an Instant object for the current time in UTC.\nString time =\nZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);\nInstant instant = Instant.parse(time);\n// Create the MetricDatum.\nMetricDatum datum = MetricDatum.builder()\n.metricName(\"PAGES_VISITED\")\n.unit(StandardUnit.NONE)\n.value(dataPoint)\nBasics 793\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.timestamp(instant)\n.dimensions(dimension)\n.build();\nPutMetricDataRequest request = PutMetricDataRequest.builder()\n.namespace(\"SITE/TRAFFIC\")\n.metricData(datum)\n.build();\nreturn getAsyncClient().putMetricData(request)\n.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Error adding custom metric\", ex);\n} else {\nlogger.info(\"Successfully added metric values for\nPAGES_VISITED.\");\n}\n});\n}\n/**\n* Lists the available dashboards.\n*\n* @return a {@link CompletableFuture} that completes when the operation is\nfinished.\n* The future will complete exceptionally if an error occurs while listing the\ndashboards.", "mimetype": "text/plain", "start_char_idx": 1199619, "end_char_idx": 1203649, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3c9831bd-35a9-44af-9c46-848cc80f9ea0": {"__data__": {"id_": "3c9831bd-35a9-44af-9c46-848cc80f9ea0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "eee336ac-bf2c-4fff-8e1f-aa8cc7a050ef", "node_type": "1", "metadata": {}, "hash": "519a29a22e801fee2113c257f43da12a88650a5ac89e95ef4aba8b16ff62a475", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5d51b3bb-53a9-45a0-9132-39e4d2c14b70", "node_type": "1", "metadata": {}, "hash": "1cfd14529a84d9d8cf3ff1569bfac10b389e9063d3829e9100ab4f5ac1204be6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "MetricDatum datum = MetricDatum.builder()\n.metricName(\"PAGES_VISITED\")\n.unit(StandardUnit.NONE)\n.value(dataPoint)\nBasics 793\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.timestamp(instant)\n.dimensions(dimension)\n.build();\nPutMetricDataRequest request = PutMetricDataRequest.builder()\n.namespace(\"SITE/TRAFFIC\")\n.metricData(datum)\n.build();\nreturn getAsyncClient().putMetricData(request)\n.whenComplete((response, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Error adding custom metric\", ex);\n} else {\nlogger.info(\"Successfully added metric values for\nPAGES_VISITED.\");\n}\n});\n}\n/**\n* Lists the available dashboards.\n*\n* @return a {@link CompletableFuture} that completes when the operation is\nfinished.\n* The future will complete exceptionally if an error occurs while listing the\ndashboards.\n*/\npublic CompletableFuture listDashboardsAsync() {\nListDashboardsRequest listDashboardsRequest =\nListDashboardsRequest.builder().build();\nListDashboardsPublisher paginator =\ngetAsyncClient().listDashboardsPaginator(listDashboardsRequest);\nreturn paginator.subscribe(response -> {\nresponse.dashboardEntries().forEach(entry -> {\nlogger.info(\"Dashboard name is: {} \", entry.dashboardName());\nlogger.info(\"Dashboard ARN is: {} \", entry.dashboardArn());\n});\n}).exceptionally(ex -> {\nlogger.info(\"Failed to list dashboards: {} \", ex.getMessage());\nthrow new RuntimeException(\"Error occurred while listing dashboards\",\nex);\n});\n}\nBasics 794\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Creates a new dashboard with the specified name and metrics from the given\nfile.\n*\n* @param dashboardName the name of the dashboard to be created\n* @param fileName the name of the file containing the dashboard body\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof creating the dashboard\n* @throws IOException if there is an error reading the dashboard body from the\nfile\n*/\npublic CompletableFuture\ncreateDashboardWithMetricsAsync(String dashboardName, String fileName) throws\nIOException {\nString dashboardBody = readFileAsString(fileName);\nPutDashboardRequest dashboardRequest = PutDashboardRequest.builder()\n.dashboardName(dashboardName)\n.dashboardBody(dashboardBody)\n.build();\nreturn getAsyncClient().putDashboard(dashboardRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to create dashboard: {}\", ex.getMessage());\nthrow new RuntimeException(\"Dashboard creation failed\", ex);\n} else {\n// Handle the normal response case\nlogger.info(\"{} was successfully created.\", dashboardName);\nList messages =\nresponse.dashboardValidationMessages();\nif (messages.isEmpty()) {\nlogger.info(\"There are no messages in the new Dashboard.\");\n} else {\nfor (DashboardValidationMessage message : messages) {\nlogger.info(\"Message: {}\", message.message());\n}\n}\nreturn response; // Return the response for further use\n}\n});\n}\nBasics 795\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Retrieves the metric statistics for the \"EstimatedCharges\" metric in the\n\"AWS/Billing\" namespace.\n*\n* @param costDateWeek the start date for the metric statistics, in the format\nof an ISO-8601 date string (e.g., \"2023-04-05\")\n* @return a {@link CompletableFuture} that, when completed, contains the {@link\nGetMetricStatisticsResponse} with the retrieved metric statistics\n* @throws RuntimeException if the metric statistics cannot be retrieved\nsuccessfully\n*/\npublic CompletableFuture\ngetMetricStatisticsAsync(String costDateWeek) {\nInstant start = Instant.parse(costDateWeek);\nInstant endDate = Instant.now();\n// Define dimension\nDimension dimension = Dimension.builder()\n.name(\"Currency\")\n.value(\"USD\")\n.build();\nList dimensionList = new ArrayList<>();\ndimensionList.add(dimension);\nGetMetricStatisticsRequest statisticsRequest =\nGetMetricStatisticsRequest.builder()\n.metricName(\"EstimatedCharges\")\n.namespace(\"AWS/Billing\")\n.dimensions(dimensionList)\n.statistics(Statistic.MAXIMUM)\n.startTime(start)\n.endTime(endDate)\n.period(86400) // One day period\n.build();\nreturn getAsyncClient().getMetricStatistics(statisticsRequest)\n.whenComplete((response, exception) -> {\nif (response != null) {\nList data = response.datapoints();\nif (!data.isEmpty()) {\nfor (Datapoint datapoint : data) {\nBasics 796\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Timestamp: {} Maximum value: {})\",\ndatapoint.timestamp(), datapoint.maximum());\n}\n} else {\nlogger.info(\"The returned data list is empty\");\n}\n} else {\nthrow new RuntimeException(\"Failed to get metric statistics: \" +\nexception.getMessage(), exception);\n}\n});\n}\n/**\n* Retrieves and displays metric statistics for the specified parameters.", "mimetype": "text/plain", "start_char_idx": 1202840, "end_char_idx": 1207581, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5d51b3bb-53a9-45a0-9132-39e4d2c14b70": {"__data__": {"id_": "5d51b3bb-53a9-45a0-9132-39e4d2c14b70", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3c9831bd-35a9-44af-9c46-848cc80f9ea0", "node_type": "1", "metadata": {}, "hash": "f880a6300bcd559465f77489d89452d5f5dbb0e657090078f6f3f002a40669e7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ebf5c6bf-47cc-4af6-961c-f5a4b28161c9", "node_type": "1", "metadata": {}, "hash": "a8b231b2b791d8ad20cd1b8496ab5da5ab3563b8abc368d5cc914fab22f0c0dd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param nameSpace the namespace for the metric\n* @param metVal the name of the metric\n* @param metricOption the statistic to retrieve for the metric (e.g.,\n\"Maximum\", \"Average\")\n* @param date the date for which to retrieve the metric statistics, in\nthe format \"yyyy-MM-dd'T'HH:mm:ss'Z'\"\n* @param myDimension the dimension(s) to filter the metric statistics by\n* @return a {@link CompletableFuture} that completes when the metric statistics\nhave been retrieved and displayed\n*/\npublic CompletableFuture\ngetAndDisplayMetricStatisticsAsync(String nameSpace, String metVal,\nString metricOption, String date, Dimension myDimension) {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\n// Building the request for metric statistics.\nGetMetricStatisticsRequest statisticsRequest =\nGetMetricStatisticsRequest.builder()\n.endTime(endDate)\n.startTime(start)\n.dimensions(myDimension)\n.metricName(metVal)\n.namespace(nameSpace)\n.period(86400) // 1 day period\nBasics 797\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.statistics(Statistic.fromValue(metricOption))\n.build();\nreturn getAsyncClient().getMetricStatistics(statisticsRequest)\n.whenComplete((response, exception) -> {\nif (response != null) {\nList data = response.datapoints();\nif (!data.isEmpty()) {\nfor (Datapoint datapoint : data) {\nlogger.info(\"Timestamp: {} Maximum value: {}\",\ndatapoint.timestamp(), datapoint.maximum());\n}\n} else {\nlogger.info(\"The returned data list is empty\");\n}\n} else {\nlogger.info(\"Failed to get metric statistics: {} \",\nexception.getMessage());\n}\n})\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Error while getting metric statistics: \"\n+ exception.getMessage(), exception);\n});\n}\n/**\n* Retrieves a list of metric names for the specified namespace.\n*\n* @param namespace the namespace for which to retrieve the metric names\n* @return a {@link CompletableFuture} that, when completed, contains an {@link\nArrayList} of\n* the metric names in the specified namespace\n* @throws RuntimeException if an error occurs while listing the metrics\n*/\npublic CompletableFuture> listMetsAsync(String namespace) {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.build();\nListMetricsPublisher metricsPaginator =\ngetAsyncClient().listMetricsPaginator(request);\nSet metSet = new HashSet<>();\nBasics 798\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture future = metricsPaginator.subscribe(response -> {\nresponse.metrics().forEach(metric -> {\nString metricName = metric.metricName();\nmetSet.add(metricName);\n});\n});\nreturn future\n.thenApply(ignored -> new ArrayList<>(metSet))\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to list metrics: \" +\nexception.getMessage(), exception);\n});\n}\n/**\n* Lists the available namespaces for the current AWS account.\n*\n* @return a {@link CompletableFuture} that, when completed, contains an {@link\nArrayList} of the available namespace names.\n* @throws RuntimeException if an error occurs while listing the namespaces.\n*/\npublic CompletableFuture> listNameSpacesAsync() {\nArrayList nameSpaceList = new ArrayList<>();\nListMetricsRequest request = ListMetricsRequest.builder().build();\nListMetricsPublisher metricsPaginator =\ngetAsyncClient().listMetricsPaginator(request);\nCompletableFuture future = metricsPaginator.subscribe(response -> {\nresponse.metrics().forEach(metric -> {\nString namespace = metric.namespace();\nif (!nameSpaceList.contains(namespace)) {\nnameSpaceList.add(namespace);\n}\n});\n});\nreturn future\n.thenApply(ignored -> nameSpaceList)\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to list namespaces: \" +\nexception.getMessage(), exception);\n});\n}\nBasics 799\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Retrieves the specific metric asynchronously.", "mimetype": "text/plain", "start_char_idx": 1207582, "end_char_idx": 1211485, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ebf5c6bf-47cc-4af6-961c-f5a4b28161c9": {"__data__": {"id_": "ebf5c6bf-47cc-4af6-961c-f5a4b28161c9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5d51b3bb-53a9-45a0-9132-39e4d2c14b70", "node_type": "1", "metadata": {}, "hash": "1cfd14529a84d9d8cf3ff1569bfac10b389e9063d3829e9100ab4f5ac1204be6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fdcec42b-0525-4799-b28f-4e8c3f085c59", "node_type": "1", "metadata": {}, "hash": "b195995556c126959e5849b89b149f93e4319d17b578e876e013c1114ffbc06f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @return a {@link CompletableFuture} that, when completed, contains an {@link\nArrayList} of the available namespace names.\n* @throws RuntimeException if an error occurs while listing the namespaces.\n*/\npublic CompletableFuture> listNameSpacesAsync() {\nArrayList nameSpaceList = new ArrayList<>();\nListMetricsRequest request = ListMetricsRequest.builder().build();\nListMetricsPublisher metricsPaginator =\ngetAsyncClient().listMetricsPaginator(request);\nCompletableFuture future = metricsPaginator.subscribe(response -> {\nresponse.metrics().forEach(metric -> {\nString namespace = metric.namespace();\nif (!nameSpaceList.contains(namespace)) {\nnameSpaceList.add(namespace);\n}\n});\n});\nreturn future\n.thenApply(ignored -> nameSpaceList)\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to list namespaces: \" +\nexception.getMessage(), exception);\n});\n}\nBasics 799\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Retrieves the specific metric asynchronously.\n*\n* @param namespace the namespace of the metric to retrieve\n* @return a CompletableFuture that completes with the first dimension of the\nfirst metric found in the specified namespace,\n* or throws a RuntimeException if an error occurs or no metrics or dimensions\nare found\n*/\npublic CompletableFuture getSpecificMetAsync(String namespace) {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.build();\nreturn getAsyncClient().listMetrics(request).handle((response, exception) ->\n{\nif (exception != null) {\nlogger.info(\"Error occurred while listing metrics: {} \",\nexception.getMessage());\nthrow new RuntimeException(\"Failed to retrieve specific metric\ndimension\", exception);\n} else {\nList myList = response.metrics();\nif (!myList.isEmpty()) {\nMetric metric = myList.get(0);\nif (!metric.dimensions().isEmpty()) {\nreturn metric.dimensions().get(0); // Return the first\ndimension\n}\n}\nthrow new RuntimeException(\"No metrics or dimensions found\");\n}\n});\n}\npublic static String readFileAsString(String file) throws IOException {\nreturn new String(Files.readAllBytes(Paths.get(file)));\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 DeleteAlarms\nBasics 800\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 DeleteAnomalyDetector\n\u2022 DeleteDashboards\n\u2022 DescribeAlarmHistory\n\u2022 DescribeAlarms\n\u2022 DescribeAlarmsForMetric\n\u2022 DescribeAnomalyDetectors\n\u2022 GetMetricData\n\u2022 GetMetricStatistics\n\u2022 GetMetricWidgetImage\n\u2022 ListMetrics\n\u2022 PutAnomalyDetector\n\u2022 PutDashboard\n\u2022 PutMetricAlarm\n\u2022 PutMetricData\nActions\nDeleteAlarms\nThe following code example shows how to use DeleteAlarms.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes a CloudWatch alarm.\n*\n* @param alarmName the name of the alarm to be deleted\n* @return a {@link CompletableFuture} representing the asynchronous operation\nto delete the alarm\nActions 801\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* the {@link DeleteAlarmsResponse} is returned when the operation completes\nsuccessfully,\n* or a {@link RuntimeException} is thrown if the operation fails\n*/\npublic CompletableFuture deleteCWAlarmAsync(String\nalarmName) {\nDeleteAlarmsRequest request = DeleteAlarmsRequest.builder()\n.alarmNames(alarmName)\n.build();\nreturn getAsyncClient().deleteAlarms(request)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the alarm:{} \" +\nalarmName, exception);\n} else {\nlogger.info(\"Successfully deleted alarm {} \", alarmName);\n}\n});\n}\n\u2022 For API details, see DeleteAlarms in AWS SDK for Java 2.x API Reference.\nDeleteAnomalyDetector\nThe following code example shows how to use DeleteAnomalyDetector.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes an Anomaly Detector.", "mimetype": "text/plain", "start_char_idx": 1210473, "end_char_idx": 1214481, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fdcec42b-0525-4799-b28f-4e8c3f085c59": {"__data__": {"id_": "fdcec42b-0525-4799-b28f-4e8c3f085c59", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ebf5c6bf-47cc-4af6-961c-f5a4b28161c9", "node_type": "1", "metadata": {}, "hash": "a8b231b2b791d8ad20cd1b8496ab5da5ab3563b8abc368d5cc914fab22f0c0dd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a3b2c513-940e-4543-8974-b263e5d920cf", "node_type": "1", "metadata": {}, "hash": "538aec31cb326b7d24b696d0d2ea6dde261e34bfd01f738ee59af86a4f3f4648", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteAnomalyDetector\nThe following code example shows how to use DeleteAnomalyDetector.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes an Anomaly Detector.\n*\n* @param fileName the name of the file containing the Anomaly Detector\nconfiguration\nActions 802\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a CompletableFuture that represents the asynchronous deletion of the\nAnomaly Detector\n*/\npublic CompletableFuture\ndeleteAnomalyDetectorAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser); // Return the root node\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nreturn readFileFuture.thenCompose(rootNode -> {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nSingleMetricAnomalyDetector singleMetricAnomalyDetector =\nSingleMetricAnomalyDetector.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.stat(\"Maximum\")\n.build();\nDeleteAnomalyDetectorRequest request =\nDeleteAnomalyDetectorRequest.builder()\n.singleMetricAnomalyDetector(singleMetricAnomalyDetector)\n.build();\nreturn getAsyncClient().deleteAnomalyDetector(request);\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the Anomaly Detector\",\nexception);\n} else {\nlogger.info(\"Successfully deleted the Anomaly Detector.\");\n}\n});\n}\nActions 803\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see DeleteAnomalyDetector in AWS SDK for Java 2.x API Reference.\nDeleteDashboards\nThe following code example shows how to use DeleteDashboards.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes the specified dashboard.\n*\n* @param dashboardName the name of the dashboard to be deleted\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof deleting the dashboard\n* @throws RuntimeException if the dashboard deletion fails\n*/\npublic CompletableFuture deleteDashboardAsync(String\ndashboardName) {\nDeleteDashboardsRequest dashboardsRequest =\nDeleteDashboardsRequest.builder()\n.dashboardNames(dashboardName)\n.build();\nreturn getAsyncClient().deleteDashboards(dashboardsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the dashboard: \" +\ndashboardName, exception);\n} else {\nlogger.info(\"{} was successfully deleted.\", dashboardName);\n}\n});\n}\nActions 804\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see DeleteDashboards in AWS SDK for Java 2.x API Reference.\nDescribeAlarmHistory\nThe following code example shows how to use DescribeAlarmHistory.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves the alarm history for a given alarm name and date range.\n*\n* @param fileName the path to the JSON file containing the alarm name\n* @param date the date to start the alarm history search (in the format\n\"yyyy-MM-dd'T'HH:mm:ss'Z'\")\n* @return a {@code CompletableFuture} that completes when the alarm\nhistory has been retrieved and processed\n*/\npublic CompletableFuture getAlarmHistoryAsync(String fileName, String\ndate) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.findValue(\"exampleAlarmName\").asText(); // Return\nalarmName from the JSON file\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nActions 805\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Use the alarm name to describe alarm history with a paginator.\nreturn readFileFuture.thenCompose(alarmName -> {\ntry {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\nDescribeAlarmHistoryRequest historyRequest =\nDescribeAlarmHistoryRequest.builder()\n.startDate(start)\n.endDate(endDate)\n.alarmName(alarmName)\n.historyItemType(HistoryItemType.ACTION)\n.build();\n// Use the paginator to paginate through alarm history pages.", "mimetype": "text/plain", "start_char_idx": 1214217, "end_char_idx": 1218899, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a3b2c513-940e-4543-8974-b263e5d920cf": {"__data__": {"id_": "a3b2c513-940e-4543-8974-b263e5d920cf", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fdcec42b-0525-4799-b28f-4e8c3f085c59", "node_type": "1", "metadata": {}, "hash": "b195995556c126959e5849b89b149f93e4319d17b578e876e013c1114ffbc06f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7882b2b7-8d74-4b75-a080-bc7021a9eff6", "node_type": "1", "metadata": {}, "hash": "05dba7e1135cf59a1fc33f2029ae9e5f86d0d647e3d39f9b50bc6b7aeac62afe", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return readFileFuture.thenCompose(alarmName -> {\ntry {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\nDescribeAlarmHistoryRequest historyRequest =\nDescribeAlarmHistoryRequest.builder()\n.startDate(start)\n.endDate(endDate)\n.alarmName(alarmName)\n.historyItemType(HistoryItemType.ACTION)\n.build();\n// Use the paginator to paginate through alarm history pages.\nDescribeAlarmHistoryPublisher historyPublisher =\ngetAsyncClient().describeAlarmHistoryPaginator(historyRequest);\nCompletableFuture future = historyPublisher\n.subscribe(response -> response.alarmHistoryItems().forEach(item\n-> {\nlogger.info(\"History summary: {}\", item.historySummary());\nlogger.info(\"Timestamp: {}\", item.timestamp());\n}))\n.whenComplete((result, exception) -> {\nif (exception != null) {\nlogger.error(\"Error occurred while getting alarm\nhistory: \" + exception.getMessage(), exception);\n} else {\nlogger.info(\"Successfully retrieved all alarm\nhistory.\");\n}\n});\n// Return the future to the calling code for further handling\nreturn future;\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to process alarm history\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error completing alarm history\nprocessing\", exception);\n}\n});\n}\nActions 806\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see DescribeAlarmHistory in AWS SDK for Java 2.x API Reference.\nDescribeAlarms\nThe following code example shows how to use DescribeAlarms.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Describes the CloudWatch alarms of the 'METRIC_ALARM' type.\n*\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of describing the CloudWatch alarms. The future completes when the\n* operation is finished, either successfully or with an error.\n*/\npublic CompletableFuture describeAlarmsAsync() {\nList typeList = new ArrayList<>();\ntypeList.add(AlarmType.METRIC_ALARM);\nDescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder()\n.alarmTypes(typeList)\n.maxRecords(10)\n.build();\nreturn getAsyncClient().describeAlarms(alarmsRequest)\n.thenAccept(response -> {\nList alarmList = response.metricAlarms();\nfor (MetricAlarm alarm : alarmList) {\nlogger.info(\"Alarm name: {}\", alarm.alarmName());\nlogger.info(\"Alarm description: {} \", alarm.alarmDescription());\n}\n})\nActions 807\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.whenComplete((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to describe alarms: {}\", ex.getMessage());\n} else {\nlogger.info(\"Successfully described alarms.\");\n}\n});\n}\n\u2022 For API details, see DescribeAlarms in AWS SDK for Java 2.x API Reference.\nDescribeAlarmsForMetric\nThe following code example shows how to use DescribeAlarmsForMetric.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Checks for a metric alarm in AWS CloudWatch.\n*\n* @param fileName the name of the file containing the JSON configuration for\nthe custom metric\n* @return a {@link CompletableFuture} that completes when the check for the\nmetric alarm is complete\n*/\npublic CompletableFuture checkForMetricAlarmAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nActions 808\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nDescribeAlarmsForMetricRequest metricRequest =\nDescribeAlarmsForMetricRequest.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nreturn checkForAlarmAsync(metricRequest, customMetricName, 10);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to parse JSON content\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error checking metric alarm\",\nexception);\n}\n});\n}\n// Recursive method to check for the alarm.\n/**\n* Checks for the existence of an alarm asynchronously for the specified metric.", "mimetype": "text/plain", "start_char_idx": 1218521, "end_char_idx": 1223260, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7882b2b7-8d74-4b75-a080-bc7021a9eff6": {"__data__": {"id_": "7882b2b7-8d74-4b75-a080-bc7021a9eff6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a3b2c513-940e-4543-8974-b263e5d920cf", "node_type": "1", "metadata": {}, "hash": "538aec31cb326b7d24b696d0d2ea6dde261e34bfd01f738ee59af86a4f3f4648", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1df8bab7-1e54-4cf4-b13e-fd87f3f81ab1", "node_type": "1", "metadata": {}, "hash": "ce228451b4d496d62b51aa0e42bae56674f85dfdf6e2f1b7253c1d3c392eb460", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "/**\n* Checks for the existence of an alarm asynchronously for the specified metric.\n*\n* @param metricRequest the request to describe the alarms for the specified\nmetric\n* @param customMetricName the name of the custom metric to check for an alarm\n* @param retries the number of retries to perform if no alarm is found\nActions 809\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} that completes when an alarm is found or\nthe maximum number of retries has been reached\n*/\nprivate static CompletableFuture\ncheckForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String\ncustomMetricName, int retries) {\nif (retries == 0) {\nreturn CompletableFuture.completedFuture(null).thenRun(() ->\nlogger.info(\"No Alarm state found for {} after 10 retries.\",\ncustomMetricName)\n);\n}\nreturn\n(getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> {\nif (response.hasMetricAlarms()) {\nlogger.info(\"Alarm state found for {}\", customMetricName);\nreturn CompletableFuture.completedFuture(null); // Alarm found,\ncomplete the future\n} else {\nreturn CompletableFuture.runAsync(() -> {\ntry {\nThread.sleep(20000);\nlogger.info(\".\");\n} catch (InterruptedException e) {\nthrow new RuntimeException(\"Interrupted while waiting to\nretry\", e);\n}\n}).thenCompose(v -> checkForAlarmAsync(metricRequest,\ncustomMetricName, retries - 1)); // Recursive call\n}\n}));\n}\n\u2022 For API details, see DescribeAlarmsForMetric in AWS SDK for Java 2.x API Reference.\nDescribeAnomalyDetectors\nThe following code example shows how to use DescribeAnomalyDetectors.\nActions 810\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Describes the anomaly detectors based on the specified JSON file.\n*\n* @param fileName the name of the JSON file containing the custom metric\nnamespace and name\n* @return a {@link CompletableFuture} that completes when the anomaly detectors\nhave been described\n* @throws RuntimeException if there is a failure during the operation, such as\nwhen reading or parsing the JSON file,\n* or when describing the anomaly detectors\n*/\npublic CompletableFuture describeAnomalyDetectorsAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nreturn readFileFuture.thenCompose(rootNode -> {\ntry {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nDescribeAnomalyDetectorsRequest detectorsRequest =\nDescribeAnomalyDetectorsRequest.builder()\n.maxResults(10)\nActions 811\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nreturn\ngetAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response ->\n{\nList anomalyDetectorList =\nresponse.anomalyDetectors();\nfor (AnomalyDetector detector : anomalyDetectorList) {\nlogger.info(\"Metric name: {} \",\ndetector.singleMetricAnomalyDetector().metricName());\nlogger.info(\"State: {} \", detector.stateValue());\n}\n});\n} catch (RuntimeException e) {\nthrow new RuntimeException(\"Failed to describe anomaly detectors\",\ne);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error describing anomaly detectors\",\nexception);\n}\n});\n}\n\u2022 For API details, see DescribeAnomalyDetectors in AWS SDK for Java 2.x API Reference.\nDisableAlarmActions\nThe following code example shows how to use DisableAlarmActions.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 812\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1223177, "end_char_idx": 1227628, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1df8bab7-1e54-4cf4-b13e-fd87f3f81ab1": {"__data__": {"id_": "1df8bab7-1e54-4cf4-b13e-fd87f3f81ab1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7882b2b7-8d74-4b75-a080-bc7021a9eff6", "node_type": "1", "metadata": {}, "hash": "05dba7e1135cf59a1fc33f2029ae9e5f86d0d647e3d39f9b50bc6b7aeac62afe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "625fd63f-d761-4fab-bc56-b43e7c41200a", "node_type": "1", "metadata": {}, "hash": "577224d62e2e6027d043909baf75fc692b3523bfc4c5ac3164db57e12d9ba090", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DisableAlarmActions\nThe following code example shows how to use DisableAlarmActions.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 812\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DisableAlarmActions {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nalarmName - An alarm name to disable (for example, MyAlarm).\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString alarmName = args[0];\nRegion region = Region.US_EAST_1;\nCloudWatchClient cw = CloudWatchClient.builder()\n.region(region)\n.build();\ndisableActions(cw, alarmName);\ncw.close();\n}\npublic static void disableActions(CloudWatchClient cw, String alarmName) {\ntry {\nDisableAlarmActionsRequest request =\nDisableAlarmActionsRequest.builder()\nActions 813\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.alarmNames(alarmName)\n.build();\ncw.disableAlarmActions(request);\nSystem.out.printf(\"Successfully disabled actions on alarm %s\",\nalarmName);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DisableAlarmActions in AWS SDK for Java 2.x API Reference.\nEnableAlarmActions\nThe following code example shows how to use EnableAlarmActions.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatch.CloudWatchClient;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\nActions 814\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class EnableAlarmActions {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nalarmName - An alarm name to enable (for example, MyAlarm).\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString alarm = args[0];\nRegion region = Region.US_EAST_1;\nCloudWatchClient cw = CloudWatchClient.builder()\n.region(region)\n.build();\nenableActions(cw, alarm);\ncw.close();\n}\npublic static void enableActions(CloudWatchClient cw, String alarm) {\ntry {\nEnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder()\n.alarmNames(alarm)\n.build();\ncw.enableAlarmActions(request);\nSystem.out.printf(\"Successfully enabled actions on alarm %s\", alarm);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see EnableAlarmActions in AWS SDK for Java 2.x API Reference.\nActions 815\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetMetricData\nThe following code example shows how to use GetMetricData.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves custom metric data from the AWS CloudWatch service.\n*\n* @param fileName the name of the file containing the custom metric information\n* @return a {@link CompletableFuture} that completes when the metric data has\nbeen retrieved\n*/\npublic CompletableFuture getCustomMetricDataAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\n// Read values from the JSON file.", "mimetype": "text/plain", "start_char_idx": 1226948, "end_char_idx": 1231238, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "625fd63f-d761-4fab-bc56-b43e7c41200a": {"__data__": {"id_": "625fd63f-d761-4fab-bc56-b43e7c41200a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1df8bab7-1e54-4cf4-b13e-fd87f3f81ab1", "node_type": "1", "metadata": {}, "hash": "ce228451b4d496d62b51aa0e42bae56674f85dfdf6e2f1b7253c1d3c392eb460", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "247e6c7e-a768-4b90-878a-ca4dc433c9fb", "node_type": "1", "metadata": {}, "hash": "93561a42633e24899cea0d1f23110d022f7ffe281c66b97ef63beb080768b638", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 815\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetMetricData\nThe following code example shows how to use GetMetricData.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves custom metric data from the AWS CloudWatch service.\n*\n* @param fileName the name of the file containing the custom metric information\n* @return a {@link CompletableFuture} that completes when the metric data has\nbeen retrieved\n*/\npublic CompletableFuture getCustomMetricDataAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\n// Read values from the JSON file.\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\n// Parse the JSON string to extract relevant values.\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nActions 816\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\n// Set the current time and date range for metric query.\nInstant nowDate = Instant.now();\nlong hours = 1;\nlong minutes = 30;\nInstant endTime = nowDate.plus(hours,\nChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES);\nMetric met = Metric.builder()\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.build();\nMetricStat metStat = MetricStat.builder()\n.stat(\"Maximum\")\n.period(60) // Assuming period in seconds\n.metric(met)\n.build();\nMetricDataQuery dataQuery = MetricDataQuery.builder()\n.metricStat(metStat)\n.id(\"foo2\")\n.returnData(true)\n.build();\nList dq = new ArrayList<>();\ndq.add(dataQuery);\nGetMetricDataRequest getMetricDataRequest =\nGetMetricDataRequest.builder()\n.maxDatapoints(10)\n.scanBy(ScanBy.TIMESTAMP_DESCENDING)\n.startTime(nowDate)\n.endTime(endTime)\n.metricDataQueries(dq)\n.build();\n// Call the async method for CloudWatch data retrieval.\nreturn getAsyncClient().getMetricData(getMetricDataRequest);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to parse JSON content\", e);\nActions 817\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}).thenAccept(response -> {\nList data = response.metricDataResults();\nfor (MetricDataResult item : data) {\nlogger.info(\"The label is: {}\", item.label());\nlogger.info(\"The status code is: {}\", item.statusCode().toString());\n}\n}).exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to get metric data\", exception);\n});\n}\n\u2022 For API details, see GetMetricData in AWS SDK for Java 2.x API Reference.\nGetMetricStatistics\nThe following code example shows how to use GetMetricStatistics.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves and displays metric statistics for the specified parameters.\n*\n* @param nameSpace the namespace for the metric\n* @param metVal the name of the metric\n* @param metricOption the statistic to retrieve for the metric (e.g.,\n\"Maximum\", \"Average\")\n* @param date the date for which to retrieve the metric statistics, in\nthe format \"yyyy-MM-dd'T'HH:mm:ss'Z'\"\n* @param myDimension the dimension(s) to filter the metric statistics by\n* @return a {@link CompletableFuture} that completes when the metric statistics\nhave been retrieved and displayed\n*/\npublic CompletableFuture\ngetAndDisplayMetricStatisticsAsync(String nameSpace, String metVal,\nActions 818\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString metricOption, String date, Dimension myDimension) {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\n// Building the request for metric statistics.", "mimetype": "text/plain", "start_char_idx": 1230517, "end_char_idx": 1234660, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "247e6c7e-a768-4b90-878a-ca4dc433c9fb": {"__data__": {"id_": "247e6c7e-a768-4b90-878a-ca4dc433c9fb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "625fd63f-d761-4fab-bc56-b43e7c41200a", "node_type": "1", "metadata": {}, "hash": "577224d62e2e6027d043909baf75fc692b3523bfc4c5ac3164db57e12d9ba090", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b35b0d8d-fcec-451e-8f5f-5069daad95a1", "node_type": "1", "metadata": {}, "hash": "e32fa8a8c8deb15d714a0a894b76c1a47dd2113387706ae6daa43d6e63f8039a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "/**\n* Retrieves and displays metric statistics for the specified parameters.\n*\n* @param nameSpace the namespace for the metric\n* @param metVal the name of the metric\n* @param metricOption the statistic to retrieve for the metric (e.g.,\n\"Maximum\", \"Average\")\n* @param date the date for which to retrieve the metric statistics, in\nthe format \"yyyy-MM-dd'T'HH:mm:ss'Z'\"\n* @param myDimension the dimension(s) to filter the metric statistics by\n* @return a {@link CompletableFuture} that completes when the metric statistics\nhave been retrieved and displayed\n*/\npublic CompletableFuture\ngetAndDisplayMetricStatisticsAsync(String nameSpace, String metVal,\nActions 818\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString metricOption, String date, Dimension myDimension) {\nInstant start = Instant.parse(date);\nInstant endDate = Instant.now();\n// Building the request for metric statistics.\nGetMetricStatisticsRequest statisticsRequest =\nGetMetricStatisticsRequest.builder()\n.endTime(endDate)\n.startTime(start)\n.dimensions(myDimension)\n.metricName(metVal)\n.namespace(nameSpace)\n.period(86400) // 1 day period\n.statistics(Statistic.fromValue(metricOption))\n.build();\nreturn getAsyncClient().getMetricStatistics(statisticsRequest)\n.whenComplete((response, exception) -> {\nif (response != null) {\nList data = response.datapoints();\nif (!data.isEmpty()) {\nfor (Datapoint datapoint : data) {\nlogger.info(\"Timestamp: {} Maximum value: {}\",\ndatapoint.timestamp(), datapoint.maximum());\n}\n} else {\nlogger.info(\"The returned data list is empty\");\n}\n} else {\nlogger.info(\"Failed to get metric statistics: {} \",\nexception.getMessage());\n}\n})\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Error while getting metric statistics: \"\n+ exception.getMessage(), exception);\n});\n}\n\u2022 For API details, see GetMetricStatistics in AWS SDK for Java 2.x API Reference.\nActions 819\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetMetricWidgetImage\nThe following code example shows how to use GetMetricWidgetImage.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves and saves a custom metric image to a file.\n*\n* @param fileName the name of the file to save the metric image to\n* @return a {@link CompletableFuture} that completes when the image has been\nsaved to the file\n*/\npublic CompletableFuture downloadAndSaveMetricImageAsync(String fileName)\n{\nlogger.info(\"Getting Image data for custom metric.\");\nString myJSON = \"\"\"\n{\n\"title\": \"Example Metric Graph\",\n\"view\": \"timeSeries\",\n\"stacked \": false,\n\"period\": 10,\n\"width\": 1400,\n\"height\": 600,\n\"metrics\": [\n[\n\"AWS/Billing\",\n\"EstimatedCharges\",\n\"Currency\",\n\"USD\"\n]\n]\n}\n\"\"\";\nActions 820\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetMetricWidgetImageRequest imageRequest =\nGetMetricWidgetImageRequest.builder()\n.metricWidget(myJSON)\n.build();\nreturn getAsyncClient().getMetricWidgetImage(imageRequest)\n.thenCompose(response -> {\nSdkBytes sdkBytes = response.metricWidgetImage();\nbyte[] bytes = sdkBytes.asByteArray();\nreturn CompletableFuture.runAsync(() -> {\ntry {\nFile outputFile = new File(fileName);\ntry (FileOutputStream outputStream = new\nFileOutputStream(outputFile)) {\noutputStream.write(bytes);\n}\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to write image to file\",\ne);\n}\n});\n})\n.whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error getting and saving metric\nimage\", exception);\n} else {\nlogger.info(\"Image data saved successfully to {}\", fileName);\n}\n});\n}\n\u2022 For API details, see GetMetricWidgetImage in AWS SDK for Java 2.x API Reference.\nListDashboards\nThe following code example shows how to use ListDashboards.\nActions 821\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Lists the available dashboards.\n*\n* @return a {@link CompletableFuture} that completes when the operation is\nfinished.\n* The future will complete exceptionally if an error occurs while listing the\ndashboards.", "mimetype": "text/plain", "start_char_idx": 1233741, "end_char_idx": 1237952, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b35b0d8d-fcec-451e-8f5f-5069daad95a1": {"__data__": {"id_": "b35b0d8d-fcec-451e-8f5f-5069daad95a1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "247e6c7e-a768-4b90-878a-ca4dc433c9fb", "node_type": "1", "metadata": {}, "hash": "93561a42633e24899cea0d1f23110d022f7ffe281c66b97ef63beb080768b638", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "07f3f519-69e4-4e9e-a5aa-9dcb8ad05403", "node_type": "1", "metadata": {}, "hash": "4b2c80d7ccd8697cd082f6a07f48f37c12e24f1af4d318956ea7c0a3abe3b932", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ListDashboards\nThe following code example shows how to use ListDashboards.\nActions 821\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Lists the available dashboards.\n*\n* @return a {@link CompletableFuture} that completes when the operation is\nfinished.\n* The future will complete exceptionally if an error occurs while listing the\ndashboards.\n*/\npublic CompletableFuture listDashboardsAsync() {\nListDashboardsRequest listDashboardsRequest =\nListDashboardsRequest.builder().build();\nListDashboardsPublisher paginator =\ngetAsyncClient().listDashboardsPaginator(listDashboardsRequest);\nreturn paginator.subscribe(response -> {\nresponse.dashboardEntries().forEach(entry -> {\nlogger.info(\"Dashboard name is: {} \", entry.dashboardName());\nlogger.info(\"Dashboard ARN is: {} \", entry.dashboardArn());\n});\n}).exceptionally(ex -> {\nlogger.info(\"Failed to list dashboards: {} \", ex.getMessage());\nthrow new RuntimeException(\"Error occurred while listing dashboards\",\nex);\n});\n}\n\u2022 For API details, see ListDashboards in AWS SDK for Java 2.x API Reference.\nListMetrics\nThe following code example shows how to use ListMetrics.\nActions 822\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves a list of metric names for the specified namespace.\n*\n* @param namespace the namespace for which to retrieve the metric names\n* @return a {@link CompletableFuture} that, when completed, contains an {@link\nArrayList} of\n* the metric names in the specified namespace\n* @throws RuntimeException if an error occurs while listing the metrics\n*/\npublic CompletableFuture> listMetsAsync(String namespace) {\nListMetricsRequest request = ListMetricsRequest.builder()\n.namespace(namespace)\n.build();\nListMetricsPublisher metricsPaginator =\ngetAsyncClient().listMetricsPaginator(request);\nSet metSet = new HashSet<>();\nCompletableFuture future = metricsPaginator.subscribe(response -> {\nresponse.metrics().forEach(metric -> {\nString metricName = metric.metricName();\nmetSet.add(metricName);\n});\n});\nreturn future\n.thenApply(ignored -> new ArrayList<>(metSet))\n.exceptionally(exception -> {\nthrow new RuntimeException(\"Failed to list metrics: \" +\nexception.getMessage(), exception);\n});\n}\n\u2022 For API details, see ListMetrics in AWS SDK for Java 2.x API Reference.\nActions 823\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPutAnomalyDetector\nThe following code example shows how to use PutAnomalyDetector.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Adds an anomaly detector for the given file.\n*\n* @param fileName the name of the file containing the anomaly detector\nconfiguration\n* @return a {@link CompletableFuture} that completes when the anomaly detector\nhas been added\n*/\npublic CompletableFuture addAnomalyDetectorAsync(String fileName) {\nCompletableFuture readFileFuture =\nCompletableFuture.supplyAsync(() -> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\nreturn new ObjectMapper().readTree(parser); // Return the root node\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read or parse the file\", e);\n}\n});\nreturn readFileFuture.thenCompose(rootNode -> {\ntry {\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nSingleMetricAnomalyDetector singleMetricAnomalyDetector =\nSingleMetricAnomalyDetector.builder()\n.metricName(customMetricName)\nActions 824\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.namespace(customMetricNamespace)\n.stat(\"Maximum\")\n.build();\nPutAnomalyDetectorRequest anomalyDetectorRequest =\nPutAnomalyDetectorRequest.builder()\n.singleMetricAnomalyDetector(singleMetricAnomalyDetector)\n.build();\nreturn\ngetAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response ->\n{\nlogger.info(\"Added anomaly detector for metric {}\",\ncustomMetricName);\n});\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to create anomaly detector\", e);\n}\n}).whenComplete((result, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Error adding anomaly detector\",\nexception);\n}\n});\n}\n\u2022 For API details, see PutAnomalyDetector in AWS SDK for Java 2.x API Reference.\nPutDashboard\nThe following code example shows how to use PutDashboard.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1237457, "end_char_idx": 1242185, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "07f3f519-69e4-4e9e-a5aa-9dcb8ad05403": {"__data__": {"id_": "07f3f519-69e4-4e9e-a5aa-9dcb8ad05403", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b35b0d8d-fcec-451e-8f5f-5069daad95a1", "node_type": "1", "metadata": {}, "hash": "e32fa8a8c8deb15d714a0a894b76c1a47dd2113387706ae6daa43d6e63f8039a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cbab7583-bfb5-4fca-9045-01318ac4eeb4", "node_type": "1", "metadata": {}, "hash": "292a841a528b7d366cb57a9ec31bd7b4bf0108b5f75d73e87e480370d62885db", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "PutDashboard\nThe following code example shows how to use PutDashboard.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 825\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Creates a new dashboard with the specified name and metrics from the given\nfile.\n*\n* @param dashboardName the name of the dashboard to be created\n* @param fileName the name of the file containing the dashboard body\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof creating the dashboard\n* @throws IOException if there is an error reading the dashboard body from the\nfile\n*/\npublic CompletableFuture\ncreateDashboardWithMetricsAsync(String dashboardName, String fileName) throws\nIOException {\nString dashboardBody = readFileAsString(fileName);\nPutDashboardRequest dashboardRequest = PutDashboardRequest.builder()\n.dashboardName(dashboardName)\n.dashboardBody(dashboardBody)\n.build();\nreturn getAsyncClient().putDashboard(dashboardRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to create dashboard: {}\", ex.getMessage());\nthrow new RuntimeException(\"Dashboard creation failed\", ex);\n} else {\n// Handle the normal response case\nlogger.info(\"{} was successfully created.\", dashboardName);\nList messages =\nresponse.dashboardValidationMessages();\nif (messages.isEmpty()) {\nlogger.info(\"There are no messages in the new Dashboard.\");\n} else {\nfor (DashboardValidationMessage message : messages) {\nlogger.info(\"Message: {}\", message.message());\n}\n}\nreturn response; // Return the response for further use\n}\n});\n}\n\u2022 For API details, see PutDashboard in AWS SDK for Java 2.x API Reference.\nActions 826\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPutMetricAlarm\nThe following code example shows how to use PutMetricAlarm.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates an alarm based on the configuration provided in a JSON file.\n*\n* @param fileName the name of the JSON file containing the alarm configuration\n* @return a CompletableFuture that represents the asynchronous operation of\ncreating the alarm\n* @throws RuntimeException if an exception occurs while reading the JSON file\nor creating the alarm\n*/\npublic CompletableFuture createAlarmAsync(String fileName) {\ncom.fasterxml.jackson.databind.JsonNode rootNode;\ntry {\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\nrootNode = new ObjectMapper().readTree(parser);\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read the alarm configuration\nfile\", e);\n}\n// Extract values from the JSON node.\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName = rootNode.findValue(\"customMetricName\").asText();\nString alarmName = rootNode.findValue(\"exampleAlarmName\").asText();\nString emailTopic = rootNode.findValue(\"emailTopic\").asText();\nString accountId = rootNode.findValue(\"accountId\").asText();\nString region = rootNode.findValue(\"region\").asText();\n// Create a List for alarm actions.\nList alarmActions = new ArrayList<>();\nActions 827\nAWS SDK for Java 2.x Developer Guide for version 2.x\nalarmActions.add(\"arn:aws:sns:\" + region + \":\" + accountId + \":\" +\nemailTopic);\nPutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder()\n.alarmActions(alarmActions)\n.alarmDescription(\"Example metric alarm\")\n.alarmName(alarmName)\n.comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD)\n.threshold(100.00)\n.metricName(customMetricName)\n.namespace(customMetricNamespace)\n.evaluationPeriods(1)\n.period(10)\n.statistic(\"Maximum\")\n.datapointsToAlarm(1)\n.treatMissingData(\"ignore\")\n.build();\n// Call the putMetricAlarm asynchronously and handle the result.\nreturn getAsyncClient().putMetricAlarm(alarmRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to create alarm: {}\", ex.getMessage());\nthrow new RuntimeException(\"Failed to create alarm\", ex);\n} else {\nlogger.info(\"{} was successfully created!\", alarmName);\nreturn alarmName;\n}\n});\n}\n\u2022 For API details, see PutMetricAlarm in AWS SDK for Java 2.x API Reference.\nPutMetricData\nThe following code example shows how to use PutMetricData.\nActions 828\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Adds metric data for an alarm asynchronously.", "mimetype": "text/plain", "start_char_idx": 1242069, "end_char_idx": 1246714, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cbab7583-bfb5-4fca-9045-01318ac4eeb4": {"__data__": {"id_": "cbab7583-bfb5-4fca-9045-01318ac4eeb4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "07f3f519-69e4-4e9e-a5aa-9dcb8ad05403", "node_type": "1", "metadata": {}, "hash": "4b2c80d7ccd8697cd082f6a07f48f37c12e24f1af4d318956ea7c0a3abe3b932", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c691b00-633a-44d5-ac59-2fcd6c48963b", "node_type": "1", "metadata": {}, "hash": "984fa8eadd0dd8c4197200d3192458c24b2fd93ee19e009dcd54d51b04d3f304", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return getAsyncClient().putMetricAlarm(alarmRequest)\n.handle((response, ex) -> {\nif (ex != null) {\nlogger.info(\"Failed to create alarm: {}\", ex.getMessage());\nthrow new RuntimeException(\"Failed to create alarm\", ex);\n} else {\nlogger.info(\"{} was successfully created!\", alarmName);\nreturn alarmName;\n}\n});\n}\n\u2022 For API details, see PutMetricAlarm in AWS SDK for Java 2.x API Reference.\nPutMetricData\nThe following code example shows how to use PutMetricData.\nActions 828\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Adds metric data for an alarm asynchronously.\n*\n* @param fileName the name of the JSON file containing the metric data\n* @return a CompletableFuture that asynchronously returns the\nPutMetricDataResponse\n*/\npublic CompletableFuture\naddMetricDataForAlarmAsync(String fileName) {\nCompletableFuture readFileFuture = CompletableFuture.supplyAsync(()\n-> {\ntry {\nJsonParser parser = new JsonFactory().createParser(new\nFile(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nreturn rootNode.toString(); // Return JSON as a string for further\nprocessing\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to read file\", e);\n}\n});\nreturn readFileFuture.thenCompose(jsonContent -> {\ntry {\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(jsonContent);\nString customMetricNamespace =\nrootNode.findValue(\"customMetricNamespace\").asText();\nString customMetricName =\nrootNode.findValue(\"customMetricName\").asText();\nInstant instant = Instant.now();\nActions 829\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create MetricDatum objects.\nMetricDatum datum1 = MetricDatum.builder()\n.metricName(customMetricName)\n.unit(StandardUnit.NONE)\n.value(1001.00)\n.timestamp(instant)\n.build();\nMetricDatum datum2 = MetricDatum.builder()\n.metricName(customMetricName)\n.unit(StandardUnit.NONE)\n.value(1002.00)\n.timestamp(instant)\n.build();\nList metricDataList = new ArrayList<>();\nmetricDataList.add(datum1);\nmetricDataList.add(datum2);\n// Build the PutMetricData request.\nPutMetricDataRequest request = PutMetricDataRequest.builder()\n.namespace(customMetricNamespace)\n.metricData(metricDataList)\n.build();\n// Send the request asynchronously.\nreturn getAsyncClient().putMetricData(request);\n} catch (IOException e) {\nCompletableFuture failedFuture = new\nCompletableFuture<>();\nfailedFuture.completeExceptionally(new RuntimeException(\"Failed to\nparse JSON content\", e));\nreturn failedFuture;\n}\n}).whenComplete((response, exception) -> {\nif (exception != null) {\nlogger.error(\"Failed to put metric data: \" + exception.getMessage(),\nexception);\n} else {\nlogger.info(\"Added metric values for metric.\");\n}\n});\n}\nActions 830\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see PutMetricData in AWS SDK for Java 2.x API Reference.\nScenarios\nMonitor DynamoDB performance\nThe following code example shows how to configure an application's use of DynamoDB to monitor\nperformance.\nSDK for Java 2.x\nThis example shows how to configure a Java application to monitor the performance of\nDynamoDB. The application sends metric data to CloudWatch where you can monitor the\nperformance.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 CloudWatch\n\u2022 DynamoDB\nCloudWatch Events examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch Events.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nScenarios 831\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions\nPutEvents\nThe following code example shows how to use PutEvents.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1245999, "end_char_idx": 1250381, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9c691b00-633a-44d5-ac59-2fcd6c48963b": {"__data__": {"id_": "9c691b00-633a-44d5-ac59-2fcd6c48963b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cbab7583-bfb5-4fca-9045-01318ac4eeb4", "node_type": "1", "metadata": {}, "hash": "292a841a528b7d366cb57a9ec31bd7b4bf0108b5f75d73e87e480370d62885db", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8afec0be-80f2-4361-9f1f-ea8a16748c0a", "node_type": "1", "metadata": {}, "hash": "b398cecb327fc3025c9ae1075ee11d5141138bb78943c7445212837afff67ede", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Services used in this example\n\u2022 CloudWatch\n\u2022 DynamoDB\nCloudWatch Events examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch Events.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nScenarios 831\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions\nPutEvents\nThe following code example shows how to use PutEvents.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequestEntry;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class PutEvents {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nresourceArn - An Amazon Resource Name (ARN) related to the\nevents.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\nActions 832\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nString resourceArn = args[0];\nCloudWatchEventsClient cwe = CloudWatchEventsClient.builder()\n.build();\nputCWEvents(cwe, resourceArn);\ncwe.close();\n}\npublic static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn) {\ntry {\nfinal String EVENT_DETAILS = \"{ \\\"key1\\\": \\\"value1\\\", \\\"key2\\\":\n\\\"value2\\\" }\";\nPutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder()\n.detail(EVENT_DETAILS)\n.detailType(\"sampleSubmitted\")\n.resources(resourceArn)\n.source(\"aws-sdk-java-cloudwatch-example\")\n.build();\nPutEventsRequest request = PutEventsRequest.builder()\n.entries(requestEntry)\n.build();\ncwe.putEvents(request);\nSystem.out.println(\"Successfully put CloudWatch event\");\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see PutEvents in AWS SDK for Java 2.x API Reference.\nPutRule\nThe following code example shows how to use PutRule.\nActions 833\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutRuleResponse;\nimport software.amazon.awssdk.services.cloudwatchevents.model.RuleState;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class PutRule {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n roleArn>\\s\nWhere:\nruleName - A rule name (for example, myrule).\nroleArn - A role ARN value (for example,\narn:aws:iam::xxxxxx047983:user/MyUser).", "mimetype": "text/plain", "start_char_idx": 1249496, "end_char_idx": 1253336, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8afec0be-80f2-4361-9f1f-ea8a16748c0a": {"__data__": {"id_": "8afec0be-80f2-4361-9f1f-ea8a16748c0a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c691b00-633a-44d5-ac59-2fcd6c48963b", "node_type": "1", "metadata": {}, "hash": "984fa8eadd0dd8c4197200d3192458c24b2fd93ee19e009dcd54d51b04d3f304", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "23403119-b096-423f-b84a-a89ea7cd5605", "node_type": "1", "metadata": {}, "hash": "2638e4b037fa9b45a5db6a00275155fe2dc8aa862b7d001621facbe9da54327a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class PutRule {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n roleArn>\\s\nWhere:\nruleName - A rule name (for example, myrule).\nroleArn - A role ARN value (for example,\narn:aws:iam::xxxxxx047983:user/MyUser).\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString ruleName = args[0];\nString roleArn = args[1];\nActions 834\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCloudWatchEventsClient cwe = CloudWatchEventsClient.builder()\n.build();\nputCWRule(cwe, ruleName, roleArn);\ncwe.close();\n}\npublic static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String\nroleArn) {\ntry {\nPutRuleRequest request = PutRuleRequest.builder()\n.name(ruleName)\n.roleArn(roleArn)\n.scheduleExpression(\"rate(5 minutes)\")\n.state(RuleState.ENABLED)\n.build();\nPutRuleResponse response = cwe.putRule(request);\nSystem.out.printf(\n\"Successfully created CloudWatch events rule %s with arn %s\",\nroleArn, response.ruleArn());\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see PutRule in AWS SDK for Java 2.x API Reference.\nPutTargets\nThe following code example shows how to use PutTargets.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nActions 835\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;\nimport software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsRequest;\nimport software.amazon.awssdk.services.cloudwatchevents.model.Target;\n/**\n* To run this Java V2 code example, ensure that you have setup your development\n* environment, including your credentials.\n*\n* For information, see this documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class PutTargets {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nruleName - A rule name (for example, myrule).\nfunctionArn - An AWS Lambda function ARN (for example,\narn:aws:lambda:us-west-2:xxxxxx047983:function:lamda1).\ntargetId - A target id value.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString ruleName = args[0];\nString functionArn = args[1];\nString targetId = args[2];\nCloudWatchEventsClient cwe = CloudWatchEventsClient.builder()\n.build();\nputCWTargets(cwe, ruleName, functionArn, targetId);\ncwe.close();\n}\nActions 836\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void putCWTargets(CloudWatchEventsClient cwe, String ruleName,\nString functionArn, String targetId) {\ntry {\nTarget target = Target.builder()\n.arn(functionArn)\n.id(targetId)\n.build();\nPutTargetsRequest request = PutTargetsRequest.builder()\n.targets(target)\n.rule(ruleName)\n.build();\ncwe.putTargets(request);\nSystem.out.printf(\n\"Successfully created CloudWatch events target for rule %s\",\nruleName);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see PutTargets in AWS SDK for Java 2.x API Reference.\nCloudWatch Logs examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch Logs.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nCloudWatch Logs 837\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions\nDeleteSubscriptionFilter\nThe following code example shows how to use DeleteSubscriptionFilter.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1252932, "end_char_idx": 1257155, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "23403119-b096-423f-b84a-a89ea7cd5605": {"__data__": {"id_": "23403119-b096-423f-b84a-a89ea7cd5605", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8afec0be-80f2-4361-9f1f-ea8a16748c0a", "node_type": "1", "metadata": {}, "hash": "b398cecb327fc3025c9ae1075ee11d5141138bb78943c7445212837afff67ede", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9fcb799d-36a2-4fd7-9a37-9c809b1ab715", "node_type": "1", "metadata": {}, "hash": "38cce7c657101b876918e7de1940fce5ac240093f3f949e79057e58722a50b28", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CloudWatch Logs examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with CloudWatch Logs.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nCloudWatch Logs 837\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions\nDeleteSubscriptionFilter\nThe following code example shows how to use DeleteSubscriptionFilter.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteSubscriptionFilter {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\nfilter - The name of the subscription filter (for example,\nMyFilter).\nlogGroup - The name of the log group. (for example, testgroup).\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nActions 838\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\nString filter = args[0];\nString logGroup = args[1];\nCloudWatchLogsClient logs = CloudWatchLogsClient.builder()\n.build();\ndeleteSubFilter(logs, filter, logGroup);\nlogs.close();\n}\npublic static void deleteSubFilter(CloudWatchLogsClient logs, String filter,\nString logGroup) {\ntry {\nDeleteSubscriptionFilterRequest request =\nDeleteSubscriptionFilterRequest.builder()\n.filterName(filter)\n.logGroupName(logGroup)\n.build();\nlogs.deleteSubscriptionFilter(request);\nSystem.out.printf(\"Successfully deleted CloudWatch logs subscription\nfilter %s\", filter);\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DeleteSubscriptionFilter in AWS SDK for Java 2.x API Reference.\nDescribeSubscriptionFilters\nThe following code example shows how to use DescribeSubscriptionFilters.\nActions 839\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersRequest;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersResponse;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.SubscriptionFilter;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeSubscriptionFilters {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nlogGroup - A log group name (for example, myloggroup).", "mimetype": "text/plain", "start_char_idx": 1256387, "end_char_idx": 1260189, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9fcb799d-36a2-4fd7-9a37-9c809b1ab715": {"__data__": {"id_": "9fcb799d-36a2-4fd7-9a37-9c809b1ab715", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "23403119-b096-423f-b84a-a89ea7cd5605", "node_type": "1", "metadata": {}, "hash": "2638e4b037fa9b45a5db6a00275155fe2dc8aa862b7d001621facbe9da54327a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ad8c6486-8752-42d6-ab4e-286325244518", "node_type": "1", "metadata": {}, "hash": "915bb28c7e3ca1830a23f9dc56b72f14d95cd875961a1026bc59298f571dc384", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;\nimport software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersRequest;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersResponse;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.SubscriptionFilter;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeSubscriptionFilters {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nlogGroup - A log group name (for example, myloggroup).\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nActions 840\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString logGroup = args[0];\nCloudWatchLogsClient logs = CloudWatchLogsClient.builder()\n.credentialsProvider(ProfileCredentialsProvider.create())\n.build();\ndescribeFilters(logs, logGroup);\nlogs.close();\n}\npublic static void describeFilters(CloudWatchLogsClient logs, String logGroup) {\ntry {\nboolean done = false;\nString newToken = null;\nwhile (!done) {\nDescribeSubscriptionFiltersResponse response;\nif (newToken == null) {\nDescribeSubscriptionFiltersRequest request =\nDescribeSubscriptionFiltersRequest.builder()\n.logGroupName(logGroup)\n.limit(1).build();\nresponse = logs.describeSubscriptionFilters(request);\n} else {\nDescribeSubscriptionFiltersRequest request =\nDescribeSubscriptionFiltersRequest.builder()\n.nextToken(newToken)\n.logGroupName(logGroup)\n.limit(1).build();\nresponse = logs.describeSubscriptionFilters(request);\n}\nfor (SubscriptionFilter filter : response.subscriptionFilters()) {\nSystem.out.printf(\"Retrieved filter with name %s, \" + \"pattern\n%s \" + \"and destination arn %s\",\nfilter.filterName(),\nfilter.filterPattern(),\nfilter.destinationArn());\n}\nif (response.nextToken() == null) {\ndone = true;\n} else {\nnewToken = response.nextToken();\nActions 841\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n} catch (CloudWatchException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.printf(\"Done\");\n}\n}\n\u2022 For API details, see DescribeSubscriptionFilters in AWS SDK for Java 2.x API Reference.\nPutSubscriptionFilter\nThe following code example shows how to use PutSubscriptionFilter.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.PutSubscriptionFilterRequest;\n/**\n* Before running this code example, you need to grant permission to CloudWatch\n* Logs the right to execute your Lambda function.\n* To perform this task, you can use this CLI command:\n*\n* aws lambda add-permission --function-name \"lamda1\" --statement-id \"lamda1\"\n* --principal \"logs.us-west-2.amazonaws.com\" --action \"lambda:InvokeFunction\"\n* --source-arn \"arn:aws:logs:us-west-2:111111111111:log-group:testgroup:*\"\n* --source-account \"111111111111\"\n*\nActions 842\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Make sure you replace the function name with your function name and replace\n* '111111111111' with your account details.\n* For more information, see \"Subscription Filters with AWS Lambda\" in the\n* Amazon CloudWatch Logs Guide.\n*\n*\n* Also, before running this Java V2 code example,set up your development\n* environment,including your credentials.\n*\n* For more information,see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n*/\npublic class PutSubscriptionFilter {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nfilter - A filter name (for example, myfilter).\npattern - A filter pattern (for example, ERROR).\nlogGroup - A log group name (testgroup).\nfunctionArn - An AWS Lambda function ARN (for example,\narn:aws:lambda:us-west-2:111111111111:function:lambda1) .", "mimetype": "text/plain", "start_char_idx": 1259232, "end_char_idx": 1263743, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ad8c6486-8752-42d6-ab4e-286325244518": {"__data__": {"id_": "ad8c6486-8752-42d6-ab4e-286325244518", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9fcb799d-36a2-4fd7-9a37-9c809b1ab715", "node_type": "1", "metadata": {}, "hash": "38cce7c657101b876918e7de1940fce5ac240093f3f949e79057e58722a50b28", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e4b4e19b-34ff-4378-8797-3aca2209cf3c", "node_type": "1", "metadata": {}, "hash": "3107f63c4b3792209578602e1221800e2a9a5935b7f989b730b7e674c6d748c7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* For more information, see \"Subscription Filters with AWS Lambda\" in the\n* Amazon CloudWatch Logs Guide.\n*\n*\n* Also, before running this Java V2 code example,set up your development\n* environment,including your credentials.\n*\n* For more information,see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n*/\npublic class PutSubscriptionFilter {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nfilter - A filter name (for example, myfilter).\npattern - A filter pattern (for example, ERROR).\nlogGroup - A log group name (testgroup).\nfunctionArn - An AWS Lambda function ARN (for example,\narn:aws:lambda:us-west-2:111111111111:function:lambda1) .\n\"\"\";\nif (args.length != 4) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString filter = args[0];\nString pattern = args[1];\nString logGroup = args[2];\nString functionArn = args[3];\nRegion region = Region.US_WEST_2;\nCloudWatchLogsClient cwl = CloudWatchLogsClient.builder()\n.region(region)\n.build();\nActions 843\nAWS SDK for Java 2.x Developer Guide for version 2.x\nputSubFilters(cwl, filter, pattern, logGroup, functionArn);\ncwl.close();\n}\npublic static void putSubFilters(CloudWatchLogsClient cwl,\nString filter,\nString pattern,\nString logGroup,\nString functionArn) {\ntry {\nPutSubscriptionFilterRequest request =\nPutSubscriptionFilterRequest.builder()\n.filterName(filter)\n.filterPattern(pattern)\n.logGroupName(logGroup)\n.destinationArn(functionArn)\n.build();\ncwl.putSubscriptionFilter(request);\nSystem.out.printf(\n\"Successfully created CloudWatch logs subscription filter %s\",\nfilter);\n} catch (CloudWatchLogsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see PutSubscriptionFilter in AWS SDK for Java 2.x API Reference.\nStartLiveTail\nThe following code example shows how to use StartLiveTail.\nSDK for Java 2.x\nInclude the required files.\nimport io.reactivex.FlowableSubscriber;\nActions 844\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport io.reactivex.annotations.NonNull;\nimport org.reactivestreams.Subscription;\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionLogEvent;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionStart;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionUpdate;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailRequest;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseHandler;\nimport software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException;\nimport\nsoftware.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseStream;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\nHandle the events from the Live Tail session.\nprivate static StartLiveTailResponseHandler\ngetStartLiveTailResponseStreamHandler(\nAtomicReference subscriptionAtomicReference) {\nreturn StartLiveTailResponseHandler.builder()\n.onResponse(r -> System.out.println(\"Received initial response\"))\n.onError(throwable -> {\nCloudWatchLogsException e = (CloudWatchLogsException)\nthrowable.getCause();\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n})\n.subscriber(() -> new FlowableSubscriber<>() {\n@Override\npublic void onSubscribe(@NonNull Subscription s) {\nsubscriptionAtomicReference.set(s);\ns.request(Long.MAX_VALUE);\n}\n@Override\npublic void onNext(StartLiveTailResponseStream event) {\nif (event instanceof LiveTailSessionStart) {\nActions 845\nAWS SDK for Java 2.x Developer Guide for version 2.x\nLiveTailSessionStart sessionStart = (LiveTailSessionStart)\nevent;\nSystem.out.println(sessionStart);\n} else if (event instanceof LiveTailSessionUpdate) {\nLiveTailSessionUpdate sessionUpdate =\n(LiveTailSessionUpdate) event;\nList logEvents =\nsessionUpdate.sessionResults();\nlogEvents.forEach(e -> {\nlong timestamp = e.timestamp();\nDate date = new Date(timestamp);\nSystem.out.println(\"[\" + date + \"] \" + e.message());\n});\n} else {\nthrow CloudWatchLogsException.builder().message(\"Unknown\nevent type\").build();\n}\n}\n@Override\npublic void onError(Throwable throwable) {\nSystem.out.println(throwable.getMessage());\nSystem.exit(1);\n}\n@Override\npublic void onComplete() {\nSystem.out.println(\"Completed Streaming Session\");\n}\n})\n.build();\n}\nStart the Live Tail session.", "mimetype": "text/plain", "start_char_idx": 1262951, "end_char_idx": 1267595, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e4b4e19b-34ff-4378-8797-3aca2209cf3c": {"__data__": {"id_": "e4b4e19b-34ff-4378-8797-3aca2209cf3c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ad8c6486-8752-42d6-ab4e-286325244518", "node_type": "1", "metadata": {}, "hash": "915bb28c7e3ca1830a23f9dc56b72f14d95cd875961a1026bc59298f571dc384", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "68a7e795-4593-4de1-8243-0646853bf1ef", "node_type": "1", "metadata": {}, "hash": "7e97ab9d1cb03ff756b911fa5b2ce12bb8373880094cb8ea4c57e41dab54a898", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CloudWatchLogsAsyncClient cloudWatchLogsAsyncClient =\nCloudWatchLogsAsyncClient.builder()\n.credentialsProvider(ProfileCredentialsProvider.create())\n.build();\nStartLiveTailRequest request =\nStartLiveTailRequest.builder()\nActions 846\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.logGroupIdentifiers(logGroupIdentifiers)\n.logStreamNames(logStreamNames)\n.logEventFilterPattern(logEventFilterPattern)\n.build();\n/* Create a reference to store the subscription */\nfinal AtomicReference subscriptionAtomicReference = new\nAtomicReference<>(null);\ncloudWatchLogsAsyncClient.startLiveTail(request,\ngetStartLiveTailResponseStreamHandler(subscriptionAtomicReference));\nStop the Live Tail session after a period of time has elapsed.\n/* Set a timeout for the session and cancel the subscription. This will:\n* 1). Close the stream\n* 2). Stop the Live Tail session\n*/\ntry {\nThread.sleep(10000);\n} catch (InterruptedException e) {\nthrow new RuntimeException(e);\n}\nif (subscriptionAtomicReference.get() != null) {\nsubscriptionAtomicReference.get().cancel();\nSystem.out.println(\"Subscription to stream closed\");\n}\n\u2022 For API details, see StartLiveTail in AWS SDK for Java 2.x API Reference.\nAmazon Cognito Identity examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon Cognito Identity.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nAmazon Cognito Identity 847\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTopics\n\u2022 Actions\nActions\nCreateIdentityPool\nThe following code example shows how to use CreateIdentityPool.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateIdentityPool {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nActions 848\nAWS SDK for Java 2.x Developer Guide for version 2.x\nidentityPoolName - The name to give your identity pool.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString identityPoolName = args[0];\nCognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()\n.region(Region.US_EAST_1)\n.build();\nString identityPoolId = createIdPool(cognitoClient, identityPoolName);\nSystem.out.println(\"Unity pool ID \" + identityPoolId);\ncognitoClient.close();\n}\npublic static String createIdPool(CognitoIdentityClient cognitoClient, String\nidentityPoolName) {\ntry {\nCreateIdentityPoolRequest poolRequest =\nCreateIdentityPoolRequest.builder()\n.allowUnauthenticatedIdentities(false)\n.identityPoolName(identityPoolName)\n.build();\nCreateIdentityPoolResponse response =\ncognitoClient.createIdentityPool(poolRequest);\nreturn response.identityPoolId();\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see CreateIdentityPool in AWS SDK for Java 2.x API Reference.\nActions 849\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteIdentityPool\nThe following code example shows how to use DeleteIdentityPool.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1267596, "end_char_idx": 1271848, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "68a7e795-4593-4de1-8243-0646853bf1ef": {"__data__": {"id_": "68a7e795-4593-4de1-8243-0646853bf1ef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e4b4e19b-34ff-4378-8797-3aca2209cf3c", "node_type": "1", "metadata": {}, "hash": "3107f63c4b3792209578602e1221800e2a9a5935b7f989b730b7e674c6d748c7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7f857d1c-41d4-46ed-98bf-e8774af5b6ca", "node_type": "1", "metadata": {}, "hash": "30dfe15350f4df002e96e68fc50373dc20a9b6690fde23d18896a24f20014ea0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 849\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteIdentityPool\nThe following code example shows how to use DeleteIdentityPool.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.awscore.exception.AwsServiceException;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.DeleteIdentityPoolRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteIdentityPool {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nidentityPoolId - The Id value of your identity pool.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nActions 850\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString identityPoold = args[0];\nCognitoIdentityClient cognitoIdClient = CognitoIdentityClient.builder()\n.region(Region.US_EAST_1)\n.credentialsProvider(ProfileCredentialsProvider.create())\n.build();\ndeleteIdPool(cognitoIdClient, identityPoold);\ncognitoIdClient.close();\n}\npublic static void deleteIdPool(CognitoIdentityClient cognitoIdClient, String\nidentityPoold) {\ntry {\nDeleteIdentityPoolRequest identityPoolRequest =\nDeleteIdentityPoolRequest.builder()\n.identityPoolId(identityPoold)\n.build();\ncognitoIdClient.deleteIdentityPool(identityPoolRequest);\nSystem.out.println(\"Done\");\n} catch (AwsServiceException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DeleteIdentityPool in AWS SDK for Java 2.x API Reference.\nGetCredentialsForIdentity\nThe following code example shows how to use GetCredentialsForIdentity.\nActions 851\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class GetIdentityCredentials {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nidentityId - The Id of an existing identity in the format\nREGION:GUID.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nActions 852\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString identityId = args[0];\nCognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()\n.region(Region.US_EAST_1)\n.build();\ngetCredsForIdentity(cognitoClient, identityId);\ncognitoClient.close();\n}\npublic static void getCredsForIdentity(CognitoIdentityClient cognitoClient,\nString identityId) {\ntry {\nGetCredentialsForIdentityRequest getCredentialsForIdentityRequest =\nGetCredentialsForIdentityRequest\n.builder()\n.identityId(identityId)\n.build();\nGetCredentialsForIdentityResponse response = cognitoClient\n.getCredentialsForIdentity(getCredentialsForIdentityRequest);\nSystem.out.println(\n\"Identity ID \" + response.identityId() + \", Access key ID \" +\nresponse.credentials().accessKeyId());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see GetCredentialsForIdentity in AWS SDK for Java 2.x API Reference.\nListIdentityPools\nThe following code example shows how to use ListIdentityPools.\nActions 853\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1271560, "end_char_idx": 1276008, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7f857d1c-41d4-46ed-98bf-e8774af5b6ca": {"__data__": {"id_": "7f857d1c-41d4-46ed-98bf-e8774af5b6ca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "68a7e795-4593-4de1-8243-0646853bf1ef", "node_type": "1", "metadata": {}, "hash": "7e97ab9d1cb03ff756b911fa5b2ce12bb8373880094cb8ea4c57e41dab54a898", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e03f4163-9818-4dc5-98ff-ab5dc3d63bf8", "node_type": "1", "metadata": {}, "hash": "a5a8088e7ba49e387fdde5fbefe3517421935a83898900e7d863a9eb8dbf75ca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ListIdentityPools\nThe following code example shows how to use ListIdentityPools.\nActions 853\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListIdentityPools {\npublic static void main(String[] args) {\nCognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()\n.region(Region.US_EAST_1)\n.build();\nlistIdPools(cognitoClient);\ncognitoClient.close();\n}\npublic static void listIdPools(CognitoIdentityClient cognitoClient) {\ntry {\nListIdentityPoolsRequest poolsRequest =\nListIdentityPoolsRequest.builder()\n.maxResults(15)\n.build();\nActions 854\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListIdentityPoolsResponse response =\ncognitoClient.listIdentityPools(poolsRequest);\nresponse.identityPools().forEach(pool -> {\nSystem.out.println(\"Pool ID: \" + pool.identityPoolId());\nSystem.out.println(\"Pool name: \" + pool.identityPoolName());\n});\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListIdentityPools in AWS SDK for Java 2.x API Reference.\nAmazon Cognito Identity Provider examples using SDK for Java\n2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon Cognito Identity Provider.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello Amazon Cognito\nThe following code examples show how to get started using Amazon Cognito.\nAmazon Cognito Identity Provider 855\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1275817, "end_char_idx": 1279304, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e03f4163-9818-4dc5-98ff-ab5dc3d63bf8": {"__data__": {"id_": "e03f4163-9818-4dc5-98ff-ab5dc3d63bf8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7f857d1c-41d4-46ed-98bf-e8774af5b6ca", "node_type": "1", "metadata": {}, "hash": "30dfe15350f4df002e96e68fc50373dc20a9b6690fde23d18896a24f20014ea0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "09411206-7ff8-4ba7-845d-c4a2c5203e83", "node_type": "1", "metadata": {}, "hash": "68b46bc68e56fc1e2694916373ebd125da577d4e24d212c95800872359b3bc97", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Get started\nHello Amazon Cognito\nThe following code examples show how to get started using Amazon Cognito.\nAmazon Cognito Identity Provider 855\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListUserPools {\npublic static void main(String[] args) {\nCognitoIdentityProviderClient cognitoClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\nlistAllUserPools(cognitoClient);\ncognitoClient.close();\n}\npublic static void listAllUserPools(CognitoIdentityProviderClient cognitoClient)\n{\ntry {\nListUserPoolsRequest request = ListUserPoolsRequest.builder()\n.maxResults(10)\nAmazon Cognito Identity Provider 856\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nListUserPoolsResponse response = cognitoClient.listUserPools(request);\nresponse.userPools().forEach(userpool -> {\nSystem.out.println(\"User pool \" + userpool.name() + \", User ID \" +\nuserpool.id());\n});\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListUserPools in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nAdminGetUser\nThe following code example shows how to use AdminGetUser.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void getAdminUser(CognitoIdentityProviderClient\nidentityProviderClient, String userName,\nString poolId) {\nActions 857\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nAdminGetUserRequest userRequest = AdminGetUserRequest.builder()\n.username(userName)\n.userPoolId(poolId)\n.build();\nAdminGetUserResponse response =\nidentityProviderClient.adminGetUser(userRequest);\nSystem.out.println(\"User status \" + response.userStatusAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see AdminGetUser in AWS SDK for Java 2.x API Reference.\nAdminInitiateAuth\nThe following code example shows how to use AdminInitiateAuth.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static AdminInitiateAuthResponse\ninitiateAuth(CognitoIdentityProviderClient identityProviderClient,\nString clientId, String userName, String password, String userPoolId) {\ntry {\nMap authParameters = new HashMap<>();\nauthParameters.put(\"USERNAME\", userName);\nauthParameters.put(\"PASSWORD\", password);\nAdminInitiateAuthRequest authRequest =\nAdminInitiateAuthRequest.builder()\nActions 858\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.clientId(clientId)\n.userPoolId(userPoolId)\n.authParameters(authParameters)\n.authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)\n.build();\nAdminInitiateAuthResponse response =\nidentityProviderClient.adminInitiateAuth(authRequest);\nSystem.out.println(\"Result Challenge is : \" + response.challengeName());\nreturn response;\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn null;\n}\n\u2022 For API details, see AdminInitiateAuth in AWS SDK for Java 2.x API Reference.\nAdminRespondToAuthChallenge\nThe following code example shows how to use AdminRespondToAuthChallenge.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Respond to an authentication challenge.", "mimetype": "text/plain", "start_char_idx": 1278426, "end_char_idx": 1282780, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "09411206-7ff8-4ba7-845d-c4a2c5203e83": {"__data__": {"id_": "09411206-7ff8-4ba7-845d-c4a2c5203e83", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e03f4163-9818-4dc5-98ff-ab5dc3d63bf8", "node_type": "1", "metadata": {}, "hash": "a5a8088e7ba49e387fdde5fbefe3517421935a83898900e7d863a9eb8dbf75ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "76cd9a09-e980-425f-a108-855ca0485815", "node_type": "1", "metadata": {}, "hash": "e423208fea90d3bad82977debe93c41a8f2cfcc891b6a94f134a1569b157621a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "AdminRespondToAuthChallenge\nThe following code example shows how to use AdminRespondToAuthChallenge.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Respond to an authentication challenge.\npublic static void adminRespondToAuthChallenge(CognitoIdentityProviderClient\nidentityProviderClient,\nString userName, String clientId, String mfaCode, String session) {\nSystem.out.println(\"SOFTWARE_TOKEN_MFA challenge is generated\");\nMap challengeResponses = new HashMap<>();\nchallengeResponses.put(\"USERNAME\", userName);\nActions 859\nAWS SDK for Java 2.x Developer Guide for version 2.x\nchallengeResponses.put(\"SOFTWARE_TOKEN_MFA_CODE\", mfaCode);\nAdminRespondToAuthChallengeRequest respondToAuthChallengeRequest =\nAdminRespondToAuthChallengeRequest.builder()\n.challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)\n.clientId(clientId)\n.challengeResponses(challengeResponses)\n.session(session)\n.build();\nAdminRespondToAuthChallengeResponse respondToAuthChallengeResult =\nidentityProviderClient\n.adminRespondToAuthChallenge(respondToAuthChallengeRequest);\nSystem.out.println(\"respondToAuthChallengeResult.getAuthenticationResult()\"\n+ respondToAuthChallengeResult.authenticationResult());\n}\n\u2022 For API details, see AdminRespondToAuthChallenge in AWS SDK for Java 2.x API Reference.\nAssociateSoftwareToken\nThe following code example shows how to use AssociateSoftwareToken.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static String getSecretForAppMFA(CognitoIdentityProviderClient\nidentityProviderClient, String session) {\nAssociateSoftwareTokenRequest softwareTokenRequest =\nAssociateSoftwareTokenRequest.builder()\n.session(session)\n.build();\nAssociateSoftwareTokenResponse tokenResponse = identityProviderClient\n.associateSoftwareToken(softwareTokenRequest);\nString secretCode = tokenResponse.secretCode();\nActions 860\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Enter this token into Google Authenticator\");\nSystem.out.println(secretCode);\nreturn tokenResponse.session();\n}\n\u2022 For API details, see AssociateSoftwareToken in AWS SDK for Java 2.x API Reference.\nConfirmSignUp\nThe following code example shows how to use ConfirmSignUp.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void confirmSignUp(CognitoIdentityProviderClient\nidentityProviderClient, String clientId, String code,\nString userName) {\ntry {\nConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder()\n.clientId(clientId)\n.confirmationCode(code)\n.username(userName)\n.build();\nidentityProviderClient.confirmSignUp(signUpRequest);\nSystem.out.println(userName + \" was confirmed\");\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see ConfirmSignUp in AWS SDK for Java 2.x API Reference.\nActions 861\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateUserPool\nThe following code example shows how to use CreateUserPool.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateUserPool {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nuserPoolName - The name to give your user pool when it's\ncreated.", "mimetype": "text/plain", "start_char_idx": 1282496, "end_char_idx": 1286752, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "76cd9a09-e980-425f-a108-855ca0485815": {"__data__": {"id_": "76cd9a09-e980-425f-a108-855ca0485815", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "09411206-7ff8-4ba7-845d-c4a2c5203e83", "node_type": "1", "metadata": {}, "hash": "68b46bc68e56fc1e2694916373ebd125da577d4e24d212c95800872359b3bc97", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6221e26f-61e7-40d0-ac0f-4fced0d13cd7", "node_type": "1", "metadata": {}, "hash": "c3454026e72cb992785a9d08cac34379b8919bb734a8d35e573cd5fd1ff7d666", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateUserPool {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nuserPoolName - The name to give your user pool when it's\ncreated.\n\"\"\";\nActions 862\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString userPoolName = args[0];\nCognitoIdentityProviderClient cognitoClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\nString id = createPool(cognitoClient, userPoolName);\nSystem.out.println(\"User pool ID: \" + id);\ncognitoClient.close();\n}\npublic static String createPool(CognitoIdentityProviderClient cognitoClient,\nString userPoolName) {\ntry {\nCreateUserPoolRequest request = CreateUserPoolRequest.builder()\n.poolName(userPoolName)\n.build();\nCreateUserPoolResponse response = cognitoClient.createUserPool(request);\nreturn response.userPool().id();\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see CreateUserPool in AWS SDK for Java 2.x API Reference.\nCreateUserPoolClient\nThe following code example shows how to use CreateUserPoolClient.\nActions 863\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientResponse;\n/**\n* A user pool client app is an application that authenticates with Amazon\n* Cognito user pools.\n* When you create a user pool, you can configure app clients that allow mobile\n* or web applications\n* to call API operations to authenticate users, manage user attributes and\n* profiles,\n* and implement sign-up and sign-in flows.\n*\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateUserPoolClient {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nclientName - The name for the user pool client to create.\nActions 864\nAWS SDK for Java 2.x Developer Guide for version 2.x\nuserPoolId - The ID for the user pool.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clientName = args[0];\nString userPoolId = args[1];\nCognitoIdentityProviderClient cognitoClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\ncreatePoolClient(cognitoClient, clientName, userPoolId);\ncognitoClient.close();\n}\npublic static void createPoolClient(CognitoIdentityProviderClient cognitoClient,\nString clientName,\nString userPoolId) {\ntry {\nCreateUserPoolClientRequest request =\nCreateUserPoolClientRequest.builder()\n.clientName(clientName)\n.userPoolId(userPoolId)\n.build();\nCreateUserPoolClientResponse response =\ncognitoClient.createUserPoolClient(request);\nSystem.out.println(\"User pool \" + response.userPoolClient().clientName()\n+ \" created. ID: \"\n+ response.userPoolClient().clientId());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see CreateUserPoolClient in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1285864, "end_char_idx": 1290345, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6221e26f-61e7-40d0-ac0f-4fced0d13cd7": {"__data__": {"id_": "6221e26f-61e7-40d0-ac0f-4fced0d13cd7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "76cd9a09-e980-425f-a108-855ca0485815", "node_type": "1", "metadata": {}, "hash": "e423208fea90d3bad82977debe93c41a8f2cfcc891b6a94f134a1569b157621a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5f06b8b1-0031-46dc-ad84-de548da0adfd", "node_type": "1", "metadata": {}, "hash": "6c248cfd8e4728002f74ad43b0eb74ba4917fa436ca5e4a72ce3c5d19e2edcab", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ID: \"\n+ response.userPoolClient().clientId());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see CreateUserPoolClient in AWS SDK for Java 2.x API Reference.\nActions 865\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListUserPools\nThe following code example shows how to use ListUserPools.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListUserPools {\npublic static void main(String[] args) {\nCognitoIdentityProviderClient cognitoClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\nlistAllUserPools(cognitoClient);\ncognitoClient.close();\n}\npublic static void listAllUserPools(CognitoIdentityProviderClient cognitoClient)\n{\nActions 866\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nListUserPoolsRequest request = ListUserPoolsRequest.builder()\n.maxResults(10)\n.build();\nListUserPoolsResponse response = cognitoClient.listUserPools(request);\nresponse.userPools().forEach(userpool -> {\nSystem.out.println(\"User pool \" + userpool.name() + \", User ID \" +\nuserpool.id());\n});\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListUserPools in AWS SDK for Java 2.x API Reference.\nListUsers\nThe following code example shows how to use ListUsers.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersResponse;\nActions 867\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListUsers {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nuserPoolId - The ID given to your user pool when it's created.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString userPoolId = args[0];\nCognitoIdentityProviderClient cognitoClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\nlistAllUsers(cognitoClient, userPoolId);\nlistUsersFilter(cognitoClient, userPoolId);\ncognitoClient.close();\n}\npublic static void listAllUsers(CognitoIdentityProviderClient cognitoClient,\nString userPoolId) {\ntry {\nListUsersRequest usersRequest = ListUsersRequest.builder()\n.userPoolId(userPoolId)\n.build();\nActions 868\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListUsersResponse response = cognitoClient.listUsers(usersRequest);\nresponse.users().forEach(user -> {\nSystem.out.println(\"User \" + user.username() + \" Status \" +\nuser.userStatus() + \" Created \"\n+ user.userCreateDate());\n});\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n// Shows how to list users by using a filter.", "mimetype": "text/plain", "start_char_idx": 1290091, "end_char_idx": 1294343, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5f06b8b1-0031-46dc-ad84-de548da0adfd": {"__data__": {"id_": "5f06b8b1-0031-46dc-ad84-de548da0adfd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6221e26f-61e7-40d0-ac0f-4fced0d13cd7", "node_type": "1", "metadata": {}, "hash": "c3454026e72cb992785a9d08cac34379b8919bb734a8d35e573cd5fd1ff7d666", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "93934fb7-7761-4cd6-b8aa-460de19efd70", "node_type": "1", "metadata": {}, "hash": "3e2d5f607c7d95400c1e474adcf3b282ffebc5fa27c4a774331f385dee7bed91", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static void listUsersFilter(CognitoIdentityProviderClient cognitoClient,\nString userPoolId) {\ntry {\nString filter = \"email = \\\"tblue@noserver.com\\\"\";\nListUsersRequest usersRequest = ListUsersRequest.builder()\n.userPoolId(userPoolId)\n.filter(filter)\n.build();\nListUsersResponse response = cognitoClient.listUsers(usersRequest);\nresponse.users().forEach(user -> {\nSystem.out.println(\"User with filter applied \" + user.username() + \"\nStatus \" + user.userStatus()\n+ \" Created \" + user.userCreateDate());\n});\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListUsers in AWS SDK for Java 2.x API Reference.\nActions 869\nAWS SDK for Java 2.x Developer Guide for version 2.x\nResendConfirmationCode\nThe following code example shows how to use ResendConfirmationCode.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void resendConfirmationCode(CognitoIdentityProviderClient\nidentityProviderClient, String clientId,\nString userName) {\ntry {\nResendConfirmationCodeRequest codeRequest =\nResendConfirmationCodeRequest.builder()\n.clientId(clientId)\n.username(userName)\n.build();\nResendConfirmationCodeResponse response =\nidentityProviderClient.resendConfirmationCode(codeRequest);\nSystem.out.println(\"Method of delivery is \" +\nresponse.codeDeliveryDetails().deliveryMediumAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see ResendConfirmationCode in AWS SDK for Java 2.x API Reference.\nSignUp\nThe following code example shows how to use SignUp.\nActions 870\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic static void signUp(CognitoIdentityProviderClient identityProviderClient,\nString clientId, String userName,\nString password, String email) {\nAttributeType userAttrs = AttributeType.builder()\n.name(\"email\")\n.value(email)\n.build();\nList userAttrsList = new ArrayList<>();\nuserAttrsList.add(userAttrs);\ntry {\nSignUpRequest signUpRequest = SignUpRequest.builder()\n.userAttributes(userAttrsList)\n.username(userName)\n.clientId(clientId)\n.password(password)\n.build();\nidentityProviderClient.signUp(signUpRequest);\nSystem.out.println(\"User has been signed up \");\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see SignUp in AWS SDK for Java 2.x API Reference.\nVerifySoftwareToken\nThe following code example shows how to use VerifySoftwareToken.\nActions 871\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Verify the TOTP and register for MFA.\npublic static void verifyTOTP(CognitoIdentityProviderClient\nidentityProviderClient, String session, String code) {\ntry {\nVerifySoftwareTokenRequest tokenRequest =\nVerifySoftwareTokenRequest.builder()\n.userCode(code)\n.session(session)\n.build();\nVerifySoftwareTokenResponse verifyResponse =\nidentityProviderClient.verifySoftwareToken(tokenRequest);\nSystem.out.println(\"The status of the token is \" +\nverifyResponse.statusAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n\u2022 For API details, see VerifySoftwareToken in AWS SDK for Java 2.x API Reference.\nScenarios\nSign up a user with a user pool that requires MFA\nThe following code example shows how to:\n\u2022 Sign up and confirm a user with a username, password, and email address.\n\u2022 Set up multi-factor authentication by associating an MFA application with the user.\nScenarios 872\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Sign in by using a password and an MFA code.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1294344, "end_char_idx": 1298553, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "93934fb7-7761-4cd6-b8aa-460de19efd70": {"__data__": {"id_": "93934fb7-7761-4cd6-b8aa-460de19efd70", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5f06b8b1-0031-46dc-ad84-de548da0adfd", "node_type": "1", "metadata": {}, "hash": "6c248cfd8e4728002f74ad43b0eb74ba4917fa436ca5e4a72ce3c5d19e2edcab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c1935cc9-41fc-45fb-899f-227d67e29c3f", "node_type": "1", "metadata": {}, "hash": "5d0574ced24e433a44cbbf1c38981080c85672b050240182fad65dfed3ad29ca", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Scenarios\nSign up a user with a user pool that requires MFA\nThe following code example shows how to:\n\u2022 Sign up and confirm a user with a username, password, and email address.\n\u2022 Set up multi-factor authentication by associating an MFA application with the user.\nScenarios 872\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Sign in by using a password and an MFA code.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminRespondToAuthChallengeRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AdminRespondToAuthChallengeResponse;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AssociateSoftwareTokenRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.AssociateSoftwareTokenResponse;\nimport software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;\nimport software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ConfirmSignUpRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ResendConfirmationCodeRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.ResendConfirmationCodeResponse;\nimport software.amazon.awssdk.services.cognitoidentityprovider.model.SignUpRequest;\nScenarios 873\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.VerifySoftwareTokenRequest;\nimport\nsoftware.amazon.awssdk.services.cognitoidentityprovider.model.VerifySoftwareTokenResponse;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS\n* CDK) script provided in this GitHub repo at\n* resources/cdk/cognito_scenario_user_pool_with_mfa.\n*\n* This code example performs the following operations:\n*\n* 1. Invokes the signUp method to sign up a user.\n* 2. Invokes the adminGetUser method to get the user's confirmation status.\n* 3. Invokes the ResendConfirmationCode method if the user requested another\n* code.\n* 4. Invokes the confirmSignUp method.\n* 5. Invokes the AdminInitiateAuth to sign in. This results in being prompted\n* to set up TOTP (time-based one-time password). (The response is\n* \u201cChallengeName\u201d: \u201cMFA_SETUP\u201d).\n* 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private\n* key. This can be used with Google Authenticator.\n* 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for\n* MFA.\n* 8. Invokes the AdminInitiateAuth to sign in again. This results in being\n* prompted to submit a TOTP (Response: \u201cChallengeName\u201d: \u201cSOFTWARE_TOKEN_MFA\u201d).\n* 9. Invokes the AdminRespondToAuthChallenge to get back a token.", "mimetype": "text/plain", "start_char_idx": 1298037, "end_char_idx": 1302049, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c1935cc9-41fc-45fb-899f-227d67e29c3f": {"__data__": {"id_": "c1935cc9-41fc-45fb-899f-227d67e29c3f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "93934fb7-7761-4cd6-b8aa-460de19efd70", "node_type": "1", "metadata": {}, "hash": "3e2d5f607c7d95400c1e474adcf3b282ffebc5fa27c4a774331f385dee7bed91", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "28ef4cae-07fe-46fa-a758-810fa89b9255", "node_type": "1", "metadata": {}, "hash": "17f3a19f91bf493f0eb24e05c9fc11ba113b8b57e0ceada7f91a1f9fda3f589e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* 4. Invokes the confirmSignUp method.\n* 5. Invokes the AdminInitiateAuth to sign in. This results in being prompted\n* to set up TOTP (time-based one-time password). (The response is\n* \u201cChallengeName\u201d: \u201cMFA_SETUP\u201d).\n* 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private\n* key. This can be used with Google Authenticator.\n* 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for\n* MFA.\n* 8. Invokes the AdminInitiateAuth to sign in again. This results in being\n* prompted to submit a TOTP (Response: \u201cChallengeName\u201d: \u201cSOFTWARE_TOKEN_MFA\u201d).\n* 9. Invokes the AdminRespondToAuthChallenge to get back a token.\n*/\npublic class CognitoMVP {\nScenarios 874\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws NoSuchAlgorithmException,\nInvalidKeyException {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\nclientId - The app client Id value that you can get from the AWS\nCDK script.\npoolId - The pool Id that you can get from the AWS CDK script.\\s\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clientId = args[0];\nString poolId = args[1];\nCognitoIdentityProviderClient identityProviderClient =\nCognitoIdentityProviderClient.builder()\n.region(Region.US_EAST_1)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon Cognito example scenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"*** Enter your user name\");\nScanner in = new Scanner(System.in);\nString userName = in.nextLine();\nSystem.out.println(\"*** Enter your password\");\nString password = in.nextLine();\nSystem.out.println(\"*** Enter your email\");\nString email = in.nextLine();\nSystem.out.println(\"1. Signing up \" + userName);\nsignUp(identityProviderClient, clientId, userName, password, email);\nScenarios 875\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Getting \" + userName + \" in the user pool\");\ngetAdminUser(identityProviderClient, userName, poolId);\nSystem.out\n.println(\"*** Conformation code sent to \" + userName + \". Would you\nlike to send a new code? (Yes/No)\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nString ans = in.nextLine();\nif (ans.compareTo(\"Yes\") == 0) {\nresendConfirmationCode(identityProviderClient, clientId, userName);\nSystem.out.println(\"3. Sending a new confirmation code\");\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. Enter confirmation code that was emailed\");\nString code = in.nextLine();\nconfirmSignUp(identityProviderClient, clientId, code, userName);\nSystem.out.println(\"Rechecking the status of \" + userName + \" in the user\npool\");\ngetAdminUser(identityProviderClient, userName, poolId);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"5. Invokes the initiateAuth to sign in\");\nAdminInitiateAuthResponse authResponse =\ninitiateAuth(identityProviderClient, clientId, userName, password,\npoolId);\nString mySession = authResponse.session();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Invokes the AssociateSoftwareToken method to generate\na TOTP key\");\nString newSession = getSecretForAppMFA(identityProviderClient, mySession);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nScenarios 876\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"*** Enter the 6-digit code displayed in Google\nAuthenticator\");\nString myCode = in.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Verify the TOTP and register for MFA\");\nverifyTOTP(identityProviderClient, newSession, myCode);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Re-enter a 6-digit code displayed in Google\nAuthenticator\");\nString mfaCode = in.nextLine();\nAdminInitiateAuthResponse authResponse1 =\ninitiateAuth(identityProviderClient, clientId, userName, password,\npoolId);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"9.", "mimetype": "text/plain", "start_char_idx": 1301398, "end_char_idx": 1305568, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "28ef4cae-07fe-46fa-a758-810fa89b9255": {"__data__": {"id_": "28ef4cae-07fe-46fa-a758-810fa89b9255", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c1935cc9-41fc-45fb-899f-227d67e29c3f", "node_type": "1", "metadata": {}, "hash": "5d0574ced24e433a44cbbf1c38981080c85672b050240182fad65dfed3ad29ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6162008e-079e-4a3c-a5bc-a2540b83b9f6", "node_type": "1", "metadata": {}, "hash": "259478638a25433780b2c2fe8aeda6640f7ce7c5fefcfeb961226c1ba25407dc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Verify the TOTP and register for MFA\");\nverifyTOTP(identityProviderClient, newSession, myCode);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Re-enter a 6-digit code displayed in Google\nAuthenticator\");\nString mfaCode = in.nextLine();\nAdminInitiateAuthResponse authResponse1 =\ninitiateAuth(identityProviderClient, clientId, userName, password,\npoolId);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"9. Invokes the AdminRespondToAuthChallenge\");\nString session2 = authResponse1.session();\nadminRespondToAuthChallenge(identityProviderClient, userName, clientId,\nmfaCode, session2);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"All Amazon Cognito operations were successfully\nperformed\");\nSystem.out.println(DASHES);\n}\n// Respond to an authentication challenge.\npublic static void adminRespondToAuthChallenge(CognitoIdentityProviderClient\nidentityProviderClient,\nString userName, String clientId, String mfaCode, String session) {\nSystem.out.println(\"SOFTWARE_TOKEN_MFA challenge is generated\");\nMap challengeResponses = new HashMap<>();\nchallengeResponses.put(\"USERNAME\", userName);\nchallengeResponses.put(\"SOFTWARE_TOKEN_MFA_CODE\", mfaCode);\nAdminRespondToAuthChallengeRequest respondToAuthChallengeRequest =\nAdminRespondToAuthChallengeRequest.builder()\nScenarios 877\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)\n.clientId(clientId)\n.challengeResponses(challengeResponses)\n.session(session)\n.build();\nAdminRespondToAuthChallengeResponse respondToAuthChallengeResult =\nidentityProviderClient\n.adminRespondToAuthChallenge(respondToAuthChallengeRequest);\nSystem.out.println(\"respondToAuthChallengeResult.getAuthenticationResult()\"\n+ respondToAuthChallengeResult.authenticationResult());\n}\n// Verify the TOTP and register for MFA.", "mimetype": "text/plain", "start_char_idx": 1305104, "end_char_idx": 1307000, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6162008e-079e-4a3c-a5bc-a2540b83b9f6": {"__data__": {"id_": "6162008e-079e-4a3c-a5bc-a2540b83b9f6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "28ef4cae-07fe-46fa-a758-810fa89b9255", "node_type": "1", "metadata": {}, "hash": "17f3a19f91bf493f0eb24e05c9fc11ba113b8b57e0ceada7f91a1f9fda3f589e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "69f67f25-1c48-475a-90aa-6e107406847c", "node_type": "1", "metadata": {}, "hash": "d0e8e8c3c3c430247803fee847c3ab20902efef4d1f19c288dc2dd99a9e27d2c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public static void verifyTOTP(CognitoIdentityProviderClient\nidentityProviderClient, String session, String code) {\ntry {\nVerifySoftwareTokenRequest tokenRequest =\nVerifySoftwareTokenRequest.builder()\n.userCode(code)\n.session(session)\n.build();\nVerifySoftwareTokenResponse verifyResponse =\nidentityProviderClient.verifySoftwareToken(tokenRequest);\nSystem.out.println(\"The status of the token is \" +\nverifyResponse.statusAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static AdminInitiateAuthResponse\ninitiateAuth(CognitoIdentityProviderClient identityProviderClient,\nString clientId, String userName, String password, String userPoolId) {\ntry {\nMap authParameters = new HashMap<>();\nauthParameters.put(\"USERNAME\", userName);\nauthParameters.put(\"PASSWORD\", password);\nAdminInitiateAuthRequest authRequest =\nAdminInitiateAuthRequest.builder()\nScenarios 878\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.clientId(clientId)\n.userPoolId(userPoolId)\n.authParameters(authParameters)\n.authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)\n.build();\nAdminInitiateAuthResponse response =\nidentityProviderClient.adminInitiateAuth(authRequest);\nSystem.out.println(\"Result Challenge is : \" + response.challengeName());\nreturn response;\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn null;\n}\npublic static String getSecretForAppMFA(CognitoIdentityProviderClient\nidentityProviderClient, String session) {\nAssociateSoftwareTokenRequest softwareTokenRequest =\nAssociateSoftwareTokenRequest.builder()\n.session(session)\n.build();\nAssociateSoftwareTokenResponse tokenResponse = identityProviderClient\n.associateSoftwareToken(softwareTokenRequest);\nString secretCode = tokenResponse.secretCode();\nSystem.out.println(\"Enter this token into Google Authenticator\");\nSystem.out.println(secretCode);\nreturn tokenResponse.session();\n}\npublic static void confirmSignUp(CognitoIdentityProviderClient\nidentityProviderClient, String clientId, String code,\nString userName) {\ntry {\nConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder()\n.clientId(clientId)\n.confirmationCode(code)\n.username(userName)\n.build();\nScenarios 879\nAWS SDK for Java 2.x Developer Guide for version 2.x\nidentityProviderClient.confirmSignUp(signUpRequest);\nSystem.out.println(userName + \" was confirmed\");\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void resendConfirmationCode(CognitoIdentityProviderClient\nidentityProviderClient, String clientId,\nString userName) {\ntry {\nResendConfirmationCodeRequest codeRequest =\nResendConfirmationCodeRequest.builder()\n.clientId(clientId)\n.username(userName)\n.build();\nResendConfirmationCodeResponse response =\nidentityProviderClient.resendConfirmationCode(codeRequest);\nSystem.out.println(\"Method of delivery is \" +\nresponse.codeDeliveryDetails().deliveryMediumAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void signUp(CognitoIdentityProviderClient identityProviderClient,\nString clientId, String userName,\nString password, String email) {\nAttributeType userAttrs = AttributeType.builder()\n.name(\"email\")\n.value(email)\n.build();\nList userAttrsList = new ArrayList<>();\nuserAttrsList.add(userAttrs);\ntry {\nSignUpRequest signUpRequest = SignUpRequest.builder()\n.userAttributes(userAttrsList)\n.username(userName)\nScenarios 880\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.clientId(clientId)\n.password(password)\n.build();\nidentityProviderClient.signUp(signUpRequest);\nSystem.out.println(\"User has been signed up \");\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void getAdminUser(CognitoIdentityProviderClient\nidentityProviderClient, String userName,\nString poolId) {\ntry {\nAdminGetUserRequest userRequest = AdminGetUserRequest.builder()\n.username(userName)\n.userPoolId(poolId)\n.build();\nAdminGetUserResponse response =\nidentityProviderClient.adminGetUser(userRequest);\nSystem.out.println(\"User status \" + response.userStatusAsString());\n} catch (CognitoIdentityProviderException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1307001, "end_char_idx": 1311543, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "69f67f25-1c48-475a-90aa-6e107406847c": {"__data__": {"id_": "69f67f25-1c48-475a-90aa-6e107406847c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6162008e-079e-4a3c-a5bc-a2540b83b9f6", "node_type": "1", "metadata": {}, "hash": "259478638a25433780b2c2fe8aeda6640f7ce7c5fefcfeb961226c1ba25407dc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "918cf268-cb13-4af0-ba78-7d147df5484e", "node_type": "1", "metadata": {}, "hash": "7718c501691233d8fe7cd9de998c2925241f6760d657a8eae3a00fd3d8fa0e8f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 AdminGetUser\n\u2022 AdminInitiateAuth\n\u2022 AdminRespondToAuthChallenge\n\u2022 AssociateSoftwareToken\n\u2022 ConfirmDevice\n\u2022 ConfirmSignUp\nScenarios 881\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 InitiateAuth\n\u2022 ListUsers\n\u2022 ResendConfirmationCode\n\u2022 RespondToAuthChallenge\n\u2022 SignUp\n\u2022 VerifySoftwareToken\nAmazon Comprehend examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon Comprehend.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateDocumentClassifier\nThe following code example shows how to use CreateDocumentClassifier.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nAmazon Comprehend 882\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport\nsoftware.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierRequest;\nimport\nsoftware.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierResponse;\nimport\nsoftware.amazon.awssdk.services.comprehend.model.DocumentClassifierInputDataConfig;\n/**\n* Before running this code example, you can setup the necessary resources, such\n* as the CSV file and IAM Roles, by following this document:\n* https://aws.amazon.com/blogs/machine-learning/building-a-custom-classifier-using-\namazon-comprehend/\n*\n* Also, set up your development environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DocumentClassifierDemo {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ndataAccessRoleArn - The ARN value of the role used for this\noperation.\ns3Uri - The Amazon S3 bucket that contains the CSV file.\ndocumentClassifierName - The name of the document classifier.\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString dataAccessRoleArn = args[0];\nString s3Uri = args[1];\nString documentClassifierName = args[2];\nActions 883\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\ncreateDocumentClassifier(comClient, dataAccessRoleArn, s3Uri,\ndocumentClassifierName);\ncomClient.close();\n}\npublic static void createDocumentClassifier(ComprehendClient comClient, String\ndataAccessRoleArn, String s3Uri,\nString documentClassifierName) {\ntry {\nDocumentClassifierInputDataConfig config =\nDocumentClassifierInputDataConfig.builder()\n.s3Uri(s3Uri)\n.build();\nCreateDocumentClassifierRequest createDocumentClassifierRequest =\nCreateDocumentClassifierRequest.builder()\n.documentClassifierName(documentClassifierName)\n.dataAccessRoleArn(dataAccessRoleArn)\n.languageCode(\"en\")\n.inputDataConfig(config)\n.build();\nCreateDocumentClassifierResponse createDocumentClassifierResult =\ncomClient\n.createDocumentClassifier(createDocumentClassifierRequest);\nString documentClassifierArn =\ncreateDocumentClassifierResult.documentClassifierArn();\nSystem.out.println(\"Document Classifier ARN: \" + documentClassifierArn);\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see CreateDocumentClassifier in AWS SDK for Java 2.x API Reference.\nActions 884\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDetectDominantLanguage\nThe following code example shows how to use DetectDominantLanguage.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1311544, "end_char_idx": 1315946, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "918cf268-cb13-4af0-ba78-7d147df5484e": {"__data__": {"id_": "918cf268-cb13-4af0-ba78-7d147df5484e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "69f67f25-1c48-475a-90aa-6e107406847c", "node_type": "1", "metadata": {}, "hash": "d0e8e8c3c3c430247803fee847c3ab20902efef4d1f19c288dc2dd99a9e27d2c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7a28b953-cec1-4079-99e3-b1a77f66e883", "node_type": "1", "metadata": {}, "hash": "6c76a3b1ded764f2b309d07731012ab4212a9a65189676f6e440ddd148008e5a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 884\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDetectDominantLanguage\nThe following code example shows how to use DetectDominantLanguage.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport\nsoftware.amazon.awssdk.services.comprehend.model.DetectDominantLanguageRequest;\nimport\nsoftware.amazon.awssdk.services.comprehend.model.DetectDominantLanguageResponse;\nimport software.amazon.awssdk.services.comprehend.model.DominantLanguage;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DetectLanguage {\npublic static void main(String[] args) {\n// Specify French text - \"It is raining today in Seattle\".\nString text = \"Il pleut aujourd'hui \u00e0 Seattle\";\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Calling DetectDominantLanguage\");\ndetectTheDominantLanguage(comClient, text);\ncomClient.close();\nActions 885\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\npublic static void detectTheDominantLanguage(ComprehendClient comClient, String\ntext) {\ntry {\nDetectDominantLanguageRequest request =\nDetectDominantLanguageRequest.builder()\n.text(text)\n.build();\nDetectDominantLanguageResponse resp =\ncomClient.detectDominantLanguage(request);\nList allLanList = resp.languages();\nfor (DominantLanguage lang : allLanList) {\nSystem.out.println(\"Language is \" + lang.languageCode());\n}\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DetectDominantLanguage in AWS SDK for Java 2.x API Reference.\nDetectEntities\nThe following code example shows how to use DetectEntities.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.DetectEntitiesRequest;\nActions 886\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.comprehend.model.DetectEntitiesResponse;\nimport software.amazon.awssdk.services.comprehend.model.Entity;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DetectEntities {\npublic static void main(String[] args) {\nString text = \"Amazon.com, Inc. is located in Seattle, WA and was founded\nJuly 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to\nblenders. Seattle is north of Portland and south of Vancouver, BC. Other notable\nSeattle - based companies are Starbucks and Boeing.\";\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Calling DetectEntities\");\ndetectAllEntities(comClient, text);\ncomClient.close();\n}\npublic static void detectAllEntities(ComprehendClient comClient, String text) {\ntry {\nDetectEntitiesRequest detectEntitiesRequest =\nDetectEntitiesRequest.builder()\n.text(text)\n.languageCode(\"en\")\n.build();\nDetectEntitiesResponse detectEntitiesResult =\ncomClient.detectEntities(detectEntitiesRequest);\nList entList = detectEntitiesResult.entities();\nfor (Entity entity : entList) {\nSystem.out.println(\"Entity text is \" + entity.text());\n}\nActions 887\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DetectEntities in AWS SDK for Java 2.x API Reference.\nDetectKeyPhrases\nThe following code example shows how to use DetectKeyPhrases.", "mimetype": "text/plain", "start_char_idx": 1315650, "end_char_idx": 1320131, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7a28b953-cec1-4079-99e3-b1a77f66e883": {"__data__": {"id_": "7a28b953-cec1-4079-99e3-b1a77f66e883", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "918cf268-cb13-4af0-ba78-7d147df5484e", "node_type": "1", "metadata": {}, "hash": "7718c501691233d8fe7cd9de998c2925241f6760d657a8eae3a00fd3d8fa0e8f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "29927a83-f3f6-46eb-b856-da473016e946", "node_type": "1", "metadata": {}, "hash": "d806f5c56f7c7142ca56062570d3f743befb26f3a7bb4e38956cfe2bc6d4aa99", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DetectKeyPhrases\nThe following code example shows how to use DetectKeyPhrases.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.DetectKeyPhrasesRequest;\nimport software.amazon.awssdk.services.comprehend.model.DetectKeyPhrasesResponse;\nimport software.amazon.awssdk.services.comprehend.model.KeyPhrase;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DetectKeyPhrases {\npublic static void main(String[] args) {\nString text = \"Amazon.com, Inc. is located in Seattle, WA and was founded\nJuly 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to\nActions 888\nAWS SDK for Java 2.x Developer Guide for version 2.x\nblenders. Seattle is north of Portland and south of Vancouver, BC. Other notable\nSeattle - based companies are Starbucks and Boeing.\";\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Calling DetectKeyPhrases\");\ndetectAllKeyPhrases(comClient, text);\ncomClient.close();\n}\npublic static void detectAllKeyPhrases(ComprehendClient comClient, String text)\n{\ntry {\nDetectKeyPhrasesRequest detectKeyPhrasesRequest =\nDetectKeyPhrasesRequest.builder()\n.text(text)\n.languageCode(\"en\")\n.build();\nDetectKeyPhrasesResponse detectKeyPhrasesResult =\ncomClient.detectKeyPhrases(detectKeyPhrasesRequest);\nList phraseList = detectKeyPhrasesResult.keyPhrases();\nfor (KeyPhrase keyPhrase : phraseList) {\nSystem.out.println(\"Key phrase text is \" + keyPhrase.text());\n}\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DetectKeyPhrases in AWS SDK for Java 2.x API Reference.\nDetectSentiment\nThe following code example shows how to use DetectSentiment.\nActions 889\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport software.amazon.awssdk.services.comprehend.model.DetectSentimentRequest;\nimport software.amazon.awssdk.services.comprehend.model.DetectSentimentResponse;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DetectSentiment {\npublic static void main(String[] args) {\nString text = \"Amazon.com, Inc. is located in Seattle, WA and was founded\nJuly 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to\nblenders. Seattle is north of Portland and south of Vancouver, BC. Other notable\nSeattle - based companies are Starbucks and Boeing.\";\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Calling DetectSentiment\");\ndetectSentiments(comClient, text);\ncomClient.close();\n}\npublic static void detectSentiments(ComprehendClient comClient, String text) {\ntry {\nDetectSentimentRequest detectSentimentRequest =\nDetectSentimentRequest.builder()\nActions 890\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.text(text)\n.languageCode(\"en\")\n.build();\nDetectSentimentResponse detectSentimentResult =\ncomClient.detectSentiment(detectSentimentRequest);\nSystem.out.println(\"The Neutral value is \" +\ndetectSentimentResult.sentimentScore().neutral());\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DetectSentiment in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1320053, "end_char_idx": 1324456, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "29927a83-f3f6-46eb-b856-da473016e946": {"__data__": {"id_": "29927a83-f3f6-46eb-b856-da473016e946", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7a28b953-cec1-4079-99e3-b1a77f66e883", "node_type": "1", "metadata": {}, "hash": "6c76a3b1ded764f2b309d07731012ab4212a9a65189676f6e440ddd148008e5a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1fdb3a24-7ad4-4cac-bb21-06392c698cef", "node_type": "1", "metadata": {}, "hash": "9ca9705057acefab7622dbb19568f54d31b508207d4657a296fe5a7ab2547642", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DetectSyntax\nThe following code example shows how to use DetectSyntax.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.comprehend.ComprehendClient;\nimport software.amazon.awssdk.services.comprehend.model.ComprehendException;\nimport software.amazon.awssdk.services.comprehend.model.DetectSyntaxRequest;\nimport software.amazon.awssdk.services.comprehend.model.DetectSyntaxResponse;\nimport software.amazon.awssdk.services.comprehend.model.SyntaxToken;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\nActions 891\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DetectSyntax {\npublic static void main(String[] args) {\nString text = \"Amazon.com, Inc. is located in Seattle, WA and was founded\nJuly 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to\nblenders. Seattle is north of Portland and south of Vancouver, BC. Other notable\nSeattle - based companies are Starbucks and Boeing.\";\nRegion region = Region.US_EAST_1;\nComprehendClient comClient = ComprehendClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Calling DetectSyntax\");\ndetectAllSyntax(comClient, text);\ncomClient.close();\n}\npublic static void detectAllSyntax(ComprehendClient comClient, String text) {\ntry {\nDetectSyntaxRequest detectSyntaxRequest = DetectSyntaxRequest.builder()\n.text(text)\n.languageCode(\"en\")\n.build();\nDetectSyntaxResponse detectSyntaxResult =\ncomClient.detectSyntax(detectSyntaxRequest);\nList syntaxTokens = detectSyntaxResult.syntaxTokens();\nfor (SyntaxToken token : syntaxTokens) {\nSystem.out.println(\"Language is \" + token.text());\nSystem.out.println(\"Part of speech is \" +\ntoken.partOfSpeech().tagAsString());\n}\n} catch (ComprehendException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\nActions 892\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see DetectSyntax in AWS SDK for Java 2.x API Reference.\nScenarios\nBuilding an Amazon Lex chatbot\nThe following code example shows how to create a chatbot to engage your website visitors.\nSDK for Java 2.x\nShows how to use the Amazon Lex API to create a Chatbot within a web application to engage\nyour web site visitors.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 Amazon Comprehend\n\u2022 Amazon Lex\n\u2022 Amazon Translate\nCreate a messaging application\nThe following code example shows how to create a messaging application by using Amazon SQS.\nSDK for Java 2.x\nShows how to use the Amazon SQS API to develop a Spring REST API that sends and retrieves\nmessages.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 Amazon Comprehend\n\u2022 Amazon SQS\nScenarios 893\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate an application to analyze customer feedback\nThe following code example shows how to create an application that analyzes customer comment\ncards, translates them from their original language, determines their sentiment, and generates an\naudio file from the translated text.\nSDK for Java 2.x\nThis example application analyzes and stores customer feedback cards. Specifically, it fulfills the\nneed of a fictitious hotel in New York City. The hotel receives feedback from guests in various\nlanguages in the form of physical comment cards. That feedback is uploaded into the app\nthrough a web client. After an image of a comment card is uploaded, the following steps occur:\n\u2022 Text is extracted from the image using Amazon Textract.\n\u2022 Amazon Comprehend determines the sentiment of the extracted text and its language.\n\u2022 The extracted text is translated to English using Amazon Translate.\n\u2022 Amazon Polly synthesizes an audio file from the extracted text.\nThe full app can be deployed with the AWS CDK. For source code and deployment instructions,\nsee the project in GitHub.\nServices used in this example\n\u2022 Amazon Comprehend\n\u2022 Lambda\n\u2022 Amazon Polly\n\u2022 Amazon Textract\n\u2022 Amazon Translate\nFirehose examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Firehose.", "mimetype": "text/plain", "start_char_idx": 1324457, "end_char_idx": 1329071, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1fdb3a24-7ad4-4cac-bb21-06392c698cef": {"__data__": {"id_": "1fdb3a24-7ad4-4cac-bb21-06392c698cef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "29927a83-f3f6-46eb-b856-da473016e946", "node_type": "1", "metadata": {}, "hash": "d806f5c56f7c7142ca56062570d3f743befb26f3a7bb4e38956cfe2bc6d4aa99", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f69b467b-fd2d-48f1-bf72-2ca2091eff21", "node_type": "1", "metadata": {}, "hash": "030642bc19fa6c2c5d81abbc43787bd109239e6a7a732493147e43a59cbe6516", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The hotel receives feedback from guests in various\nlanguages in the form of physical comment cards. That feedback is uploaded into the app\nthrough a web client. After an image of a comment card is uploaded, the following steps occur:\n\u2022 Text is extracted from the image using Amazon Textract.\n\u2022 Amazon Comprehend determines the sentiment of the extracted text and its language.\n\u2022 The extracted text is translated to English using Amazon Translate.\n\u2022 Amazon Polly synthesizes an audio file from the extracted text.\nThe full app can be deployed with the AWS CDK. For source code and deployment instructions,\nsee the project in GitHub.\nServices used in this example\n\u2022 Amazon Comprehend\n\u2022 Lambda\n\u2022 Amazon Polly\n\u2022 Amazon Textract\n\u2022 Amazon Translate\nFirehose examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Firehose.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nFirehose 894\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nPutRecord\nThe following code example shows how to use PutRecord.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Puts a record to the specified Amazon Kinesis Data Firehose delivery stream.\n*\n* @param record The record to be put to the delivery stream. The record must be\na {@link Map} of String keys and Object values.\n* @param deliveryStreamName The name of the Amazon Kinesis Data Firehose\ndelivery stream to which the record should be put.\n* @throws IllegalArgumentException if the input record or delivery stream name\nis null or empty.\n* @throws RuntimeException if there is an error putting the record to the\ndelivery stream.\n*/\npublic static void putRecord(Map record, String\ndeliveryStreamName) {\nif (record == null || deliveryStreamName == null ||\ndeliveryStreamName.isEmpty()) {\nthrow new IllegalArgumentException(\"Invalid input: record or delivery\nstream name cannot be null/empty\");\n}\nActions 895\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nString jsonRecord = new ObjectMapper().writeValueAsString(record);\nRecord firehoseRecord = Record.builder()\n.data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))\n.build();\nPutRecordRequest putRecordRequest = PutRecordRequest.builder()\n.deliveryStreamName(deliveryStreamName)\n.record(firehoseRecord)\n.build();\ngetFirehoseClient().putRecord(putRecordRequest);\nSystem.out.println(\"Record sent: \" + jsonRecord);\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to put record: \" + e.getMessage(),\ne);\n}\n}\n\u2022 For API details, see PutRecord in AWS SDK for Java 2.x API Reference.\nPutRecordBatch\nThe following code example shows how to use PutRecordBatch.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Puts a batch of records to an Amazon Kinesis Data Firehose delivery stream.", "mimetype": "text/plain", "start_char_idx": 1328148, "end_char_idx": 1331652, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f69b467b-fd2d-48f1-bf72-2ca2091eff21": {"__data__": {"id_": "f69b467b-fd2d-48f1-bf72-2ca2091eff21", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1fdb3a24-7ad4-4cac-bb21-06392c698cef", "node_type": "1", "metadata": {}, "hash": "9ca9705057acefab7622dbb19568f54d31b508207d4657a296fe5a7ab2547642", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ce76a1b7-3efd-4c1c-835a-220c70aeee8a", "node_type": "1", "metadata": {}, "hash": "8e1df987a459af1f1034d5f53745224192be4e30b4d0cf5c0c56c2cd54ea7fad", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "PutRecordBatch\nThe following code example shows how to use PutRecordBatch.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Puts a batch of records to an Amazon Kinesis Data Firehose delivery stream.\n*\n* @param records a list of maps representing the records to be sent\n* @param batchSize the maximum number of records to include in each\nbatch\nActions 896\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param deliveryStreamName the name of the Kinesis Data Firehose delivery\nstream\n* @throws IllegalArgumentException if the input parameters are invalid (null or\nempty)\n* @throws RuntimeException if there is an error putting the record\nbatch\n*/\npublic static void putRecordBatch(List> records, int\nbatchSize, String deliveryStreamName) {\nif (records == null || records.isEmpty() || deliveryStreamName == null ||\ndeliveryStreamName.isEmpty()) {\nthrow new IllegalArgumentException(\"Invalid input: records or delivery\nstream name cannot be null/empty\");\n}\nObjectMapper objectMapper = new ObjectMapper();\ntry {\nfor (int i = 0; i < records.size(); i += batchSize) {\nList> batch = records.subList(i, Math.min(i +\nbatchSize, records.size()));\nList batchRecords = batch.stream().map(record -> {\ntry {\nString jsonRecord = objectMapper.writeValueAsString(record);\nreturn Record.builder()\n.data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))\n.build();\n} catch (Exception e) {\nthrow new RuntimeException(\"Error creating Firehose record\",\ne);\n}\n}).collect(Collectors.toList());\nPutRecordBatchRequest request = PutRecordBatchRequest.builder()\n.deliveryStreamName(deliveryStreamName)\n.records(batchRecords)\n.build();\nPutRecordBatchResponse response =\ngetFirehoseClient().putRecordBatch(request);\nif (response.failedPutCount() > 0) {\nresponse.requestResponses().stream()\nActions 897\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.filter(r -> r.errorCode() != null)\n.forEach(r -> System.err.println(\"Failed record: \" +\nr.errorMessage()));\n}\nSystem.out.println(\"Batch sent with size: \" + batchRecords.size());\n}\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to put record batch: \" +\ne.getMessage(), e);\n}\n}\n\u2022 For API details, see PutRecordBatch in AWS SDK for Java 2.x API Reference.\nScenarios\nPut records to Firehose\nThe following code example shows how to use Firehose to process individual and batch records.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nThis example puts individual and batch records to Firehose.\n/**\n* Amazon Firehose Scenario example using Java V2 SDK.\n*\n* Demonstrates individual and batch record processing,\n* and monitoring Firehose delivery stream metrics.\n*/\npublic class FirehoseScenario {\nprivate static FirehoseClient firehoseClient;\nprivate static CloudWatchClient cloudWatchClient;\nScenarios 898\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ndeliveryStreamName - The Firehose delivery stream name.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString deliveryStreamName = args[0];\ntry {\n// Read and parse sample data.\nString jsonContent = readJsonFile(\"sample_records.json\");\nObjectMapper objectMapper = new ObjectMapper();\nList> sampleData =\nobjectMapper.readValue(jsonContent, new TypeReference<>() {});\n// Process individual records.\nSystem.out.println(\"Processing individual records...\");\nsampleData.subList(0, 100).forEach(record -> {\ntry {\nputRecord(record, deliveryStreamName);\n} catch (Exception e) {\nSystem.err.println(\"Error processing record: \" +\ne.getMessage());\n}\n});\n// Monitor metrics.\nmonitorMetrics(deliveryStreamName);\n// Process batch records.", "mimetype": "text/plain", "start_char_idx": 1331355, "end_char_idx": 1335272, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ce76a1b7-3efd-4c1c-835a-220c70aeee8a": {"__data__": {"id_": "ce76a1b7-3efd-4c1c-835a-220c70aeee8a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f69b467b-fd2d-48f1-bf72-2ca2091eff21", "node_type": "1", "metadata": {}, "hash": "030642bc19fa6c2c5d81abbc43787bd109239e6a7a732493147e43a59cbe6516", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cd94903c-ae7a-4c6e-939d-02d459e640bd", "node_type": "1", "metadata": {}, "hash": "b4cd05318e1d162be2215d0d036d4750cf8c92fd0d7a169649c9242c9675bef6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nreturn;\n}\nString deliveryStreamName = args[0];\ntry {\n// Read and parse sample data.\nString jsonContent = readJsonFile(\"sample_records.json\");\nObjectMapper objectMapper = new ObjectMapper();\nList> sampleData =\nobjectMapper.readValue(jsonContent, new TypeReference<>() {});\n// Process individual records.\nSystem.out.println(\"Processing individual records...\");\nsampleData.subList(0, 100).forEach(record -> {\ntry {\nputRecord(record, deliveryStreamName);\n} catch (Exception e) {\nSystem.err.println(\"Error processing record: \" +\ne.getMessage());\n}\n});\n// Monitor metrics.\nmonitorMetrics(deliveryStreamName);\n// Process batch records.\nSystem.out.println(\"Processing batch records...\");\nputRecordBatch(sampleData.subList(100, sampleData.size()), 500,\ndeliveryStreamName);\nmonitorMetrics(deliveryStreamName);\n} catch (Exception e) {\nSystem.err.println(\"Scenario failed: \" + e.getMessage());\nScenarios 899\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} finally {\ncloseClients();\n}\n}\nprivate static FirehoseClient getFirehoseClient() {\nif (firehoseClient == null) {\nfirehoseClient = FirehoseClient.create();\n}\nreturn firehoseClient;\n}\nprivate static CloudWatchClient getCloudWatchClient() {\nif (cloudWatchClient == null) {\ncloudWatchClient = CloudWatchClient.create();\n}\nreturn cloudWatchClient;\n}\n/**\n* Puts a record to the specified Amazon Kinesis Data Firehose delivery stream.\n*\n* @param record The record to be put to the delivery stream. The record must be\na {@link Map} of String keys and Object values.\n* @param deliveryStreamName The name of the Amazon Kinesis Data Firehose\ndelivery stream to which the record should be put.\n* @throws IllegalArgumentException if the input record or delivery stream name\nis null or empty.\n* @throws RuntimeException if there is an error putting the record to the\ndelivery stream.\n*/\npublic static void putRecord(Map record, String\ndeliveryStreamName) {\nif (record == null || deliveryStreamName == null ||\ndeliveryStreamName.isEmpty()) {\nthrow new IllegalArgumentException(\"Invalid input: record or delivery\nstream name cannot be null/empty\");\n}\ntry {\nString jsonRecord = new ObjectMapper().writeValueAsString(record);\nRecord firehoseRecord = Record.builder()\n.data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))\n.build();\nScenarios 900\nAWS SDK for Java 2.x Developer Guide for version 2.x\nPutRecordRequest putRecordRequest = PutRecordRequest.builder()\n.deliveryStreamName(deliveryStreamName)\n.record(firehoseRecord)\n.build();\ngetFirehoseClient().putRecord(putRecordRequest);\nSystem.out.println(\"Record sent: \" + jsonRecord);\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to put record: \" + e.getMessage(),\ne);\n}\n}\n/**\n* Puts a batch of records to an Amazon Kinesis Data Firehose delivery stream.", "mimetype": "text/plain", "start_char_idx": 1334568, "end_char_idx": 1337431, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cd94903c-ae7a-4c6e-939d-02d459e640bd": {"__data__": {"id_": "cd94903c-ae7a-4c6e-939d-02d459e640bd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ce76a1b7-3efd-4c1c-835a-220c70aeee8a", "node_type": "1", "metadata": {}, "hash": "8e1df987a459af1f1034d5f53745224192be4e30b4d0cf5c0c56c2cd54ea7fad", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "46e72a62-0366-4e16-8dee-9762f8055065", "node_type": "1", "metadata": {}, "hash": "6be8563643fc551c837f3041d79245f9be78828153220487346ff56c92fbcfcf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param records a list of maps representing the records to be sent\n* @param batchSize the maximum number of records to include in each\nbatch\n* @param deliveryStreamName the name of the Kinesis Data Firehose delivery\nstream\n* @throws IllegalArgumentException if the input parameters are invalid (null or\nempty)\n* @throws RuntimeException if there is an error putting the record\nbatch\n*/\npublic static void putRecordBatch(List> records, int\nbatchSize, String deliveryStreamName) {\nif (records == null || records.isEmpty() || deliveryStreamName == null ||\ndeliveryStreamName.isEmpty()) {\nthrow new IllegalArgumentException(\"Invalid input: records or delivery\nstream name cannot be null/empty\");\n}\nObjectMapper objectMapper = new ObjectMapper();\ntry {\nfor (int i = 0; i < records.size(); i += batchSize) {\nList> batch = records.subList(i, Math.min(i +\nbatchSize, records.size()));\nList batchRecords = batch.stream().map(record -> {\ntry {\nScenarios 901\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString jsonRecord = objectMapper.writeValueAsString(record);\nreturn Record.builder()\n.data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))\n.build();\n} catch (Exception e) {\nthrow new RuntimeException(\"Error creating Firehose record\",\ne);\n}\n}).collect(Collectors.toList());\nPutRecordBatchRequest request = PutRecordBatchRequest.builder()\n.deliveryStreamName(deliveryStreamName)\n.records(batchRecords)\n.build();\nPutRecordBatchResponse response =\ngetFirehoseClient().putRecordBatch(request);\nif (response.failedPutCount() > 0) {\nresponse.requestResponses().stream()\n.filter(r -> r.errorCode() != null)\n.forEach(r -> System.err.println(\"Failed record: \" +\nr.errorMessage()));\n}\nSystem.out.println(\"Batch sent with size: \" + batchRecords.size());\n}\n} catch (Exception e) {\nthrow new RuntimeException(\"Failed to put record batch: \" +\ne.getMessage(), e);\n}\n}\npublic static void monitorMetrics(String deliveryStreamName) {\nInstant endTime = Instant.now();\nInstant startTime = endTime.minusSeconds(600);\nList metrics = List.of(\"IncomingBytes\", \"IncomingRecords\",\n\"FailedPutCount\");\nmetrics.forEach(metric -> monitorMetric(metric, startTime, endTime,\ndeliveryStreamName));\n}\nScenarios 902\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static void monitorMetric(String metricName, Instant startTime, Instant\nendTime, String deliveryStreamName) {\ntry {\nGetMetricStatisticsRequest request =\nGetMetricStatisticsRequest.builder()\n.namespace(\"AWS/Firehose\")\n.metricName(metricName)\n.dimensions(Dimension.builder().name(\"DeliveryStreamName\").value(deliveryStreamName).build())\n.startTime(startTime)\n.endTime(endTime)\n.period(60)\n.statistics(Statistic.SUM)\n.build();\nGetMetricStatisticsResponse response =\ngetCloudWatchClient().getMetricStatistics(request);\ndouble totalSum =\nresponse.datapoints().stream().mapToDouble(Datapoint::sum).sum();\nSystem.out.println(metricName + \": \" + totalSum);\n} catch (Exception e) {\nSystem.err.println(\"Failed to monitor metric \" + metricName + \": \" +\ne.getMessage());\n}\n}\npublic static String readJsonFile(String fileName) {\ntry (InputStream inputStream =\nFirehoseScenario.class.getClassLoader().getResourceAsStream(fileName);\nScanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8)) {\nreturn scanner.useDelimiter(\"\\\\A\").next();\n} catch (Exception e) {\nthrow new RuntimeException(\"Error reading file: \" + fileName, e);\n}\n}\nprivate static void closeClients() {\ntry {\nif (firehoseClient != null) firehoseClient.close();\nif (cloudWatchClient != null) cloudWatchClient.close();\n} catch (Exception e) {\nSystem.err.println(\"Error closing clients: \" + e.getMessage());\n}\n}\nScenarios 903\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 PutRecord\n\u2022 PutRecordBatch\nAmazon DocumentDB examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon DocumentDB.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Serverless examples\nServerless examples\nInvoke a Lambda function from a Amazon DocumentDB trigger\nThe following code example shows how to implement a Lambda function that receives an event\ntriggered by receiving records from a DocumentDB change stream. The function retrieves the\nDocumentDB payload and logs the record contents.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1337432, "end_char_idx": 1342020, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "46e72a62-0366-4e16-8dee-9762f8055065": {"__data__": {"id_": "46e72a62-0366-4e16-8dee-9762f8055065", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cd94903c-ae7a-4c6e-939d-02d459e640bd", "node_type": "1", "metadata": {}, "hash": "b4cd05318e1d162be2215d0d036d4750cf8c92fd0d7a169649c9242c9675bef6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c32b579-e408-4ebf-b405-8aee63ada3c5", "node_type": "1", "metadata": {}, "hash": "0bac0e8fe94b2d97b6a66d8905a2c026985552be899df423139670075e5d5be3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 PutRecord\n\u2022 PutRecordBatch\nAmazon DocumentDB examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon DocumentDB.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Serverless examples\nServerless examples\nInvoke a Lambda function from a Amazon DocumentDB trigger\nThe following code example shows how to implement a Lambda function that receives an event\ntriggered by receiving records from a DocumentDB change stream. The function retrieves the\nDocumentDB payload and logs the record contents.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe Serverless examples repository.\nConsuming a Amazon DocumentDB event with Lambda using Java.\nimport java.util.List;\nimport java.util.Map;\nAmazon DocumentDB 904\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\npublic class Example implements RequestHandler, String> {\n@SuppressWarnings(\"unchecked\")\n@Override\npublic String handleRequest(Map event, Context context) {\nList> events = (List>)\nevent.get(\"events\");\nfor (Map record : events) {\nMap eventData = (Map)\nrecord.get(\"event\");\nprocessEventData(eventData);\n}\nreturn \"OK\";\n}\n@SuppressWarnings(\"unchecked\")\nprivate void processEventData(Map eventData) {\nString operationType = (String) eventData.get(\"operationType\");\nSystem.out.println(\"operationType: %s\".formatted(operationType));\nMap ns = (Map) eventData.get(\"ns\");\nString db = (String) ns.get(\"db\");\nSystem.out.println(\"db: %s\".formatted(db));\nString coll = (String) ns.get(\"coll\");\nSystem.out.println(\"coll: %s\".formatted(coll));\nMap fullDocument = (Map)\neventData.get(\"fullDocument\");\nSystem.out.println(\"fullDocument: %s\".formatted(fullDocument));\n}\n}\nServerless examples 905\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDynamoDB examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with DynamoDB.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nAWS community contributions are examples that were created and are maintained by multiple\nteams across AWS. To provide feedback, use the mechanism provided in the linked repositories.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello DynamoDB\nThe following code examples show how to get started using DynamoDB.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\nDynamoDB 906\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1341273, "end_char_idx": 1345271, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9c32b579-e408-4ebf-b405-8aee63ada3c5": {"__data__": {"id_": "9c32b579-e408-4ebf-b405-8aee63ada3c5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "46e72a62-0366-4e16-8dee-9762f8055065", "node_type": "1", "metadata": {}, "hash": "6be8563643fc551c837f3041d79245f9be78828153220487346ff56c92fbcfcf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "16927a4a-e956-4601-8fee-c448174c9cf6", "node_type": "1", "metadata": {}, "hash": "089e45bcfe09d51b6a69b4ca8cb44e15c635486955b74374e0767552b2e1bba8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Get started\nHello DynamoDB\nThe following code examples show how to get started using DynamoDB.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\nDynamoDB 906\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListTables {\npublic static void main(String[] args) {\nSystem.out.println(\"Listing your Amazon DynamoDB tables:\\n\");\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nlistAllTables(ddb);\nddb.close();\n}\npublic static void listAllTables(DynamoDbClient ddb) {\nboolean moreTables = true;\nString lastName = null;\nwhile (moreTables) {\ntry {\nListTablesResponse response = null;\nif (lastName == null) {\nListTablesRequest request = ListTablesRequest.builder().build();\nresponse = ddb.listTables(request);\n} else {\nListTablesRequest request = ListTablesRequest.builder()\n.exclusiveStartTableName(lastName).build();\nresponse = ddb.listTables(request);\n}\nList tableNames = response.tableNames();\nif (tableNames.size() > 0) {\nfor (String curName : tableNames) {\nSystem.out.format(\"* %s\\n\", curName);\n}\n} else {\nSystem.out.println(\"No tables found!\");\nSystem.exit(0);\n}\nlastName = response.lastEvaluatedTableName();\nDynamoDB 907\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (lastName == null) {\nmoreTables = false;\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSystem.out.println(\"\\nDone!\");\n}\n}\n\u2022 For API details, see ListTables in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\n\u2022 Serverless examples\n\u2022 AWS community contributions\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create a table that can hold movie data.\n\u2022 Put, get, and update a single movie in the table.\n\u2022 Write movie data to the table from a sample JSON file.\n\u2022 Query for movies that were released in a given year.\n\u2022 Scan for movies that were released in a range of years.\n\u2022 Delete a movie from the table, then delete the table.\nBasics 908\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nCreate a DynamoDB table.\n// Create a table with a Sort key.\npublic static void createTable(DynamoDbClient ddb, String tableName) {\nDynamoDbWaiter dbWaiter = ddb.waiter();\nArrayList attributeDefinitions = new ArrayList<>();\n// Define attributes.\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"year\")\n.attributeType(\"N\")\n.build());\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"title\")\n.attributeType(\"S\")\n.build());\nArrayList tableKey = new ArrayList<>();\nKeySchemaElement key = KeySchemaElement.builder()\n.attributeName(\"year\")\n.keyType(KeyType.HASH)\n.build();\nKeySchemaElement key2 = KeySchemaElement.builder()\n.attributeName(\"title\")\n.keyType(KeyType.RANGE)\n.build();\n// Add KeySchemaElement objects to the list.\ntableKey.add(key);\ntableKey.add(key2);\nCreateTableRequest request = CreateTableRequest.builder()\n.keySchema(tableKey)\nBasics 909\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n.attributeDefinitions(attributeDefinitions)\n.tableName(tableName)\n.build();\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.", "mimetype": "text/plain", "start_char_idx": 1344502, "end_char_idx": 1348780, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "16927a4a-e956-4601-8fee-c448174c9cf6": {"__data__": {"id_": "16927a4a-e956-4601-8fee-c448174c9cf6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c32b579-e408-4ebf-b405-8aee63ada3c5", "node_type": "1", "metadata": {}, "hash": "0bac0e8fe94b2d97b6a66d8905a2c026985552be899df423139670075e5d5be3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0db593f2-2b89-4b5d-b8af-0160bd04d0fe", "node_type": "1", "metadata": {}, "hash": "adc6e97879ab131513075a2e6b0dae1684dfa23fb3c9f26385d6375ff6487b0f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "tableKey.add(key);\ntableKey.add(key2);\nCreateTableRequest request = CreateTableRequest.builder()\n.keySchema(tableKey)\nBasics 909\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n.attributeDefinitions(attributeDefinitions)\n.tableName(tableName)\n.build();\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nString newTable = response.tableDescription().tableName();\nSystem.out.println(\"The \" + newTable + \" was successfully created.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nCreate a helper function to download and extract the sample JSON file.\n// Load data into the table.\npublic static void loadData(DynamoDbClient ddb, String tableName, String\nfileName) throws IOException {\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nDynamoDbTable mappedTable = enhancedClient.table(\"Movies\",\nTableSchema.fromBean(Movies.class));\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nIterator iter = rootNode.iterator();\nBasics 910\nAWS SDK for Java 2.x Developer Guide for version 2.x\nObjectNode currentNode;\nint t = 0;\nwhile (iter.hasNext()) {\n// Only add 200 Movies to the table.\nif (t == 200)\nbreak;\ncurrentNode = (ObjectNode) iter.next();\nint year = currentNode.path(\"year\").asInt();\nString title = currentNode.path(\"title\").asText();\nString info = currentNode.path(\"info\").toString();\nMovies movies = new Movies();\nmovies.setYear(year);\nmovies.setTitle(title);\nmovies.setInfo(info);\n// Put the data into the Amazon DynamoDB Movie table.\nmappedTable.putItem(movies);\nt++;\n}\n}\nGet an item from a table.\npublic static void getItem(DynamoDbClient ddb) {\nHashMap keyToGet = new HashMap<>();\nkeyToGet.put(\"year\", AttributeValue.builder()\n.n(\"1933\")\n.build());\nkeyToGet.put(\"title\", AttributeValue.builder()\n.s(\"King Kong\")\n.build());\nGetItemRequest request = GetItemRequest.builder()\n.key(keyToGet)\n.tableName(\"Movies\")\n.build();\ntry {\nBasics 911\nAWS SDK for Java 2.x Developer Guide for version 2.x\nMap returnedItem = ddb.getItem(request).item();\nif (returnedItem != null) {\nSet keys = returnedItem.keySet();\nSystem.out.println(\"Amazon DynamoDB table attributes: \\n\");\nfor (String key1 : keys) {\nSystem.out.format(\"%s: %s\\n\", key1,\nreturnedItem.get(key1).toString());\n}\n} else {\nSystem.out.format(\"No item found with the key %s!\\n\", \"year\");\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nFull example.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This Java example performs these tasks:\n*\n* 1. Creates the Amazon DynamoDB Movie table with partition and sort key.\n* 2. Puts data into the Amazon DynamoDB table from a JSON document using the\n* Enhanced client.\n* 3. Gets data from the Movie table.\n* 4. Adds a new item.\n* 5. Updates an item.\n* 6. Uses a Scan to query items using the Enhanced client.\n* 7. Queries all items where the year is 2013 using the Enhanced Client.\n* 8. Deletes the table.\n*/\nBasics 912\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class Scenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws IOException {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nfileName - The path to the moviedata.json file that you can\ndownload from the Amazon DynamoDB Developer Guide.", "mimetype": "text/plain", "start_char_idx": 1348195, "end_char_idx": 1352376, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0db593f2-2b89-4b5d-b8af-0160bd04d0fe": {"__data__": {"id_": "0db593f2-2b89-4b5d-b8af-0160bd04d0fe", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "16927a4a-e956-4601-8fee-c448174c9cf6", "node_type": "1", "metadata": {}, "hash": "089e45bcfe09d51b6a69b4ca8cb44e15c635486955b74374e0767552b2e1bba8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "64c8d0bb-8cd1-446c-b5e0-9c06ed848049", "node_type": "1", "metadata": {}, "hash": "bf58890484c491860c19242cd90b906162b453f050bfd040ff58a5968ede6d8b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* 2. Puts data into the Amazon DynamoDB table from a JSON document using the\n* Enhanced client.\n* 3. Gets data from the Movie table.\n* 4. Adds a new item.\n* 5. Updates an item.\n* 6. Uses a Scan to query items using the Enhanced client.\n* 7. Queries all items where the year is 2013 using the Enhanced Client.\n* 8. Deletes the table.\n*/\nBasics 912\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class Scenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws IOException {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nfileName - The path to the moviedata.json file that you can\ndownload from the Amazon DynamoDB Developer Guide.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = \"Movies\";\nString fileName = args[0];\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon DynamoDB example scenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\n\"1. Creating an Amazon DynamoDB table named Movies with a key named\nyear and a sort key named title.\");\ncreateTable(ddb, tableName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Loading data into the Amazon DynamoDB table.\");\nloadData(ddb, tableName, fileName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nBasics 913\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"3. Getting data from the Movie table.\");\ngetItem(ddb);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. Putting a record into the Amazon DynamoDB table.\");\nputRecord(ddb);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"5. Updating a record.\");\nupdateTableItem(ddb, tableName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Scanning the Amazon DynamoDB table.\");\nscanMovies(ddb, tableName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Querying the Movies released in 2013.\");\nqueryTable(ddb);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Deleting the Amazon DynamoDB table.\");\ndeleteDynamoDBTable(ddb, tableName);\nSystem.out.println(DASHES);\nddb.close();\n}\n// Create a table with a Sort key.\npublic static void createTable(DynamoDbClient ddb, String tableName) {\nDynamoDbWaiter dbWaiter = ddb.waiter();\nArrayList attributeDefinitions = new ArrayList<>();\n// Define attributes.\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"year\")\n.attributeType(\"N\")\n.build());\nattributeDefinitions.add(AttributeDefinition.builder()\nBasics 914\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.attributeName(\"title\")\n.attributeType(\"S\")\n.build());\nArrayList tableKey = new ArrayList<>();\nKeySchemaElement key = KeySchemaElement.builder()\n.attributeName(\"year\")\n.keyType(KeyType.HASH)\n.build();\nKeySchemaElement key2 = KeySchemaElement.builder()\n.attributeName(\"title\")\n.keyType(KeyType.RANGE)\n.build();\n// Add KeySchemaElement objects to the list.\ntableKey.add(key);\ntableKey.add(key2);\nCreateTableRequest request = CreateTableRequest.builder()\n.keySchema(tableKey)\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n.attributeDefinitions(attributeDefinitions)\n.tableName(tableName)\n.build();\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nString newTable = response.tableDescription().tableName();\nSystem.out.println(\"The \" + newTable + \" was successfully created.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nBasics 915\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n// Query the table.", "mimetype": "text/plain", "start_char_idx": 1351651, "end_char_idx": 1355874, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "64c8d0bb-8cd1-446c-b5e0-9c06ed848049": {"__data__": {"id_": "64c8d0bb-8cd1-446c-b5e0-9c06ed848049", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0db593f2-2b89-4b5d-b8af-0160bd04d0fe", "node_type": "1", "metadata": {}, "hash": "adc6e97879ab131513075a2e6b0dae1684dfa23fb3c9f26385d6375ff6487b0f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b276ae0c-0050-420d-a8ea-cd5bafd9ea12", "node_type": "1", "metadata": {}, "hash": "798a98a7c5aa2058ece28c624a1581850e6b81b6cf3e9276e8b578d4bcd89fbf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "WaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nString newTable = response.tableDescription().tableName();\nSystem.out.println(\"The \" + newTable + \" was successfully created.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nBasics 915\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\n}\n// Query the table.\npublic static void queryTable(DynamoDbClient ddb) {\ntry {\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nDynamoDbTable custTable = enhancedClient.table(\"Movies\",\nTableSchema.fromBean(Movies.class));\nQueryConditional queryConditional = QueryConditional\n.keyEqualTo(Key.builder()\n.partitionValue(2013)\n.build());\n// Get items in the table and write out the ID value.\nIterator results =\ncustTable.query(queryConditional).items().iterator();\nString result = \"\";\nwhile (results.hasNext()) {\nMovies rec = results.next();\nSystem.out.println(\"The title of the movie is \" + rec.getTitle());\nSystem.out.println(\"The movie information is \" + rec.getInfo());\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n// Scan the table.\npublic static void scanMovies(DynamoDbClient ddb, String tableName) {\nSystem.out.println(\"******* Scanning all movies.\\n\");\ntry {\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nBasics 916\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDynamoDbTable custTable = enhancedClient.table(\"Movies\",\nTableSchema.fromBean(Movies.class));\nIterator results = custTable.scan().items().iterator();\nwhile (results.hasNext()) {\nMovies rec = results.next();\nSystem.out.println(\"The movie title is \" + rec.getTitle());\nSystem.out.println(\"The movie year is \" + rec.getYear());\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n// Load data into the table.\npublic static void loadData(DynamoDbClient ddb, String tableName, String\nfileName) throws IOException {\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nDynamoDbTable mappedTable = enhancedClient.table(\"Movies\",\nTableSchema.fromBean(Movies.class));\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nIterator iter = rootNode.iterator();\nObjectNode currentNode;\nint t = 0;\nwhile (iter.hasNext()) {\n// Only add 200 Movies to the table.\nif (t == 200)\nbreak;\ncurrentNode = (ObjectNode) iter.next();\nint year = currentNode.path(\"year\").asInt();\nString title = currentNode.path(\"title\").asText();\nString info = currentNode.path(\"info\").toString();\nMovies movies = new Movies();\nmovies.setYear(year);\nmovies.setTitle(title);\nmovies.setInfo(info);\nBasics 917\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Put the data into the Amazon DynamoDB Movie table.\nmappedTable.putItem(movies);\nt++;\n}\n}\n// Update the record to include show only directors.\npublic static void updateTableItem(DynamoDbClient ddb, String tableName) {\nHashMap itemKey = new HashMap<>();\nitemKey.put(\"year\", AttributeValue.builder().n(\"1933\").build());\nitemKey.put(\"title\", AttributeValue.builder().s(\"King Kong\").build());\nHashMap updatedValues = new HashMap<>();\nupdatedValues.put(\"info\", AttributeValueUpdate.builder()\n.value(AttributeValue.builder().s(\"{\\\"directors\\\":[\\\"Merian C.\nCooper\\\",\\\"Ernest B. Schoedsack\\\"]\")\n.build())\n.action(AttributeAction.PUT)\n.build());\nUpdateItemRequest request = UpdateItemRequest.builder()\n.tableName(tableName)\n.key(itemKey)\n.attributeUpdates(updatedValues)\n.build();\ntry {\nddb.updateItem(request);\n} catch (ResourceNotFoundException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Item was updated!", "mimetype": "text/plain", "start_char_idx": 1355406, "end_char_idx": 1359522, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b276ae0c-0050-420d-a8ea-cd5bafd9ea12": {"__data__": {"id_": "b276ae0c-0050-420d-a8ea-cd5bafd9ea12", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "64c8d0bb-8cd1-446c-b5e0-9c06ed848049", "node_type": "1", "metadata": {}, "hash": "bf58890484c491860c19242cd90b906162b453f050bfd040ff58a5968ede6d8b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cb3f6cd2-ea68-4eb1-bd88-f3db54d029de", "node_type": "1", "metadata": {}, "hash": "2f60073a6686ce10ffe26fe7a350d10d7e8d4844d4b91952ecfd51819365510e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\npublic static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {\nDeleteTableRequest request = DeleteTableRequest.builder()\n.tableName(tableName)\n.build();\nBasics 918\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nddb.deleteTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(tableName + \" was successfully deleted!\");\n}\npublic static void putRecord(DynamoDbClient ddb) {\ntry {\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nDynamoDbTable table = enhancedClient.table(\"Movies\",\nTableSchema.fromBean(Movies.class));\n// Populate the Table.\nMovies record = new Movies();\nrecord.setYear(2020);\nrecord.setTitle(\"My Movie2\");\nrecord.setInfo(\"no info\");\ntable.putItem(record);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Added a new movie to the table.\");\n}\npublic static void getItem(DynamoDbClient ddb) {\nHashMap keyToGet = new HashMap<>();\nkeyToGet.put(\"year\", AttributeValue.builder()\n.n(\"1933\")\n.build());\nkeyToGet.put(\"title\", AttributeValue.builder()\n.s(\"King Kong\")\n.build());\nBasics 919\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetItemRequest request = GetItemRequest.builder()\n.key(keyToGet)\n.tableName(\"Movies\")\n.build();\ntry {\nMap returnedItem = ddb.getItem(request).item();\nif (returnedItem != null) {\nSet keys = returnedItem.keySet();\nSystem.out.println(\"Amazon DynamoDB table attributes: \\n\");\nfor (String key1 : keys) {\nSystem.out.format(\"%s: %s\\n\", key1,\nreturnedItem.get(key1).toString());\n}\n} else {\nSystem.out.format(\"No item found with the key %s!\\n\", \"year\");\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 BatchWriteItem\n\u2022 CreateTable\n\u2022 DeleteItem\n\u2022 DeleteTable\n\u2022 DescribeTable\n\u2022 GetItem\n\u2022 PutItem\n\u2022 Query\n\u2022 Scan\nBasics 920\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 UpdateItem\nActions\nBatchGetItem\nThe following code example shows how to use BatchGetItem.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nShows how to get batch items using the service client.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;\nimport software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n/**\n* Before running this Java V2 code example, set up your development environment,\nincluding your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class BatchReadItems {\npublic static void main(String[] args){\nfinal String usage = \"\"\"\nUsage:\n\nActions 921\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWhere:\ntableName - The Amazon DynamoDB table (for example, Music).\\s\n\"\"\";\nString tableName = \"Music\";\nRegion region = Region.US_EAST_1;\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.region(region)\n.build();\ngetBatchItems(dynamoDbClient, tableName);\n}\npublic static void getBatchItems(DynamoDbClient dynamoDbClient, String\ntableName) {\n// Define the primary key values for the items you want to retrieve.\nMap key1 = new HashMap<>();\nkey1.put(\"Artist\", AttributeValue.builder().s(\"Artist1\").build());\nMap key2 = new HashMap<>();\nkey2.put(\"Artist\", AttributeValue.builder().s(\"Artist2\").build());\n// Construct the batchGetItem request.", "mimetype": "text/plain", "start_char_idx": 1359522, "end_char_idx": 1363540, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "cb3f6cd2-ea68-4eb1-bd88-f3db54d029de": {"__data__": {"id_": "cb3f6cd2-ea68-4eb1-bd88-f3db54d029de", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b276ae0c-0050-420d-a8ea-cd5bafd9ea12", "node_type": "1", "metadata": {}, "hash": "798a98a7c5aa2058ece28c624a1581850e6b81b6cf3e9276e8b578d4bcd89fbf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "46ad5aa4-1cdb-4a93-8031-8cc5b1c7df4e", "node_type": "1", "metadata": {}, "hash": "49594696e2f84a1ea058b9cc3bd9c39b6f6ca50b07594c337c05c33ef0d1490a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Map key1 = new HashMap<>();\nkey1.put(\"Artist\", AttributeValue.builder().s(\"Artist1\").build());\nMap key2 = new HashMap<>();\nkey2.put(\"Artist\", AttributeValue.builder().s(\"Artist2\").build());\n// Construct the batchGetItem request.\nMap requestItems = new HashMap<>();\nrequestItems.put(tableName, KeysAndAttributes.builder()\n.keys(List.of(key1, key2))\n.projectionExpression(\"Artist, SongTitle\")\n.build());\nBatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()\n.requestItems(requestItems)\n.build();\n// Make the batchGetItem request.\nBatchGetItemResponse batchGetItemResponse =\ndynamoDbClient.batchGetItem(batchGetItemRequest);\n// Extract and print the retrieved items.\nMap>> responses =\nbatchGetItemResponse.responses();\nif (responses.containsKey(tableName)) {\nList> musicItems = responses.get(tableName);\nfor (Map item : musicItems) {\nActions 922\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Artist: \" + item.get(\"Artist\").s() +\n\", SongTitle: \" + item.get(\"SongTitle\").s());\n}\n} else {\nSystem.out.println(\"No items retrieved.\");\n}\n}\n}\nShows how to get batch items using the service client and a paginator.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\npublic class BatchGetItemsPaginator {\npublic static void main(String[] args){\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ntableName - The Amazon DynamoDB table (for example, Music).\\s\n\"\"\";\nString tableName = \"Music\";\nRegion region = Region.US_EAST_1;\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.region(region)\n.build();\ngetBatchItemsPaginator(dynamoDbClient, tableName) ;\n}\nActions 923\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void getBatchItemsPaginator(DynamoDbClient dynamoDbClient, String\ntableName) {\n// Define the primary key values for the items you want to retrieve.\nMap key1 = new HashMap<>();\nkey1.put(\"Artist\", AttributeValue.builder().s(\"Artist1\").build());\nMap key2 = new HashMap<>();\nkey2.put(\"Artist\", AttributeValue.builder().s(\"Artist2\").build());\n// Construct the batchGetItem request.\nMap requestItems = new HashMap<>();\nrequestItems.put(tableName, KeysAndAttributes.builder()\n.keys(List.of(key1, key2))\n.projectionExpression(\"Artist, SongTitle\")\n.build());\nBatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()\n.requestItems(requestItems)\n.build();\n// Use batchGetItemPaginator for paginated requests.\ndynamoDbClient.batchGetItemPaginator(batchGetItemRequest).stream()\n.flatMap(response -> response.responses().getOrDefault(tableName,\nCollections.emptyList()).stream())\n.forEach(item -> {\nSystem.out.println(\"Artist: \" + item.get(\"Artist\").s() +\n\", SongTitle: \" + item.get(\"SongTitle\").s());\n});\n}\n}\n\u2022 For API details, see BatchGetItem in AWS SDK for Java 2.x API Reference.\nBatchWriteItem\nThe following code example shows how to use BatchWriteItem.\nActions 924\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nInserts many items into a table by using the service client.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.PutRequest;\nimport software.amazon.awssdk.services.dynamodb.model.WriteRequest;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n/**\n* Before running this Java V2 code example, set up your development environment,\nincluding your credentials.", "mimetype": "text/plain", "start_char_idx": 1363264, "end_char_idx": 1367739, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "46ad5aa4-1cdb-4a93-8031-8cc5b1c7df4e": {"__data__": {"id_": "46ad5aa4-1cdb-4a93-8031-8cc5b1c7df4e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cb3f6cd2-ea68-4eb1-bd88-f3db54d029de", "node_type": "1", "metadata": {}, "hash": "2f60073a6686ce10ffe26fe7a350d10d7e8d4844d4b91952ecfd51819365510e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "092998f5-f360-4b7e-a923-f3234b01dc27", "node_type": "1", "metadata": {}, "hash": "5eec0c23ce400c6526ccfff099c896090b13bb4fcd16c8b7a290b4bf4e596725", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nInserts many items into a table by using the service client.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.PutRequest;\nimport software.amazon.awssdk.services.dynamodb.model.WriteRequest;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n/**\n* Before running this Java V2 code example, set up your development environment,\nincluding your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class BatchWriteItems {\npublic static void main(String[] args){\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ntableName - The Amazon DynamoDB table (for example, Music).\\s\n\"\"\";\nString tableName = \"Music\";\nActions 925\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRegion region = Region.US_EAST_1;\nDynamoDbClient dynamoDbClient = DynamoDbClient.builder()\n.region(region)\n.build();\naddBatchItems(dynamoDbClient, tableName);\n}\npublic static void addBatchItems(DynamoDbClient dynamoDbClient, String\ntableName) {\n// Specify the updates you want to perform.\nList writeRequests = new ArrayList<>();\n// Set item 1.\nMap item1Attributes = new HashMap<>();\nitem1Attributes.put(\"Artist\",\nAttributeValue.builder().s(\"Artist1\").build());\nitem1Attributes.put(\"Rating\", AttributeValue.builder().s(\"5\").build());\nitem1Attributes.put(\"Comments\", AttributeValue.builder().s(\"Great\nsong!\").build());\nitem1Attributes.put(\"SongTitle\",\nAttributeValue.builder().s(\"SongTitle1\").build());\nwriteRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1Attributes).build()).build());\n// Set item 2.\nMap item2Attributes = new HashMap<>();\nitem2Attributes.put(\"Artist\",\nAttributeValue.builder().s(\"Artist2\").build());\nitem2Attributes.put(\"Rating\", AttributeValue.builder().s(\"4\").build());\nitem2Attributes.put(\"Comments\", AttributeValue.builder().s(\"Nice\nmelody.\").build());\nitem2Attributes.put(\"SongTitle\",\nAttributeValue.builder().s(\"SongTitle2\").build());\nwriteRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2Attributes).build()).build());\ntry {\n// Create the BatchWriteItemRequest.\nBatchWriteItemRequest batchWriteItemRequest =\nBatchWriteItemRequest.builder()\n.requestItems(Map.of(tableName, writeRequests))\n.build();\nActions 926\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Execute the BatchWriteItem operation.\nBatchWriteItemResponse batchWriteItemResponse =\ndynamoDbClient.batchWriteItem(batchWriteItemRequest);\n// Process the response.\nSystem.out.println(\"Batch write successful: \" + batchWriteItemResponse);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\nInserts many items into a table by using the enhanced client.\nimport com.example.dynamodb.Customer;\nimport com.example.dynamodb.Music;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;\nimport software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;\nimport software.amazon.awssdk.enhanced.dynamodb.Key;\nimport software.amazon.awssdk.enhanced.dynamodb.TableSchema;\nimport software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;\nimport software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport java.time.Instant;\nimport java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.ZoneOffset;\n/*\n* Before running this code example, create an Amazon DynamoDB table named Customer\nwith these columns:\n* - id - the id of the record that is the key\n* - custName - the customer name\n* - email - the email value\n* - registrationDate - an instant value when the item was added to the table\n*\n* Also, ensure that you have set up your development environment, including your\ncredentials.", "mimetype": "text/plain", "start_char_idx": 1366830, "end_char_idx": 1371332, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "092998f5-f360-4b7e-a923-f3234b01dc27": {"__data__": {"id_": "092998f5-f360-4b7e-a923-f3234b01dc27", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "46ad5aa4-1cdb-4a93-8031-8cc5b1c7df4e", "node_type": "1", "metadata": {}, "hash": "49594696e2f84a1ea058b9cc3bd9c39b6f6ca50b07594c337c05c33ef0d1490a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bedab5ce-352c-440e-b9a4-92f6f016d218", "node_type": "1", "metadata": {}, "hash": "1c4467629b35287d8caebb19b01eed573a77253a5f0dc8e45ff1818362b4debe", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 927\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For information, see this documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class EnhancedBatchWriteItems {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nDynamoDbEnhancedClient enhancedClient =\nDynamoDbEnhancedClient.builder()\n.dynamoDbClient(ddb)\n.build();\nputBatchRecords(enhancedClient);\nddb.close();\n}\npublic static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) {\ntry {\nDynamoDbTable customerMappedTable =\nenhancedClient.table(\"Customer\",\nTableSchema.fromBean(Customer.class));\nDynamoDbTable musicMappedTable =\nenhancedClient.table(\"Music\",\nTableSchema.fromBean(Music.class));\nLocalDate localDate = LocalDate.parse(\"2020-04-07\");\nLocalDateTime localDateTime = localDate.atStartOfDay();\nInstant instant = localDateTime.toInstant(ZoneOffset.UTC);\nCustomer record2 = new Customer();\nrecord2.setCustName(\"Fred Pink\");\nrecord2.setId(\"id110\");\nrecord2.setEmail(\"fredp@noserver.com\");\nrecord2.setRegistrationDate(instant);\nCustomer record3 = new Customer();\nrecord3.setCustName(\"Susan Pink\");\nrecord3.setId(\"id120\");\nrecord3.setEmail(\"spink@noserver.com\");\nrecord3.setRegistrationDate(instant);\nCustomer record4 = new Customer();\nActions 928\nAWS SDK for Java 2.x Developer Guide for version 2.x\nrecord4.setCustName(\"Jerry orange\");\nrecord4.setId(\"id101\");\nrecord4.setEmail(\"jorange@noserver.com\");\nrecord4.setRegistrationDate(instant);\nBatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest\n= BatchWriteItemEnhancedRequest\n.builder()\n.writeBatches(\nWriteBatch.builder(Customer.class) // add items to the Customer\n// table\n.mappedTableResource(customerMappedTable)\n.addPutItem(builder -> builder.item(record2))\n.addPutItem(builder -> builder.item(record3))\n.addPutItem(builder -> builder.item(record4))\n.build(),\nWriteBatch.builder(Music.class) // delete an item from the Music\n// table\n.mappedTableResource(musicMappedTable)\n.addDeleteItem(builder -> builder.key(\nKey.builder().partitionValue(\n\"Famous Band\")\n.build()))\n.build())\n.build();\n// Add three items to the Customer table and delete one item\nfrom the Music\n// table.\nenhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);\nActions 929\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"done\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see BatchWriteItem in AWS SDK for Java 2.x API Reference.\nCreateTable\nThe following code example shows how to use CreateTable.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.core.waiters.WaiterResponse;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;\nimport software.amazon.awssdk.services.dynamodb.model.KeyType;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;\nimport software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;\nimport software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\nActions 930\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateTable {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to create (for example,\nMusic3).\nkey - The key for the Amazon DynamoDB table (for example,\nArtist).", "mimetype": "text/plain", "start_char_idx": 1371333, "end_char_idx": 1375733, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "bedab5ce-352c-440e-b9a4-92f6f016d218": {"__data__": {"id_": "bedab5ce-352c-440e-b9a4-92f6f016d218", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "092998f5-f360-4b7e-a923-f3234b01dc27", "node_type": "1", "metadata": {}, "hash": "5eec0c23ce400c6526ccfff099c896090b13bb4fcd16c8b7a290b4bf4e596725", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a70dca95-2537-4239-8fac-4dcc1b59921a", "node_type": "1", "metadata": {}, "hash": "d91d64d49a19304357c9fe8a7368e3db36a14f45dfa1910e13ff94e499eb30bb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 930\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateTable {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to create (for example,\nMusic3).\nkey - The key for the Amazon DynamoDB table (for example,\nArtist).\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nString key = args[1];\nSystem.out.println(\"Creating an Amazon DynamoDB table \" + tableName + \" with\na simple primary key: \" + key);\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nString result = createTable(ddb, tableName, key);\nSystem.out.println(\"New table is \" + result);\nddb.close();\n}\npublic static String createTable(DynamoDbClient ddb, String tableName, String\nkey) {\nDynamoDbWaiter dbWaiter = ddb.waiter();\nCreateTableRequest request = CreateTableRequest.builder()\n.attributeDefinitions(AttributeDefinition.builder()\n.attributeName(key)\nActions 931\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.attributeType(ScalarAttributeType.S)\n.build())\n.keySchema(KeySchemaElement.builder()\n.attributeName(key)\n.keyType(KeyType.HASH)\n.build())\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n.tableName(tableName)\n.build();\nString newTable;\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nnewTable = response.tableDescription().tableName();\nreturn newTable;\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see CreateTable in AWS SDK for Java 2.x API Reference.\nDeleteItem\nThe following code example shows how to use DeleteItem.\nActions 932\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport java.util.HashMap;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteItem {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to delete the item from\n(for example, Music3).\nkey - The key used in the Amazon DynamoDB table (for example,\nArtist).\\s\nkeyval - The key value that represents the item to delete (for\nexample, Famous Band).", "mimetype": "text/plain", "start_char_idx": 1375253, "end_char_idx": 1378701, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a70dca95-2537-4239-8fac-4dcc1b59921a": {"__data__": {"id_": "a70dca95-2537-4239-8fac-4dcc1b59921a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bedab5ce-352c-440e-b9a4-92f6f016d218", "node_type": "1", "metadata": {}, "hash": "1c4467629b35287d8caebb19b01eed573a77253a5f0dc8e45ff1818362b4debe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f845c4dc-57f1-4d68-922b-9f30ec090790", "node_type": "1", "metadata": {}, "hash": "4eda155c36a54174d8816395a858a2bc24d01b8b174c7358f1486f874bd53aa9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteItem {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to delete the item from\n(for example, Music3).\nkey - The key used in the Amazon DynamoDB table (for example,\nArtist).\\s\nkeyval - The key value that represents the item to delete (for\nexample, Famous Band).\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\nActions 933\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nString tableName = args[0];\nString key = args[1];\nString keyVal = args[2];\nSystem.out.format(\"Deleting item \\\"%s\\\" from %s\\n\", keyVal, tableName);\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\ndeleteDynamoDBItem(ddb, tableName, key, keyVal);\nddb.close();\n}\npublic static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName,\nString key, String keyVal) {\nHashMap keyToGet = new HashMap<>();\nkeyToGet.put(key, AttributeValue.builder()\n.s(keyVal)\n.build());\nDeleteItemRequest deleteReq = DeleteItemRequest.builder()\n.tableName(tableName)\n.key(keyToGet)\n.build();\ntry {\nddb.deleteItem(deleteReq);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DeleteItem in AWS SDK for Java 2.x API Reference.\nDeleteTable\nThe following code example shows how to use DeleteTable.\nActions 934\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteTable {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ntableName - The Amazon DynamoDB table to delete (for example,\nMusic3).\n**Warning** This program will delete the table that you specify!\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nActions 935\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.format(\"Deleting the Amazon DynamoDB table %s...\\n\", tableName);\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\ndeleteDynamoDBTable(ddb, tableName);\nddb.close();\n}\npublic static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {\nDeleteTableRequest request = DeleteTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nddb.deleteTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(tableName + \" was successfully deleted!\");\n}\n}\n\u2022 For API details, see DeleteTable in AWS SDK for Java 2.x API Reference.\nDescribeTable\nThe following code example shows how to use DescribeTable.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nActions 936\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;\nimport\nsoftware.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;\nimport software.amazon.awssdk.services.dynamodb.model.TableDescription;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1378172, "end_char_idx": 1382482, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f845c4dc-57f1-4d68-922b-9f30ec090790": {"__data__": {"id_": "f845c4dc-57f1-4d68-922b-9f30ec090790", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a70dca95-2537-4239-8fac-4dcc1b59921a", "node_type": "1", "metadata": {}, "hash": "d91d64d49a19304357c9fe8a7368e3db36a14f45dfa1910e13ff94e499eb30bb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "97bf1c8f-ba03-4ad0-962e-5ff694d26ffb", "node_type": "1", "metadata": {}, "hash": "606bdb2b546dc9c9f76b2b850abe55ecec74c28aac3c0de6958d9187714ca830", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeTable\nThe following code example shows how to use DescribeTable.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nActions 936\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;\nimport\nsoftware.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;\nimport software.amazon.awssdk.services.dynamodb.model.TableDescription;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeTable {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ntableName - The Amazon DynamoDB table to get information about\n(for example, Music3).\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nSystem.out.format(\"Getting description for %s\\n\\n\", tableName);\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\ndescribeDymamoDBTable(ddb, tableName);\nddb.close();\n}\nActions 937\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) {\nDescribeTableRequest request = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nTableDescription tableInfo = ddb.describeTable(request).table();\nif (tableInfo != null) {\nSystem.out.format(\"Table name : %s\\n\", tableInfo.tableName());\nSystem.out.format(\"Table ARN : %s\\n\", tableInfo.tableArn());\nSystem.out.format(\"Status : %s\\n\", tableInfo.tableStatus());\nSystem.out.format(\"Item count : %d\\n\", tableInfo.itemCount());\nSystem.out.format(\"Size (bytes): %d\\n\", tableInfo.tableSizeBytes());\nProvisionedThroughputDescription throughputInfo =\ntableInfo.provisionedThroughput();\nSystem.out.println(\"Throughput\");\nSystem.out.format(\" Read Capacity : %d\\n\",\nthroughputInfo.readCapacityUnits());\nSystem.out.format(\" Write Capacity: %d\\n\",\nthroughputInfo.writeCapacityUnits());\nList attributes =\ntableInfo.attributeDefinitions();\nSystem.out.println(\"Attributes\");\nfor (AttributeDefinition a : attributes) {\nSystem.out.format(\" %s (%s)\\n\", a.attributeName(),\na.attributeType());\n}\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"\\nDone!\");\n}\n}\n\u2022 For API details, see DescribeTable in AWS SDK for Java 2.x API Reference.\nActions 938\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeTimeToLive\nThe following code example shows how to use DescribeTimeToLive.\nSDK for Java 2.x\nDescribe TTL configuration on an existing DynamoDB table.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveRequest;\nimport software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveResponse;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport java.util.Optional;\nfinal DescribeTimeToLiveRequest request =\nDescribeTimeToLiveRequest.builder()\n.tableName(tableName)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal DescribeTimeToLiveResponse response =\nddb.describeTimeToLive(request);\nSystem.out.println(tableName + \" description of time to live is \"\n+ response.toString());\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n\u2022 For API details, see DescribeTimeToLive in AWS SDK for Java 2.x API Reference.\nActions 939\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetItem\nThe following code example shows how to use GetItem.", "mimetype": "text/plain", "start_char_idx": 1381572, "end_char_idx": 1386012, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "97bf1c8f-ba03-4ad0-962e-5ff694d26ffb": {"__data__": {"id_": "97bf1c8f-ba03-4ad0-962e-5ff694d26ffb", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f845c4dc-57f1-4d68-922b-9f30ec090790", "node_type": "1", "metadata": {}, "hash": "4eda155c36a54174d8816395a858a2bc24d01b8b174c7358f1486f874bd53aa9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7cb96e58-31f6-4726-b46f-a463ed56652f", "node_type": "1", "metadata": {}, "hash": "0c38aa0ff938f6c28d32f77ee4c625a8791ae014efcb40c5d06bd9e39511e541", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions 939\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetItem\nThe following code example shows how to use GetItem.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nGets an item from a table by using the DynamoDbClient.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.GetItemRequest;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2,\n* its better practice to use the\n* Enhanced Client, see the EnhancedGetItem example.\n*/\npublic class GetItem {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\nActions 940\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntableName - The Amazon DynamoDB table from which an item is\nretrieved (for example, Music3).\\s\nkey - The key used in the Amazon DynamoDB table (for example,\nArtist).\\s\nkeyval - The key value that represents the item to get (for\nexample, Famous Band).\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nString key = args[1];\nString keyVal = args[2];\nSystem.out.format(\"Retrieving item \\\"%s\\\" from \\\"%s\\\"\\n\", keyVal,\ntableName);\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\ngetDynamoDBItem(ddb, tableName, key, keyVal);\nddb.close();\n}\npublic static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String\nkey, String keyVal) {\nHashMap keyToGet = new HashMap<>();\nkeyToGet.put(key, AttributeValue.builder()\n.s(keyVal)\n.build());\nGetItemRequest request = GetItemRequest.builder()\n.key(keyToGet)\n.tableName(tableName)\n.build();\ntry {\n// If there is no matching item, GetItem does not return any data.\nMap returnedItem = ddb.getItem(request).item();\nif (returnedItem.isEmpty())\nSystem.out.format(\"No item found with the key %s!\\n\", key);\nActions 941\nAWS SDK for Java 2.x Developer Guide for version 2.x\nelse {\nSet keys = returnedItem.keySet();\nSystem.out.println(\"Amazon DynamoDB table attributes: \\n\");\nfor (String key1 : keys) {\nSystem.out.format(\"%s: %s\\n\", key1,\nreturnedItem.get(key1).toString());\n}\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see GetItem in AWS SDK for Java 2.x API Reference.\nListTables\nThe following code example shows how to use ListTables.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1385887, "end_char_idx": 1389544, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7cb96e58-31f6-4726-b46f-a463ed56652f": {"__data__": {"id_": "7cb96e58-31f6-4726-b46f-a463ed56652f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "97bf1c8f-ba03-4ad0-962e-5ff694d26ffb", "node_type": "1", "metadata": {}, "hash": "606bdb2b546dc9c9f76b2b850abe55ecec74c28aac3c0de6958d9187714ca830", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e1241607-efd2-4fef-b738-d669bd1b4dcc", "node_type": "1", "metadata": {}, "hash": "cf5e55c6ecbc8533c6b5a904f38fc265059005121ac2325ff45571c33ee6f7d8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ListTables\nThe following code example shows how to use ListTables.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\nActions 942\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListTables {\npublic static void main(String[] args) {\nSystem.out.println(\"Listing your Amazon DynamoDB tables:\\n\");\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nlistAllTables(ddb);\nddb.close();\n}\npublic static void listAllTables(DynamoDbClient ddb) {\nboolean moreTables = true;\nString lastName = null;\nwhile (moreTables) {\ntry {\nListTablesResponse response = null;\nif (lastName == null) {\nListTablesRequest request = ListTablesRequest.builder().build();\nresponse = ddb.listTables(request);\n} else {\nListTablesRequest request = ListTablesRequest.builder()\n.exclusiveStartTableName(lastName).build();\nresponse = ddb.listTables(request);\n}\nList tableNames = response.tableNames();\nif (tableNames.size() > 0) {\nfor (String curName : tableNames) {\nSystem.out.format(\"* %s\\n\", curName);\n}\n} else {\nSystem.out.println(\"No tables found!\");\nSystem.exit(0);\n}\nlastName = response.lastEvaluatedTableName();\nif (lastName == null) {\nmoreTables = false;\nActions 943\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nSystem.out.println(\"\\nDone!\");\n}\n}\n\u2022 For API details, see ListTables in AWS SDK for Java 2.x API Reference.\nPutItem\nThe following code example shows how to use PutItem.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nPuts an item into a table using DynamoDbClient.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.PutItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.PutItemResponse;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport java.util.HashMap;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\nActions 944\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,\n* its better practice to use the\n* Enhanced Client. See the EnhancedPutItem example.\n*/\npublic class PutItem {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \n \nWhere:\ntableName - The Amazon DynamoDB table in which an item is placed\n(for example, Music3).\nkey - The key used in the Amazon DynamoDB table (for example,\nArtist).\nkeyval - The key value that represents the item to get (for\nexample, Famous Band).\nalbumTitle - The Album title (for example, AlbumTitle).\nAlbumTitleValue - The name of the album (for example, Songs\nAbout Life ).\nAwards - The awards column (for example, Awards).\nAwardVal - The value of the awards (for example, 10).\nSongTitle - The song title (for example, SongTitle).\nSongTitleVal - The value of the song title (for example, Happy\nDay).\n**Warning** This program will place an item that you specify into a\ntable!", "mimetype": "text/plain", "start_char_idx": 1388869, "end_char_idx": 1393176, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e1241607-efd2-4fef-b738-d669bd1b4dcc": {"__data__": {"id_": "e1241607-efd2-4fef-b738-d669bd1b4dcc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7cb96e58-31f6-4726-b46f-a463ed56652f", "node_type": "1", "metadata": {}, "hash": "0c38aa0ff938f6c28d32f77ee4c625a8791ae014efcb40c5d06bd9e39511e541", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "20357f6b-7cf0-4c3a-87a0-9e256b0f918b", "node_type": "1", "metadata": {}, "hash": "d02fb0f2dceccc46a28fe1cbb89fcc448f59afa0853da77170975fb4025be81e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "key - The key used in the Amazon DynamoDB table (for example,\nArtist).\nkeyval - The key value that represents the item to get (for\nexample, Famous Band).\nalbumTitle - The Album title (for example, AlbumTitle).\nAlbumTitleValue - The name of the album (for example, Songs\nAbout Life ).\nAwards - The awards column (for example, Awards).\nAwardVal - The value of the awards (for example, 10).\nSongTitle - The song title (for example, SongTitle).\nSongTitleVal - The value of the song title (for example, Happy\nDay).\n**Warning** This program will place an item that you specify into a\ntable!\n\"\"\";\nif (args.length != 9) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nString key = args[1];\nString keyVal = args[2];\nString albumTitle = args[3];\nString albumTitleValue = args[4];\nActions 945\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString awards = args[5];\nString awardVal = args[6];\nString songTitle = args[7];\nString songTitleVal = args[8];\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nputItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue,\nawards, awardVal, songTitle,\nsongTitleVal);\nSystem.out.println(\"Done!\");\nddb.close();\n}\npublic static void putItemInTable(DynamoDbClient ddb,\nString tableName,\nString key,\nString keyVal,\nString albumTitle,\nString albumTitleValue,\nString awards,\nString awardVal,\nString songTitle,\nString songTitleVal) {\nHashMap itemValues = new HashMap<>();\nitemValues.put(key, AttributeValue.builder().s(keyVal).build());\nitemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());\nitemValues.put(albumTitle,\nAttributeValue.builder().s(albumTitleValue).build());\nitemValues.put(awards, AttributeValue.builder().s(awardVal).build());\nPutItemRequest request = PutItemRequest.builder()\n.tableName(tableName)\n.item(itemValues)\n.build();\ntry {\nPutItemResponse response = ddb.putItem(request);\nSystem.out.println(tableName + \" was successfully updated. The request\nid is \"\nActions 946\nAWS SDK for Java 2.x Developer Guide for version 2.x\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.err.println(\"Be sure that it exists and that you've typed its\nname correctly!\");\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see PutItem in AWS SDK for Java 2.x API Reference.\nQuery\nThe following code example shows how to use Query.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nQueries a table by using DynamoDbClient.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.QueryRequest;\nimport software.amazon.awssdk.services.dynamodb.model.QueryResponse;\nimport java.util.HashMap;\n/**\n* Before running this Java V2 code example, set up your development\nActions 947\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To query items from an Amazon DynamoDB table using the AWS SDK for Java V2,\n* its better practice to use the\n* Enhanced Client. See the EnhancedQueryRecords example.\n*/\npublic class Query {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to put the item in (for\nexample, Music3).\npartitionKeyName - The partition key name of the Amazon DynamoDB\ntable (for example, Artist).\npartitionKeyVal - The value of the partition key that should\nmatch (for example, Famous Band).", "mimetype": "text/plain", "start_char_idx": 1392592, "end_char_idx": 1396716, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "20357f6b-7cf0-4c3a-87a0-9e256b0f918b": {"__data__": {"id_": "20357f6b-7cf0-4c3a-87a0-9e256b0f918b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e1241607-efd2-4fef-b738-d669bd1b4dcc", "node_type": "1", "metadata": {}, "hash": "cf5e55c6ecbc8533c6b5a904f38fc265059005121ac2325ff45571c33ee6f7d8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ebd0f2b8-4630-4110-9082-1b3331f9023d", "node_type": "1", "metadata": {}, "hash": "0ea9a4cd7dc6e9d1852c112f626dea6e7f88954c1105ee0969ee29830183c924", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To query items from an Amazon DynamoDB table using the AWS SDK for Java V2,\n* its better practice to use the\n* Enhanced Client. See the EnhancedQueryRecords example.\n*/\npublic class Query {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table to put the item in (for\nexample, Music3).\npartitionKeyName - The partition key name of the Amazon DynamoDB\ntable (for example, Artist).\npartitionKeyVal - The value of the partition key that should\nmatch (for example, Famous Band).\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nString partitionKeyName = args[1];\nString partitionKeyVal = args[2];\n// For more information about an alias, see:\n// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/\nExpressions.ExpressionAttributeNames.html\nString partitionAlias = \"#a\";\nSystem.out.format(\"Querying %s\", tableName);\nSystem.out.println(\"\");\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\nActions 948\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.region(region)\n.build();\nint count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal,\npartitionAlias);\nSystem.out.println(\"There were \" + count + \" record(s) returned\");\nddb.close();\n}\npublic static int queryTable(DynamoDbClient ddb, String tableName, String\npartitionKeyName, String partitionKeyVal,\nString partitionAlias) {\n// Set up an alias for the partition key name in case it's a reserved word.\nHashMap attrNameAlias = new HashMap();\nattrNameAlias.put(partitionAlias, partitionKeyName);\n// Set up mapping of the partition name with the value.\nHashMap attrValues = new HashMap<>();\nattrValues.put(\":\" + partitionKeyName, AttributeValue.builder()\n.s(partitionKeyVal)\n.build());\nQueryRequest queryReq = QueryRequest.builder()\n.tableName(tableName)\n.keyConditionExpression(partitionAlias + \" = :\" + partitionKeyName)\n.expressionAttributeNames(attrNameAlias)\n.expressionAttributeValues(attrValues)\n.build();\ntry {\nQueryResponse response = ddb.query(queryReq);\nreturn response.count();\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nreturn -1;\n}\n}\nQueries a table by using DynamoDbClient and a secondary index.\nActions 949\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.QueryRequest;\nimport software.amazon.awssdk.services.dynamodb.model.QueryResponse;\nimport java.util.HashMap;\nimport java.util.Map;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* Create the Movies table by running the Scenario example and loading the Movie\n* data from the JSON file. Next create a secondary\n* index for the Movies table that uses only the year column. Name the index\n* **year-index**.", "mimetype": "text/plain", "start_char_idx": 1395975, "end_char_idx": 1399503, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ebd0f2b8-4630-4110-9082-1b3331f9023d": {"__data__": {"id_": "ebd0f2b8-4630-4110-9082-1b3331f9023d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "20357f6b-7cf0-4c3a-87a0-9e256b0f918b", "node_type": "1", "metadata": {}, "hash": "d02fb0f2dceccc46a28fe1cbb89fcc448f59afa0853da77170975fb4025be81e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b698a3ed-d031-4c92-8db0-243384051955", "node_type": "1", "metadata": {}, "hash": "5200b6fc04a339776537ed2119b5025e7fa26b4e330882219438030411e56f3d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* Create the Movies table by running the Scenario example and loading the Movie\n* data from the JSON file. Next create a secondary\n* index for the Movies table that uses only the year column. Name the index\n* **year-index**. For more information, see:\n*\n* https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html\n*/\npublic class QueryItemsUsingIndex {\npublic static void main(String[] args) {\nString tableName = \"Movies\";\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nqueryIndex(ddb, tableName);\nddb.close();\n}\npublic static void queryIndex(DynamoDbClient ddb, String tableName) {\ntry {\nMap expressionAttributesNames = new HashMap<>();\nexpressionAttributesNames.put(\"#year\", \"year\");\nMap expressionAttributeValues = new HashMap<>();\nexpressionAttributeValues.put(\":yearValue\",\nAttributeValue.builder().n(\"2013\").build());\nActions 950\nAWS SDK for Java 2.x Developer Guide for version 2.x\nQueryRequest request = QueryRequest.builder()\n.tableName(tableName)\n.indexName(\"year-index\")\n.keyConditionExpression(\"#year = :yearValue\")\n.expressionAttributeNames(expressionAttributesNames)\n.expressionAttributeValues(expressionAttributeValues)\n.build();\nSystem.out.println(\"=== Movie Titles ===\");\nQueryResponse response = ddb.query(request);\nresponse.items()\n.forEach(movie -> System.out.println(movie.get(\"title\").s()));\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see Query in AWS SDK for Java 2.x API Reference.\nScan\nThe following code example shows how to use Scan.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nScans an Amazon DynamoDB table using DynamoDbClient.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nActions 951\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.ScanRequest;\nimport software.amazon.awssdk.services.dynamodb.model.ScanResponse;\nimport java.util.Map;\nimport java.util.Set;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To scan items from an Amazon DynamoDB table using the AWS SDK for Java V2,\n* its better practice to use the\n* Enhanced Client, See the EnhancedScanRecords example.\n*/\npublic class DynamoDBScanItems {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ntableName - The Amazon DynamoDB table to get information from\n(for example, Music3).\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nscanItems(ddb, tableName);\nddb.close();\nActions 952\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\npublic static void scanItems(DynamoDbClient ddb, String tableName) {\ntry {\nScanRequest scanRequest = ScanRequest.builder()\n.tableName(tableName)\n.build();\nScanResponse response = ddb.scan(scanRequest);\nfor (Map item : response.items()) {\nSet keys = item.keySet();\nfor (String key : keys) {\nSystem.out.println(\"The key name is \" + key + \"\\n\");\nSystem.out.println(\"The value is \" + item.get(key).s());\n}\n}\n} catch (DynamoDbException e) {\ne.printStackTrace();\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see Scan in AWS SDK for Java 2.x API Reference.\nUpdateItem\nThe following code example shows how to use UpdateItem.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUpdates an item in a table using DynamoDbClient.", "mimetype": "text/plain", "start_char_idx": 1399127, "end_char_idx": 1403407, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b698a3ed-d031-4c92-8db0-243384051955": {"__data__": {"id_": "b698a3ed-d031-4c92-8db0-243384051955", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ebd0f2b8-4630-4110-9082-1b3331f9023d", "node_type": "1", "metadata": {}, "hash": "0ea9a4cd7dc6e9d1852c112f626dea6e7f88954c1105ee0969ee29830183c924", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f87b0663-2ced-4b2b-9497-5e40751cf78b", "node_type": "1", "metadata": {}, "hash": "64be19bbcf163eeaea9148f8460ccc396d604a485621ace00f0a6b0219f8b8a7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "UpdateItem\nThe following code example shows how to use UpdateItem.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nUpdates an item in a table using DynamoDbClient.\nimport software.amazon.awssdk.regions.Region;\nActions 953\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeAction;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport java.util.HashMap;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better\n* practice to use the\n* Enhanced Client, See the EnhancedModifyItem example.\n*/\npublic class UpdateItem {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table (for example, Music3).\nkey - The name of the key in the table (for example, Artist).\nkeyVal - The value of the key (for example, Famous Band).\nname - The name of the column where the value is updated (for\nexample, Awards).\nupdateVal - The value used to update an item (for example, 14).\nExample:\nUpdateItem Music3 Artist Famous Band Awards 14\n\"\"\";\nif (args.length != 5) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nActions 954\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString key = args[1];\nString keyVal = args[2];\nString name = args[3];\nString updateVal = args[4];\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nupdateTableItem(ddb, tableName, key, keyVal, name, updateVal);\nddb.close();\n}\npublic static void updateTableItem(DynamoDbClient ddb,\nString tableName,\nString key,\nString keyVal,\nString name,\nString updateVal) {\nHashMap itemKey = new HashMap<>();\nitemKey.put(key, AttributeValue.builder()\n.s(keyVal)\n.build());\nHashMap updatedValues = new HashMap<>();\nupdatedValues.put(name, AttributeValueUpdate.builder()\n.value(AttributeValue.builder().s(updateVal).build())\n.action(AttributeAction.PUT)\n.build());\nUpdateItemRequest request = UpdateItemRequest.builder()\n.tableName(tableName)\n.key(itemKey)\n.attributeUpdates(updatedValues)\n.build();\ntry {\nddb.updateItem(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"The Amazon DynamoDB table was updated!\");\nActions 955\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n\u2022 For API details, see UpdateItem in AWS SDK for Java 2.x API Reference.\nUpdateTimeToLive\nThe following code example shows how to use UpdateTimeToLive.\nSDK for Java 2.x\nEnable TTL on an existing DynamoDB table.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse;\nimport java.util.Optional;\nfinal TimeToLiveSpecification ttlSpecification =\nTimeToLiveSpecification.builder()\n.attributeName(ttlAttributeName)\n.enabled(true)\n.build();\nfinal UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder()\n.tableName(tableName)\n.timeToLiveSpecification(ttlSpecification)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal UpdateTimeToLiveResponse response =\nddb.updateTimeToLive(request);\nSystem.out.println(tableName + \" had its TTL successfully updated.", "mimetype": "text/plain", "start_char_idx": 1403151, "end_char_idx": 1407487, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f87b0663-2ced-4b2b-9497-5e40751cf78b": {"__data__": {"id_": "f87b0663-2ced-4b2b-9497-5e40751cf78b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b698a3ed-d031-4c92-8db0-243384051955", "node_type": "1", "metadata": {}, "hash": "5200b6fc04a339776537ed2119b5025e7fa26b4e330882219438030411e56f3d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fd629807-2c7b-41be-8e1e-eab26c80efca", "node_type": "1", "metadata": {}, "hash": "709fd10c2d7e2ac126fde0dbf4712cc64ff61dfd1f1532785659aeae198d2c38", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The request id is \"\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nActions 956\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done!\");\nDisable TTL on an existing DynamoDB table.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse;\nimport java.util.Optional;\nfinal Region region = Optional.ofNullable(args[2]).isEmpty() ?\nRegion.US_EAST_1 : Region.of(args[2]);\nfinal TimeToLiveSpecification ttlSpecification =\nTimeToLiveSpecification.builder()\n.attributeName(ttlAttributeName)\n.enabled(false)\n.build();\nfinal UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder()\n.tableName(tableName)\n.timeToLiveSpecification(ttlSpecification)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal UpdateTimeToLiveResponse response = ddb.updateTimeToLive(request);\nSystem.out.println(tableName + \" had its TTL successfully updated. The\nrequest id is \"\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nActions 957\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Done!\");\n\u2022 For API details, see UpdateTimeToLive in AWS SDK for Java 2.x API Reference.\nScenarios\nBuild an app to submit data to a DynamoDB table\nThe following code example shows how to build an application that submits data to an Amazon\nDynamoDB table and notifies you when a user updates the table.\nSDK for Java 2.x\nShows how to create a dynamic web application that submits data using the Amazon\nDynamoDB Java API and sends a text message using the Amazon Simple Notification Service\nJava API.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 DynamoDB\n\u2022 Amazon SNS\nConditionally update an item's TTL\nThe following code example shows how to conditionally update an item's TTL.\nSDK for Java 2.x\npackage com.amazon.samplelib.ttl;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nScenarios 958\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;\nimport software.amazon.awssdk.utils.ImmutableMap;\nimport java.util.Map;\nimport java.util.Optional;\npublic class UpdateTTLConditional {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table being queried.\nprimaryKey - The name of the primary key. Also known as the hash\nor partition key.\nsortKey - The name of the sort key. Also known as the range\nattribute.\nnewTtlAttribute - New attribute name (as part of the update\ncommand)\nregion (optional) - The AWS region that the Amazon DynamoDB\ntable is located in. (Default: us-east-1)\n\"\"\";\n// Optional \"region\" parameter - if args list length is NOT 3 or 4, short-\ncircuit exit.\nif (!(args.length == 4 || args.length == 5)) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nfinal String tableName = args[0];\nfinal String primaryKey = args[1];\nfinal String sortKey = args[2];\nfinal String newTtlAttribute = args[3];\nRegion region = Optional.ofNullable(args[4]).isEmpty() ?", "mimetype": "text/plain", "start_char_idx": 1407488, "end_char_idx": 1411844, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fd629807-2c7b-41be-8e1e-eab26c80efca": {"__data__": {"id_": "fd629807-2c7b-41be-8e1e-eab26c80efca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f87b0663-2ced-4b2b-9497-5e40751cf78b", "node_type": "1", "metadata": {}, "hash": "64be19bbcf163eeaea9148f8460ccc396d604a485621ace00f0a6b0219f8b8a7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a70b49c8-5886-412a-9909-2a57af361fc6", "node_type": "1", "metadata": {}, "hash": "224d266b74f0f211ab68d34c9d97488ff4a976674dc6d519c6641bb4657af42a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "primaryKey - The name of the primary key. Also known as the hash\nor partition key.\nsortKey - The name of the sort key. Also known as the range\nattribute.\nnewTtlAttribute - New attribute name (as part of the update\ncommand)\nregion (optional) - The AWS region that the Amazon DynamoDB\ntable is located in. (Default: us-east-1)\n\"\"\";\n// Optional \"region\" parameter - if args list length is NOT 3 or 4, short-\ncircuit exit.\nif (!(args.length == 4 || args.length == 5)) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nfinal String tableName = args[0];\nfinal String primaryKey = args[1];\nfinal String sortKey = args[2];\nfinal String newTtlAttribute = args[3];\nRegion region = Optional.ofNullable(args[4]).isEmpty() ? Region.US_EAST_1 :\nRegion.of(args[4]);\n// Get current time in epoch second format\nfinal long currentTime = System.currentTimeMillis() / 1000;\n// Calculate expiration time 90 days from now in epoch second format\nfinal long expireDate = currentTime + (90 * 24 * 60 * 60);\n// An expression that defines one or more attributes to be updated, the\naction to be performed on them, and new values for them.\nScenarios 959\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfinal String updateExpression = \"SET newTtlAttribute = :val1\";\n// A condition that must be satisfied in order for a conditional update to\nsucceed.\nfinal String conditionExpression = \"expireAt > :val2\";\nfinal ImmutableMap keyMap =\nImmutableMap.of(\"primaryKey\", AttributeValue.fromS(primaryKey),\n\"sortKey\", AttributeValue.fromS(sortKey));\nfinal Map expressionAttributeValues =\nImmutableMap.of(\n\":val1\", AttributeValue.builder().s(newTtlAttribute).build(),\n\":val2\",\nAttributeValue.builder().s(String.valueOf(expireDate)).build()\n);\nfinal UpdateItemRequest request = UpdateItemRequest.builder()\n.tableName(tableName)\n.key(keyMap)\n.updateExpression(updateExpression)\n.conditionExpression(conditionExpression)\n.expressionAttributeValues(expressionAttributeValues)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal UpdateItemResponse response = ddb.updateItem(request);\nSystem.out.println(tableName + \" UpdateItem operation with conditional\nTTL successful. Request id is \"\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n}\n}\n\u2022 For API details, see UpdateItem in AWS SDK for Java 2.x API Reference.\nScenarios 960\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a serverless application to manage photos\nThe following code example shows how to create a serverless application that lets users manage\nphotos using labels.\nSDK for Java 2.x\nShows how to develop a photo asset management application that detects labels in images\nusing Amazon Rekognition and stores them for later retrieval.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nFor a deep dive into the origin of this example see the post on AWS Community.\nServices used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\n\u2022 Amazon Rekognition\n\u2022 Amazon S3\n\u2022 Amazon SNS\nCreate a table with warm throughput enabled\nThe following code example shows how to create a table with warm throughput enabled.\nSDK for Java 2.x\nCreate DynamoDB table with warm throughput setting.\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;\nimport software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;\nimport software.amazon.awssdk.services.dynamodb.model.KeyType;\nimport software.amazon.awssdk.services.dynamodb.model.Projection;\nimport software.amazon.awssdk.services.dynamodb.model.ProjectionType;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;", "mimetype": "text/plain", "start_char_idx": 1411136, "end_char_idx": 1415337, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a70b49c8-5886-412a-9909-2a57af361fc6": {"__data__": {"id_": "a70b49c8-5886-412a-9909-2a57af361fc6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fd629807-2c7b-41be-8e1e-eab26c80efca", "node_type": "1", "metadata": {}, "hash": "709fd10c2d7e2ac126fde0dbf4712cc64ff61dfd1f1532785659aeae198d2c38", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "90773e7d-756f-446b-ac97-341f91c6cd8d", "node_type": "1", "metadata": {}, "hash": "0ae312fb9a54b6516664e94ef77cbc1db6dc797247f0337e48a0f578bb3eebb6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;\nimport software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;\nimport software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;\nimport software.amazon.awssdk.services.dynamodb.model.KeyType;\nimport software.amazon.awssdk.services.dynamodb.model.Projection;\nimport software.amazon.awssdk.services.dynamodb.model.ProjectionType;\nimport software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;\nScenarios 961\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;\nimport software.amazon.awssdk.services.dynamodb.model.WarmThroughput;\npublic static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond,\nfinal Long writeUnitsPerSecond)\n{\nreturn WarmThroughput.builder()\n.readUnitsPerSecond(readUnitsPerSecond)\n.writeUnitsPerSecond(writeUnitsPerSecond)\n.build();\n}\npublic static ProvisionedThroughput buildProvisionedThroughput(final Long\nreadCapacityUnits,\nfinal Long\nwriteCapacityUnits) {\nreturn ProvisionedThroughput.builder()\n.readCapacityUnits(readCapacityUnits)\n.writeCapacityUnits(writeCapacityUnits)\n.build();\n}\nprivate static AttributeDefinition buildAttributeDefinition(final String\nattributeName,\nfinal\nScalarAttributeType scalarAttributeType) {\nreturn AttributeDefinition.builder()\n.attributeName(attributeName)\n.attributeType(scalarAttributeType)\n.build();\n}\nprivate static KeySchemaElement buildKeySchemaElement(final String\nattributeName,\nfinal KeyType keyType) {\nreturn KeySchemaElement.builder()\n.attributeName(attributeName)\n.keyType(keyType)\n.build();\n}\npublic static void createDynamoDBTable(DynamoDbClient ddb,\nString tableName,\nString partitionKey,\nString sortKey,\nString miscellaneousKeyAttribute,\nString nonKeyAttribute,\nLong tableReadCapacityUnits,\nScenarios 962\nAWS SDK for Java 2.x Developer Guide for version 2.x\nLong tableWriteCapacityUnits,\nLong tableWarmReadUnitsPerSecond,\nLong tableWarmWriteUnitsPerSecond,\nString globalSecondaryIndexName,\nLong\nglobalSecondaryIndexReadCapacityUnits,\nLong\nglobalSecondaryIndexWriteCapacityUnits,\nLong\nglobalSecondaryIndexWarmReadUnitsPerSecond,\nLong\nglobalSecondaryIndexWarmWriteUnitsPerSecond) {\n// Define the table attributes\nfinal AttributeDefinition partitionKeyAttribute =\nbuildAttributeDefinition(partitionKey, ScalarAttributeType.S);\nfinal AttributeDefinition sortKeyAttribute =\nbuildAttributeDefinition(sortKey, ScalarAttributeType.S);\nfinal AttributeDefinition miscellaneousKeyAttributeDefinition =\nbuildAttributeDefinition(miscellaneousKeyAttribute, ScalarAttributeType.N);\nfinal AttributeDefinition[] attributeDefinitions = {partitionKeyAttribute,\nsortKeyAttribute, miscellaneousKeyAttributeDefinition};\n// Define the table key schema\nfinal KeySchemaElement partitionKeyElement =\nbuildKeySchemaElement(partitionKey, KeyType.HASH);\nfinal KeySchemaElement sortKeyElement = buildKeySchemaElement(sortKey,\nKeyType.RANGE);\nfinal KeySchemaElement[] keySchema = {partitionKeyElement, sortKeyElement};\n// Define the provisioned throughput for the table\nfinal ProvisionedThroughput provisionedThroughput =\nbuildProvisionedThroughput(tableReadCapacityUnits, tableWriteCapacityUnits);\n// Define the Global Secondary Index (GSI)\nfinal KeySchemaElement globalSecondaryIndexPartitionKeyElement =\nbuildKeySchemaElement(sortKey, KeyType.HASH);\nfinal KeySchemaElement globalSecondaryIndexSortKeyElement =\nbuildKeySchemaElement(miscellaneousKeyAttribute, KeyType.RANGE);\nfinal KeySchemaElement[] gsiKeySchema =\n{globalSecondaryIndexPartitionKeyElement, globalSecondaryIndexSortKeyElement};\nfinal Projection gsiProjection = Projection.builder()\n.projectionType(String.valueOf(ProjectionType.INCLUDE))\nScenarios 963\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.nonKeyAttributes(nonKeyAttribute)\n.build();\nfinal ProvisionedThroughput gsiProvisionedThroughput =\nbuildProvisionedThroughput(globalSecondaryIndexReadCapacityUnits,\nglobalSecondaryIndexWriteCapacityUnits);", "mimetype": "text/plain", "start_char_idx": 1414649, "end_char_idx": 1418857, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "90773e7d-756f-446b-ac97-341f91c6cd8d": {"__data__": {"id_": "90773e7d-756f-446b-ac97-341f91c6cd8d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a70b49c8-5886-412a-9909-2a57af361fc6", "node_type": "1", "metadata": {}, "hash": "224d266b74f0f211ab68d34c9d97488ff4a976674dc6d519c6641bb4657af42a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e1f72fc8-4e9d-495b-95ef-5a1c625fb309", "node_type": "1", "metadata": {}, "hash": "f48f712b7cb4be7a9d5287126f605cb9140d62de96b7e697b9416f71c698eb92", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "tableWriteCapacityUnits);\n// Define the Global Secondary Index (GSI)\nfinal KeySchemaElement globalSecondaryIndexPartitionKeyElement =\nbuildKeySchemaElement(sortKey, KeyType.HASH);\nfinal KeySchemaElement globalSecondaryIndexSortKeyElement =\nbuildKeySchemaElement(miscellaneousKeyAttribute, KeyType.RANGE);\nfinal KeySchemaElement[] gsiKeySchema =\n{globalSecondaryIndexPartitionKeyElement, globalSecondaryIndexSortKeyElement};\nfinal Projection gsiProjection = Projection.builder()\n.projectionType(String.valueOf(ProjectionType.INCLUDE))\nScenarios 963\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.nonKeyAttributes(nonKeyAttribute)\n.build();\nfinal ProvisionedThroughput gsiProvisionedThroughput =\nbuildProvisionedThroughput(globalSecondaryIndexReadCapacityUnits,\nglobalSecondaryIndexWriteCapacityUnits);\n// Define the warm throughput for the Global Secondary Index (GSI)\nfinal WarmThroughput gsiWarmThroughput =\nbuildWarmThroughput(globalSecondaryIndexWarmReadUnitsPerSecond,\nglobalSecondaryIndexWarmWriteUnitsPerSecond);\nfinal GlobalSecondaryIndex globalSecondaryIndex =\nGlobalSecondaryIndex.builder()\n.indexName(globalSecondaryIndexName)\n.keySchema(gsiKeySchema)\n.projection(gsiProjection)\n.provisionedThroughput(gsiProvisionedThroughput)\n.warmThroughput(gsiWarmThroughput)\n.build();\n// Define the warm throughput for the table\nfinal WarmThroughput tableWarmThroughput =\nbuildWarmThroughput(tableWarmReadUnitsPerSecond, tableWarmWriteUnitsPerSecond);\nfinal CreateTableRequest request = CreateTableRequest.builder()\n.tableName(tableName)\n.attributeDefinitions(attributeDefinitions)\n.keySchema(keySchema)\n.provisionedThroughput(provisionedThroughput)\n.globalSecondaryIndexes(globalSecondaryIndex)\n.warmThroughput(tableWarmThroughput)\n.build();\nCreateTableResponse response = ddb.createTable(request);\nSystem.out.println(response);\n}\n\u2022 For API details, see CreateTable in AWS SDK for Java 2.x API Reference.\nCreate a web application to track DynamoDB data\nThe following code example shows how to create a web application that tracks work items in an\nAmazon DynamoDB table and uses Amazon Simple Email Service (Amazon SES) to send reports.\nScenarios 964\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nShows how to use the Amazon DynamoDB API to create a dynamic web application that tracks\nDynamoDB work data.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 DynamoDB\n\u2022 Amazon SES\nCreate an item with a TTL\nThe following code example shows how to create an item with TTL.\nSDK for Java 2.x\npackage com.amazon.samplelib.ttl;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.PutItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.PutItemResponse;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.utils.ImmutableMap;\nimport java.io.Serializable;\nimport java.util.Map;\nimport java.util.Optional;\npublic class CreateTTL {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\ntableName - The Amazon DynamoDB table being queried.\nScenarios 965\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprimaryKey - The name of the primary key. Also known as the hash\nor partition key.\nsortKey - The name of the sort key. Also known as the range\nattribute.\nregion (optional) - The AWS region that the Amazon DynamoDB\ntable is located in. (Default: us-east-1)\n\"\"\";\n// Optional \"region\" parameter - if args list length is NOT 3 or 4, short-\ncircuit exit.\nif (!(args.length == 3 || args.length == 4)) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString tableName = args[0];\nString primaryKey = args[1];\nString sortKey = args[2];\nRegion region = Optional.ofNullable(args[3]).isEmpty() ? Region.US_EAST_1 :\nRegion.of(args[3]);\n// Get current time in epoch second format\nfinal long createDate = System.currentTimeMillis() / 1000;\n// Calculate expiration time 90 days from now in epoch second format\nfinal long expireDate = createDate + (90 * 24 * 60 * 60);\nfinal ImmutableMap itemMap =\nImmutableMap.of(\"primaryKey\", primaryKey,\n\"sortKey\", sortKey,\n\"creationDate\", createDate,\n\"expireAt\", expireDate);\nfinal PutItemRequest request = PutItemRequest.builder()\n.tableName(tableName)\n.item((Map) itemMap)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal PutItemResponse response = ddb.putItem(request);\nSystem.out.println(tableName + \" PutItem operation with TTL successful.\nRequest id is \"\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nScenarios 966\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n}\n}\n\u2022 For API details, see PutItem in AWS SDK for Java 2.x API Reference.\nDetect PPE in images\nThe following code example shows how to build an app that uses Amazon Rekognition to detect\nPersonal Protective Equipment (PPE) in images.\nSDK for Java 2.x\nShows how to create an AWS Lambda function that detects images with Personal Protective\nEquipment.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 DynamoDB\n\u2022 Amazon Rekognition\n\u2022 Amazon S3\n\u2022 Amazon SES\nMonitor DynamoDB performance\nThe following code example shows how to configure an application's use of DynamoDB to monitor\nperformance.\nScenarios 967\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nThis example shows how to configure a Java application to monitor the performance of\nDynamoDB. The application sends metric data to CloudWatch where you can monitor the\nperformance.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 CloudWatch\n\u2022 DynamoDB\nQuery a table by using batches of PartiQL statements\nThe following code example shows how to:\n\u2022 Get a batch of items by running multiple SELECT statements.\n\u2022 Add a batch of items by running multiple INSERT statements.\n\u2022 Update a batch of items by running multiple UPDATE statements.\n\u2022 Delete a batch of items by running multiple DELETE statements.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic class ScenarioPartiQLBatch {\npublic static void main(String[] args) throws IOException {\nString tableName = \"MoviesPartiQBatch\";\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Creating an Amazon DynamoDB table named \" + tableName\nScenarios 968\nAWS SDK for Java 2.x Developer Guide for version 2.x\n+ \" with a key named year and a sort key named title.\");\ncreateTable(ddb, tableName);\nSystem.out.println(\"Adding multiple records into the \" + tableName\n+ \" table using a batch command.\");\nputRecordBatch(ddb);\n// Update multiple movies by using the BatchExecute statement.\nString title1 = \"Star Wars\";\nint year1 = 1977;\nString title2 = \"Wizard of Oz\";\nint year2 = 1939;\nSystem.out.println(\"Query two movies.\");\ngetBatch(ddb, tableName, title1, title2, year1, year2);\nSystem.out.println(\"Updating multiple records using a batch command.\");\nupdateTableItemBatch(ddb);\nSystem.out.println(\"Deleting multiple records using a batch command.\");\ndeleteItemBatch(ddb);\nSystem.out.println(\"Deleting the Amazon DynamoDB table.", "mimetype": "text/plain", "start_char_idx": 1421672, "end_char_idx": 1425974, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3d9cb92e-d1d3-4d61-9ec8-a1edbbbb7ce0": {"__data__": {"id_": "3d9cb92e-d1d3-4d61-9ec8-a1edbbbb7ce0", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e1f72fc8-4e9d-495b-95ef-5a1c625fb309", "node_type": "1", "metadata": {}, "hash": "f48f712b7cb4be7a9d5287126f605cb9140d62de96b7e697b9416f71c698eb92", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "21896c1a-b697-493f-9ec6-068e55f82e3c", "node_type": "1", "metadata": {}, "hash": "4fb3c817eba1105894a35df03ae032dd00497e18193cb9a699336009d1a87560", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\ncreateTable(ddb, tableName);\nSystem.out.println(\"Adding multiple records into the \" + tableName\n+ \" table using a batch command.\");\nputRecordBatch(ddb);\n// Update multiple movies by using the BatchExecute statement.\nString title1 = \"Star Wars\";\nint year1 = 1977;\nString title2 = \"Wizard of Oz\";\nint year2 = 1939;\nSystem.out.println(\"Query two movies.\");\ngetBatch(ddb, tableName, title1, title2, year1, year2);\nSystem.out.println(\"Updating multiple records using a batch command.\");\nupdateTableItemBatch(ddb);\nSystem.out.println(\"Deleting multiple records using a batch command.\");\ndeleteItemBatch(ddb);\nSystem.out.println(\"Deleting the Amazon DynamoDB table.\");\ndeleteDynamoDBTable(ddb, tableName);\nddb.close();\n}\npublic static boolean getBatch(DynamoDbClient ddb, String tableName, String\ntitle1, String title2, int year1, int year2) {\nString getBatch = \"SELECT * FROM \" + tableName + \" WHERE title = ? AND year\n= ?\";\nList statements = new ArrayList<>();\nstatements.add(BatchStatementRequest.builder()\n.statement(getBatch)\n.parameters(AttributeValue.builder().s(title1).build(),\nAttributeValue.builder().n(String.valueOf(year1)).build())\n.build());\nstatements.add(BatchStatementRequest.builder()\n.statement(getBatch)\n.parameters(AttributeValue.builder().s(title2).build(),\nAttributeValue.builder().n(String.valueOf(year2)).build())\n.build());\nScenarios 969\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBatchExecuteStatementRequest batchExecuteStatementRequest =\nBatchExecuteStatementRequest.builder()\n.statements(statements)\n.build();\ntry {\nBatchExecuteStatementResponse response =\nddb.batchExecuteStatement(batchExecuteStatementRequest);\nif (!response.responses().isEmpty()) {\nresponse.responses().forEach(r -> {\nSystem.out.println(r.item().get(\"title\") + \"\\\\t\" +\nr.item().get(\"year\"));\n});\nreturn true;\n} else {\nSystem.out.println(\"Couldn't find either \" + title1 + \" or \" +\ntitle2 + \".\");\nreturn false;\n}\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nreturn false;\n}\n}\npublic static void createTable(DynamoDbClient ddb, String tableName) {\nDynamoDbWaiter dbWaiter = ddb.waiter();\nArrayList attributeDefinitions = new ArrayList<>();\n// Define attributes.\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"year\")\n.attributeType(\"N\")\n.build());\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"title\")\n.attributeType(\"S\")\n.build());\nArrayList tableKey = new ArrayList<>();\nKeySchemaElement key = KeySchemaElement.builder()\n.attributeName(\"year\")\n.keyType(KeyType.HASH)\nScenarios 970\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nKeySchemaElement key2 = KeySchemaElement.builder()\n.attributeName(\"title\")\n.keyType(KeyType.RANGE) // Sort\n.build();\n// Add KeySchemaElement objects to the list.\ntableKey.add(key);\ntableKey.add(key2);\nCreateTableRequest request = CreateTableRequest.builder()\n.keySchema(tableKey)\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(10L)\n.writeCapacityUnits(10L)\n.build())\n.attributeDefinitions(attributeDefinitions)\n.tableName(tableName)\n.build();\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.\nWaiterResponse waiterResponse = dbWaiter\n.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nString newTable = response.tableDescription().tableName();\nSystem.out.println(\"The \" + newTable + \" was successfully created.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void putRecordBatch(DynamoDbClient ddb) {\nString sqlStatement = \"INSERT INTO MoviesPartiQBatch VALUE {'year':?,\n'title' : ?, 'info' : ?}\";\ntry {\nScenarios 971\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create three movies to add to the Amazon DynamoDB table.\n// Set data for Movie 1.\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(\"1977\")\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"Star Wars\")\n.build();\nAttributeValue att3 = AttributeValue.builder()\n.s(\"No Information\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\nparameters.add(att3);\nBatchStatementRequest statementRequestMovie1 =\nBatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parameters)\n.build();\n// Set data for Movie 2.", "mimetype": "text/plain", "start_char_idx": 1425312, "end_char_idx": 1429879, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "21896c1a-b697-493f-9ec6-068e55f82e3c": {"__data__": {"id_": "21896c1a-b697-493f-9ec6-068e55f82e3c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3d9cb92e-d1d3-4d61-9ec8-a1edbbbb7ce0", "node_type": "1", "metadata": {}, "hash": "eb34768185bd0d6cd20fd4ecb2400575b9fdfba18c6465177b84964c15606ddc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "775db991-96e5-4c81-b422-7edc6d37df8a", "node_type": "1", "metadata": {}, "hash": "681a644e12416963e302fbfc02b6c501bf701bd6c6c2301a74482b6253eea778", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "}\";\ntry {\nScenarios 971\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create three movies to add to the Amazon DynamoDB table.\n// Set data for Movie 1.\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(\"1977\")\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"Star Wars\")\n.build();\nAttributeValue att3 = AttributeValue.builder()\n.s(\"No Information\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\nparameters.add(att3);\nBatchStatementRequest statementRequestMovie1 =\nBatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parameters)\n.build();\n// Set data for Movie 2.\nList parametersMovie2 = new ArrayList<>();\nAttributeValue attMovie2 = AttributeValue.builder()\n.n(\"1939\")\n.build();\nAttributeValue attMovie2A = AttributeValue.builder()\n.s(\"Wizard of Oz\")\n.build();\nAttributeValue attMovie2B = AttributeValue.builder()\n.s(\"No Information\")\n.build();\nparametersMovie2.add(attMovie2);\nparametersMovie2.add(attMovie2A);\nparametersMovie2.add(attMovie2B);\nScenarios 972\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBatchStatementRequest statementRequestMovie2 =\nBatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersMovie2)\n.build();\n// Set data for Movie 3.\nList parametersMovie3 = new ArrayList<>();\nAttributeValue attMovie3 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attMovie3A = AttributeValue.builder()\n.s(\"My Movie 3\")\n.build();\nAttributeValue attMovie3B = AttributeValue.builder()\n.s(\"No Information\")\n.build();\nparametersMovie3.add(attMovie3);\nparametersMovie3.add(attMovie3A);\nparametersMovie3.add(attMovie3B);\nBatchStatementRequest statementRequestMovie3 =\nBatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersMovie3)\n.build();\n// Add all three movies to the list.\nList myBatchStatementList = new ArrayList<>();\nmyBatchStatementList.add(statementRequestMovie1);\nmyBatchStatementList.add(statementRequestMovie2);\nmyBatchStatementList.add(statementRequestMovie3);\nBatchExecuteStatementRequest batchRequest =\nBatchExecuteStatementRequest.builder()\n.statements(myBatchStatementList)\n.build();\nBatchExecuteStatementResponse response =\nddb.batchExecuteStatement(batchRequest);\nScenarios 973\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"ExecuteStatement successful: \" +\nresponse.toString());\nSystem.out.println(\"Added new movies using a batch command.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void updateTableItemBatch(DynamoDbClient ddb) {\nString sqlStatement = \"UPDATE MoviesPartiQBatch SET info = 'directors\\\":\n[\\\"Merian C. Cooper\\\",\\\"Ernest B. Schoedsack' where year=? and title=?\";\nList parametersRec1 = new ArrayList<>();\n// Update three records.\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"My Movie 1\")\n.build();\nparametersRec1.add(att1);\nparametersRec1.add(att2);\nBatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec1)\n.build();\n// Update record 2.\nList parametersRec2 = new ArrayList<>();\nAttributeValue attRec2 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attRec2a = AttributeValue.builder()\n.s(\"My Movie 2\")\n.build();\nparametersRec2.add(attRec2);\nparametersRec2.add(attRec2a);\nScenarios 974\nAWS SDK for Java 2.x Developer Guide for version 2.x\nBatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec2)\n.build();\n// Update record 3.\nList parametersRec3 = new ArrayList<>();\nAttributeValue attRec3 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attRec3a = AttributeValue.builder()\n.s(\"My Movie 3\")\n.build();\nparametersRec3.add(attRec3);\nparametersRec3.add(attRec3a);\nBatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec3)\n.build();\n// Add all three movies to the list.", "mimetype": "text/plain", "start_char_idx": 1429217, "end_char_idx": 1433456, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "775db991-96e5-4c81-b422-7edc6d37df8a": {"__data__": {"id_": "775db991-96e5-4c81-b422-7edc6d37df8a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "21896c1a-b697-493f-9ec6-068e55f82e3c", "node_type": "1", "metadata": {}, "hash": "4fb3c817eba1105894a35df03ae032dd00497e18193cb9a699336009d1a87560", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d0514a34-cb7f-49ef-9805-d37f12e0710e", "node_type": "1", "metadata": {}, "hash": "dd22eaf0701d6ed2594100987ca1891a926c8fdb7511cdea65568500b252aee6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "List parametersRec3 = new ArrayList<>();\nAttributeValue attRec3 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attRec3a = AttributeValue.builder()\n.s(\"My Movie 3\")\n.build();\nparametersRec3.add(attRec3);\nparametersRec3.add(attRec3a);\nBatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec3)\n.build();\n// Add all three movies to the list.\nList myBatchStatementList = new ArrayList<>();\nmyBatchStatementList.add(statementRequestRec1);\nmyBatchStatementList.add(statementRequestRec2);\nmyBatchStatementList.add(statementRequestRec3);\nBatchExecuteStatementRequest batchRequest =\nBatchExecuteStatementRequest.builder()\n.statements(myBatchStatementList)\n.build();\ntry {\nBatchExecuteStatementResponse response =\nddb.batchExecuteStatement(batchRequest);\nSystem.out.println(\"ExecuteStatement successful: \" +\nresponse.toString());\nSystem.out.println(\"Updated three movies using a batch command.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nScenarios 975\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Item was updated!\");\n}\npublic static void deleteItemBatch(DynamoDbClient ddb) {\nString sqlStatement = \"DELETE FROM MoviesPartiQBatch WHERE year = ? and\ntitle=?\";\nList parametersRec1 = new ArrayList<>();\n// Specify three records to delete.\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"My Movie 1\")\n.build();\nparametersRec1.add(att1);\nparametersRec1.add(att2);\nBatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec1)\n.build();\n// Specify record 2.\nList parametersRec2 = new ArrayList<>();\nAttributeValue attRec2 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attRec2a = AttributeValue.builder()\n.s(\"My Movie 2\")\n.build();\nparametersRec2.add(attRec2);\nparametersRec2.add(attRec2a);\nBatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec2)\n.build();\n// Specify record 3.\nList parametersRec3 = new ArrayList<>();\nScenarios 976\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAttributeValue attRec3 = AttributeValue.builder()\n.n(String.valueOf(\"2022\"))\n.build();\nAttributeValue attRec3a = AttributeValue.builder()\n.s(\"My Movie 3\")\n.build();\nparametersRec3.add(attRec3);\nparametersRec3.add(attRec3a);\nBatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder()\n.statement(sqlStatement)\n.parameters(parametersRec3)\n.build();\n// Add all three movies to the list.\nList myBatchStatementList = new ArrayList<>();\nmyBatchStatementList.add(statementRequestRec1);\nmyBatchStatementList.add(statementRequestRec2);\nmyBatchStatementList.add(statementRequestRec3);\nBatchExecuteStatementRequest batchRequest =\nBatchExecuteStatementRequest.builder()\n.statements(myBatchStatementList)\n.build();\ntry {\nddb.batchExecuteStatement(batchRequest);\nSystem.out.println(\"Deleted three movies using a batch command.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {\nDeleteTableRequest request = DeleteTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nddb.deleteTable(request);\nScenarios 977\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(tableName + \" was successfully deleted!\");\n}\nprivate static ExecuteStatementResponse executeStatementRequest(DynamoDbClient\nddb, String statement,\nList parameters) {\nExecuteStatementRequest request = ExecuteStatementRequest.builder()\n.statement(statement)\n.parameters(parameters)\n.build();\nreturn ddb.executeStatement(request);\n}\n}\n\u2022 For API details, see BatchExecuteStatement in AWS SDK for Java 2.x API Reference.\nQuery a table using PartiQL\nThe following code example shows how to:\n\u2022 Get an item by running a SELECT statement.\n\u2022 Add an item by running an INSERT statement.\n\u2022 Update an item by running an UPDATE statement.\n\u2022 Delete an item by running a DELETE statement.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1432999, "end_char_idx": 1437539, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d0514a34-cb7f-49ef-9805-d37f12e0710e": {"__data__": {"id_": "d0514a34-cb7f-49ef-9805-d37f12e0710e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "775db991-96e5-4c81-b422-7edc6d37df8a", "node_type": "1", "metadata": {}, "hash": "681a644e12416963e302fbfc02b6c501bf701bd6c6c2301a74482b6253eea778", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5f21811a-0f3e-433a-ae14-02f1c74caaef", "node_type": "1", "metadata": {}, "hash": "493d95f1d28e7dab7c27bde917fca62cb2963eb650de52f5012cf5bd07d119ed", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\nprivate static ExecuteStatementResponse executeStatementRequest(DynamoDbClient\nddb, String statement,\nList parameters) {\nExecuteStatementRequest request = ExecuteStatementRequest.builder()\n.statement(statement)\n.parameters(parameters)\n.build();\nreturn ddb.executeStatement(request);\n}\n}\n\u2022 For API details, see BatchExecuteStatement in AWS SDK for Java 2.x API Reference.\nQuery a table using PartiQL\nThe following code example shows how to:\n\u2022 Get an item by running a SELECT statement.\n\u2022 Add an item by running an INSERT statement.\n\u2022 Update an item by running an UPDATE statement.\n\u2022 Delete an item by running a DELETE statement.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nScenarios 978\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class ScenarioPartiQ {\npublic static void main(String[] args) throws IOException {\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\nfileName - The path to the moviedata.json file that you can\ndownload from the Amazon DynamoDB Developer Guide.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString fileName = args[0];\nString tableName = \"MoviesPartiQ\";\nRegion region = Region.US_EAST_1;\nDynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build();\nSystem.out.println(\n\"******* Creating an Amazon DynamoDB table named MoviesPartiQ with a\nkey named year and a sort key named title.\");\ncreateTable(ddb, tableName);\nSystem.out.println(\"Loading data into the MoviesPartiQ table.\");\nloadData(ddb, fileName);\nSystem.out.println(\"Getting data from the MoviesPartiQ table.\");\ngetItem(ddb);\nSystem.out.println(\"Putting a record into the MoviesPartiQ table.\");\nputRecord(ddb);\nSystem.out.println(\"Updating a record.\");\nupdateTableItem(ddb);\nSystem.out.println(\"Querying the movies released in 2013.\");\nqueryTable(ddb);\nScenarios 979\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Deleting the Amazon DynamoDB table.\");\ndeleteDynamoDBTable(ddb, tableName);\nddb.close();\n}\npublic static void createTable(DynamoDbClient ddb, String tableName) {\nDynamoDbWaiter dbWaiter = ddb.waiter();\nArrayList attributeDefinitions = new ArrayList<>();\n// Define attributes.\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"year\")\n.attributeType(\"N\")\n.build());\nattributeDefinitions.add(AttributeDefinition.builder()\n.attributeName(\"title\")\n.attributeType(\"S\")\n.build());\nArrayList tableKey = new ArrayList<>();\nKeySchemaElement key = KeySchemaElement.builder()\n.attributeName(\"year\")\n.keyType(KeyType.HASH)\n.build();\nKeySchemaElement key2 = KeySchemaElement.builder()\n.attributeName(\"title\")\n.keyType(KeyType.RANGE) // Sort\n.build();\n// Add KeySchemaElement objects to the list.\ntableKey.add(key);\ntableKey.add(key2);\nCreateTableRequest request = CreateTableRequest.builder()\n.keySchema(tableKey)\n.provisionedThroughput(ProvisionedThroughput.builder()\n.readCapacityUnits(new Long(10))\n.writeCapacityUnits(new Long(10))\n.build())\n.attributeDefinitions(attributeDefinitions)\n.tableName(tableName)\nScenarios 980\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\ntry {\nCreateTableResponse response = ddb.createTable(request);\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\n// Wait until the Amazon DynamoDB table is created.\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nString newTable = response.tableDescription().tableName();\nSystem.out.println(\"The \" + newTable + \" was successfully created.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n// Load data into the table.\npublic static void loadData(DynamoDbClient ddb, String fileName) throws\nIOException {\nString sqlStatement = \"INSERT INTO MoviesPartiQ VALUE {'year':?,\n'title' : ?, 'info' : ?}\";\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nIterator iter = rootNode.iterator();\nObjectNode currentNode;\nint t = 0;\nList parameters = new ArrayList<>();\nwhile (iter.hasNext()) {\n// Add 200 movies to the table.", "mimetype": "text/plain", "start_char_idx": 1436749, "end_char_idx": 1441139, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5f21811a-0f3e-433a-ae14-02f1c74caaef": {"__data__": {"id_": "5f21811a-0f3e-433a-ae14-02f1c74caaef", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d0514a34-cb7f-49ef-9805-d37f12e0710e", "node_type": "1", "metadata": {}, "hash": "dd22eaf0701d6ed2594100987ca1891a926c8fdb7511cdea65568500b252aee6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1c92d4af-dc90-40cf-a557-bdfb63dc4ce8", "node_type": "1", "metadata": {}, "hash": "c5f14421bdf50d15ced03c26eac78802154fbcdb40d5dfb3909a26a3df15551d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n// Load data into the table.\npublic static void loadData(DynamoDbClient ddb, String fileName) throws\nIOException {\nString sqlStatement = \"INSERT INTO MoviesPartiQ VALUE {'year':?,\n'title' : ?, 'info' : ?}\";\nJsonParser parser = new JsonFactory().createParser(new File(fileName));\ncom.fasterxml.jackson.databind.JsonNode rootNode = new\nObjectMapper().readTree(parser);\nIterator iter = rootNode.iterator();\nObjectNode currentNode;\nint t = 0;\nList parameters = new ArrayList<>();\nwhile (iter.hasNext()) {\n// Add 200 movies to the table.\nif (t == 200)\nbreak;\ncurrentNode = (ObjectNode) iter.next();\nint year = currentNode.path(\"year\").asInt();\nString title = currentNode.path(\"title\").asText();\nString info = currentNode.path(\"info\").toString();\nScenarios 981\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(year))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(title)\n.build();\nAttributeValue att3 = AttributeValue.builder()\n.s(info)\n.build();\nparameters.add(att1);\nparameters.add(att2);\nparameters.add(att3);\n// Insert the movie into the Amazon DynamoDB table.\nexecuteStatementRequest(ddb, sqlStatement, parameters);\nSystem.out.println(\"Added Movie \" + title);\nparameters.remove(att1);\nparameters.remove(att2);\nparameters.remove(att3);\nt++;\n}\n}\npublic static void getItem(DynamoDbClient ddb) {\nString sqlStatement = \"SELECT * FROM MoviesPartiQ where year=? and title=?\";\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(\"2012\")\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"The Perks of Being a Wallflower\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\ntry {\nScenarios 982\nAWS SDK for Java 2.x Developer Guide for version 2.x\nExecuteStatementResponse response = executeStatementRequest(ddb,\nsqlStatement, parameters);\nSystem.out.println(\"ExecuteStatement successful: \" +\nresponse.toString());\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void putRecord(DynamoDbClient ddb) {\nString sqlStatement = \"INSERT INTO MoviesPartiQ VALUE {'year':?,\n'title' : ?, 'info' : ?}\";\ntry {\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2020\"))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"My Movie\")\n.build();\nAttributeValue att3 = AttributeValue.builder()\n.s(\"No Information\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\nparameters.add(att3);\nexecuteStatementRequest(ddb, sqlStatement, parameters);\nSystem.out.println(\"Added new movie.\");\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void updateTableItem(DynamoDbClient ddb) {\nScenarios 983\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString sqlStatement = \"UPDATE MoviesPartiQ SET info = 'directors\\\":[\\\"Merian\nC. Cooper\\\",\\\"Ernest B. Schoedsack' where year=? and title=?\";\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2013\"))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"The East\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\ntry {\nexecuteStatementRequest(ddb, sqlStatement, parameters);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Item was updated!\");\n}\n// Query the table where the year is 2013.\npublic static void queryTable(DynamoDbClient ddb) {\nString sqlStatement = \"SELECT * FROM MoviesPartiQ where year = ? ORDER BY\nyear\";\ntry {\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2013\"))\n.build();\nparameters.add(att1);\n// Get items in the table and write out the ID value.", "mimetype": "text/plain", "start_char_idx": 1440489, "end_char_idx": 1444434, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1c92d4af-dc90-40cf-a557-bdfb63dc4ce8": {"__data__": {"id_": "1c92d4af-dc90-40cf-a557-bdfb63dc4ce8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5f21811a-0f3e-433a-ae14-02f1c74caaef", "node_type": "1", "metadata": {}, "hash": "493d95f1d28e7dab7c27bde917fca62cb2963eb650de52f5012cf5bd07d119ed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e0434081-2332-4533-ae32-662e7b74551a", "node_type": "1", "metadata": {}, "hash": "bcef1647b722501fbaf60398a627b2d4823ab659dde665a120480d7aa2a3384e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "and title=?\";\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2013\"))\n.build();\nAttributeValue att2 = AttributeValue.builder()\n.s(\"The East\")\n.build();\nparameters.add(att1);\nparameters.add(att2);\ntry {\nexecuteStatementRequest(ddb, sqlStatement, parameters);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Item was updated!\");\n}\n// Query the table where the year is 2013.\npublic static void queryTable(DynamoDbClient ddb) {\nString sqlStatement = \"SELECT * FROM MoviesPartiQ where year = ? ORDER BY\nyear\";\ntry {\nList parameters = new ArrayList<>();\nAttributeValue att1 = AttributeValue.builder()\n.n(String.valueOf(\"2013\"))\n.build();\nparameters.add(att1);\n// Get items in the table and write out the ID value.\nExecuteStatementResponse response = executeStatementRequest(ddb,\nsqlStatement, parameters);\nSystem.out.println(\"ExecuteStatement successful: \" +\nresponse.toString());\n} catch (DynamoDbException e) {\nScenarios 984\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {\nDeleteTableRequest request = DeleteTableRequest.builder()\n.tableName(tableName)\n.build();\ntry {\nddb.deleteTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.out.println(tableName + \" was successfully deleted!\");\n}\nprivate static ExecuteStatementResponse executeStatementRequest(DynamoDbClient\nddb, String statement,\nList parameters) {\nExecuteStatementRequest request = ExecuteStatementRequest.builder()\n.statement(statement)\n.parameters(parameters)\n.build();\nreturn ddb.executeStatement(request);\n}\nprivate static void processResults(ExecuteStatementResponse\nexecuteStatementResult) {\nSystem.out.println(\"ExecuteStatement successful: \" +\nexecuteStatementResult.toString());\n}\n}\n\u2022 For API details, see ExecuteStatement in AWS SDK for Java 2.x API Reference.\nScenarios 985\nAWS SDK for Java 2.x Developer Guide for version 2.x\nQuery for TTL items\nThe following code example shows how to query for TTL items.\nSDK for Java 2.x\nQuery Filtered Expression to gather TTL items in a DynamoDB table.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.QueryRequest;\nimport software.amazon.awssdk.services.dynamodb.model.QueryResponse;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.utils.ImmutableMap;\nimport java.util.Map;\nimport java.util.Optional;\n// Get current time in epoch second format (comparing against expiry\nattribute)\nfinal long currentTime = System.currentTimeMillis() / 1000;\n// A string that contains conditions that DynamoDB applies after the Query\noperation, but before the data is returned to you.\nfinal String keyConditionExpression = \"#pk = :pk\";\n// The condition that specifies the key values for items to be retrieved by\nthe Query action.\nfinal String filterExpression = \"#ea > :ea\";\nfinal Map expressionAttributeNames = ImmutableMap.of(\n\"#pk\", \"primaryKey\",\n\"#ea\", \"expireAt\");\nfinal Map expressionAttributeValues =\nImmutableMap.of(\n\":pk\", AttributeValue.builder().s(primaryKey).build(),\n\":ea\",\nAttributeValue.builder().s(String.valueOf(currentTime)).build()\n);\nfinal QueryRequest request = QueryRequest.builder()\n.tableName(tableName)\n.keyConditionExpression(keyConditionExpression)\nScenarios 986\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.filterExpression(filterExpression)\n.expressionAttributeNames(expressionAttributeNames)\n.expressionAttributeValues(expressionAttributeValues)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal QueryResponse response = ddb.query(request);\nSystem.out.println(tableName + \" Query operation with TTL successful.\nRequest id is \"\n+ response.responseMetadata().requestId());\n// Print the items that are not expired\nfor (Map item : response.items()) {\nSystem.out.println(item.toString());\n}\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n\u2022 For API details, see Query in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1443582, "end_char_idx": 1448300, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e0434081-2332-4533-ae32-662e7b74551a": {"__data__": {"id_": "e0434081-2332-4533-ae32-662e7b74551a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1c92d4af-dc90-40cf-a557-bdfb63dc4ce8", "node_type": "1", "metadata": {}, "hash": "c5f14421bdf50d15ced03c26eac78802154fbcdb40d5dfb3909a26a3df15551d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7a60d185-8cfb-45e5-a794-da7aaf1b8d1d", "node_type": "1", "metadata": {}, "hash": "cf5412f9e4c2941aaa1223551c80c9633dfd493d303d1b9c3c575ffdfbaa0e0c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Request id is \"\n+ response.responseMetadata().requestId());\n// Print the items that are not expired\nfor (Map item : response.items()) {\nSystem.out.println(item.toString());\n}\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n\u2022 For API details, see Query in AWS SDK for Java 2.x API Reference.\nUpdate a table's warm throughput setting\nThe following code example shows how to update a table's warm throughput setting.\nSDK for Java 2.x\nUpdate warm throughput setting on an existing DynamoDB table.\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexUpdate;\nimport\nsoftware.amazon.awssdk.services.dynamodb.model.UpdateGlobalSecondaryIndexAction;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest;\nimport software.amazon.awssdk.services.dynamodb.model.WarmThroughput;\nScenarios 987\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond,\nfinal Long writeUnitsPerSecond)\n{\nreturn WarmThroughput.builder()\n.readUnitsPerSecond(readUnitsPerSecond)\n.writeUnitsPerSecond(writeUnitsPerSecond)\n.build();\n}\npublic static void updateDynamoDBTable(DynamoDbClient ddb,\nString tableName,\nLong tableReadUnitsPerSecond,\nLong tableWriteUnitsPerSecond,\nString globalSecondaryIndexName,\nLong\nglobalSecondaryIndexReadUnitsPerSecond,\nLong\nglobalSecondaryIndexWriteUnitsPerSecond) {\nfinal WarmThroughput tableWarmThroughput =\nbuildWarmThroughput(tableReadUnitsPerSecond, tableWriteUnitsPerSecond);\nfinal WarmThroughput gsiWarmThroughput =\nbuildWarmThroughput(globalSecondaryIndexReadUnitsPerSecond,\nglobalSecondaryIndexWriteUnitsPerSecond);\nfinal GlobalSecondaryIndexUpdate globalSecondaryIndexUpdate =\nGlobalSecondaryIndexUpdate.builder()\n.update(UpdateGlobalSecondaryIndexAction.builder()\n.indexName(globalSecondaryIndexName)\n.warmThroughput(gsiWarmThroughput)\n.build()\n).build();\nfinal UpdateTableRequest request = UpdateTableRequest.builder()\n.tableName(tableName)\n.globalSecondaryIndexUpdates(globalSecondaryIndexUpdate)\n.warmThroughput(tableWarmThroughput)\n.build();\ntry {\nddb.updateTable(request);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\nScenarios 988\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nSystem.out.println(\"Done!\");\n}\n\u2022 For API details, see UpdateTable in AWS SDK for Java 2.x API Reference.\nUpdate an item's TTL\nThe following code example shows how to update an item's TTL.\nSDK for Java 2.x\nUpdate TTL on an existing DynamoDB item in a table.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;\nimport software.amazon.awssdk.utils.ImmutableMap;\nimport java.util.Map;\nimport java.util.Optional;\n// Get current time in epoch second format\nfinal long currentTime = System.currentTimeMillis() / 1000;\n// Calculate expiration time 90 days from now in epoch second format\nfinal long expireDate = currentTime + (90 * 24 * 60 * 60);\n// An expression that defines one or more attributes to be updated, the\naction to be performed on them, and new values for them.", "mimetype": "text/plain", "start_char_idx": 1447785, "end_char_idx": 1451596, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7a60d185-8cfb-45e5-a794-da7aaf1b8d1d": {"__data__": {"id_": "7a60d185-8cfb-45e5-a794-da7aaf1b8d1d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e0434081-2332-4533-ae32-662e7b74551a", "node_type": "1", "metadata": {}, "hash": "bcef1647b722501fbaf60398a627b2d4823ab659dde665a120480d7aa2a3384e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7184676f-8ac9-44c9-a677-80fa23cef7e3", "node_type": "1", "metadata": {}, "hash": "007ffd504b71b668391abcaf3fa1301a66fdddfbac1db836d47019e55cfdf1e3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.dynamodb.DynamoDbClient;\nimport software.amazon.awssdk.services.dynamodb.model.AttributeValue;\nimport software.amazon.awssdk.services.dynamodb.model.DynamoDbException;\nimport software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;\nimport software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;\nimport software.amazon.awssdk.utils.ImmutableMap;\nimport java.util.Map;\nimport java.util.Optional;\n// Get current time in epoch second format\nfinal long currentTime = System.currentTimeMillis() / 1000;\n// Calculate expiration time 90 days from now in epoch second format\nfinal long expireDate = currentTime + (90 * 24 * 60 * 60);\n// An expression that defines one or more attributes to be updated, the\naction to be performed on them, and new values for them.\nfinal String updateExpression = \"SET updatedAt=:c, expireAt=:e\";\nfinal ImmutableMap keyMap =\nImmutableMap.of(\"primaryKey\", AttributeValue.fromS(primaryKey),\n\"sortKey\", AttributeValue.fromS(sortKey));\nfinal Map expressionAttributeValues =\nImmutableMap.of(\n\":c\",\nAttributeValue.builder().s(String.valueOf(currentTime)).build(),\nScenarios 989\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\":e\", AttributeValue.builder().s(String.valueOf(expireDate)).build()\n);\nfinal UpdateItemRequest request = UpdateItemRequest.builder()\n.tableName(tableName)\n.key(keyMap)\n.updateExpression(updateExpression)\n.expressionAttributeValues(expressionAttributeValues)\n.build();\ntry (DynamoDbClient ddb = DynamoDbClient.builder()\n.region(region)\n.build()) {\nfinal UpdateItemResponse response = ddb.updateItem(request);\nSystem.out.println(tableName + \" UpdateItem operation with TTL\nsuccessful. Request id is \"\n+ response.responseMetadata().requestId());\n} catch (ResourceNotFoundException e) {\nSystem.err.format(\"Error: The Amazon DynamoDB table \\\"%s\\\" can't be\nfound.\\n\", tableName);\nSystem.exit(1);\n} catch (DynamoDbException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\nSystem.exit(0);\n\u2022 For API details, see UpdateItem in AWS SDK for Java 2.x API Reference.\nUse Step Functions to invoke Lambda functions\nThe following code example shows how to create an AWS Step Functions state machine that\ninvokes AWS Lambda functions in sequence.\nSDK for Java 2.x\nShows how to create an AWS serverless workflow by using AWS Step Functions and the AWS\nSDK for Java 2.x. Each workflow step is implemented using an AWS Lambda function.\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nScenarios 990\nAWS SDK for Java 2.x Developer Guide for version 2.x\nServices used in this example\n\u2022 DynamoDB\n\u2022 Lambda\n\u2022 Amazon SES\n\u2022 Step Functions\nServerless examples\nInvoke a Lambda function from a DynamoDB trigger\nThe following code example shows how to implement a Lambda function that receives an event\ntriggered by receiving records from a DynamoDB stream. The function retrieves the DynamoDB\npayload and logs the record contents.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe Serverless examples repository.\nConsuming a DynamoDB event with Lambda using Java.\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\nimport com.amazonaws.services.lambda.runtime.events.DynamodbEvent;\nimport\ncom.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\npublic class example implements RequestHandler {\nprivate static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();\n@Override\npublic Void handleRequest(DynamodbEvent event, Context context) {\nSystem.out.println(GSON.toJson(event));\nevent.getRecords().forEach(this::logDynamoDBRecord);\nServerless examples 991\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn null;\n}\nprivate void logDynamoDBRecord(DynamodbStreamRecord record) {\nSystem.out.println(record.getEventID());\nSystem.out.println(record.getEventName());\nSystem.out.println(\"DynamoDB Record: \" + GSON.toJson(record.getDynamodb()));\n}\n}\nReporting batch item failures for Lambda functions with a DynamoDB trigger\nThe following code example shows how to implement partial batch response for Lambda functions\nthat receive events from a DynamoDB stream. The function reports the batch item failures in the\nresponse, signaling to Lambda to retry those messages later.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe Serverless examples repository.", "mimetype": "text/plain", "start_char_idx": 1450657, "end_char_idx": 1455438, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7184676f-8ac9-44c9-a677-80fa23cef7e3": {"__data__": {"id_": "7184676f-8ac9-44c9-a677-80fa23cef7e3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7a60d185-8cfb-45e5-a794-da7aaf1b8d1d", "node_type": "1", "metadata": {}, "hash": "cf5412f9e4c2941aaa1223551c80c9633dfd493d303d1b9c3c575ffdfbaa0e0c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0bd08976-3abd-4176-9a94-2f34c3a9f020", "node_type": "1", "metadata": {}, "hash": "dfbf4beb2ab8139c39be16f158abe135ce21e4dda4233f060b6aa454c46b328b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "The function reports the batch item failures in the\nresponse, signaling to Lambda to retry those messages later.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe Serverless examples repository.\nReporting DynamoDB batch item failures with Lambda using Java.\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\nimport com.amazonaws.services.lambda.runtime.events.DynamodbEvent;\nimport com.amazonaws.services.lambda.runtime.events.StreamsEventResponse;\nimport com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class ProcessDynamodbRecords implements RequestHandler {\nServerless examples 992\nAWS SDK for Java 2.x Developer Guide for version 2.x\n@Override\npublic StreamsEventResponse handleRequest(DynamodbEvent input, Context context)\n{\nList batchItemFailures = new\nArrayList<>();\nString curRecordSequenceNumber = \"\";\nfor (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord :\ninput.getRecords()) {\ntry {\n//Process your record\nStreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb();\ncurRecordSequenceNumber = dynamodbRecord.getSequenceNumber();\n} catch (Exception e) {\n/* Since we are working with streams, we can return the failed item\nimmediately.\nLambda will immediately begin to retry processing from this\nfailed item onwards. */\nbatchItemFailures.add(new\nStreamsEventResponse.BatchItemFailure(curRecordSequenceNumber));\nreturn new StreamsEventResponse(batchItemFailures);\n}\n}\nreturn new StreamsEventResponse();\n}\n}\nAWS community contributions\nBuild and test a serverless application\nThe following code example shows how to build and test a serverless application using API\nGateway with Lambda and DynamoDB\nSDK for Java 2.x\nShows how to build and test a serverless application that consists of an API Gateway with\nLambda and DynamoDB using the Java SDK.\nAWS community contributions 993\nAWS SDK for Java 2.x Developer Guide for version 2.x\nFor complete source code and instructions on how to set up and run, see the full example on\nGitHub.\nServices used in this example\n\u2022 API Gateway\n\u2022 DynamoDB\n\u2022 Lambda\nAmazon EC2 examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon EC2.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello Amazon EC2\nThe following code examples show how to get started using Amazon EC2.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\nAmazon EC2 994\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Asynchronously describes the security groups for the specified group ID.\n*\n* @param groupName the name of the security group to describe\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of describing the security groups. The future will complete with a\n* {@link DescribeSecurityGroupsResponse} object that contains the\n* security group information.\n*/\npublic CompletableFuture describeSecurityGroupArnByNameAsync(String\ngroupName) {\nDescribeSecurityGroupsRequest request =\nDescribeSecurityGroupsRequest.builder()\n.groupNames(groupName)\n.build();\nDescribeSecurityGroupsPublisher paginator =\ngetAsyncClient().describeSecurityGroupsPaginator(request);\nAtomicReference groupIdRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.securityGroups().stream()\n.filter(securityGroup ->\nsecurityGroup.groupName().equals(groupName))\n.findFirst()\n.ifPresent(securityGroup ->\ngroupIdRef.set(securityGroup.groupId()));\n}).thenApply(v -> {\nString groupId = groupIdRef.get();\nif (groupId == null) {\nthrow new RuntimeException(\"No security group found with the name: \"\n+ groupName);\n}\nreturn groupId;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe security group: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe security group\", ex);\n});\n}\n\u2022 For API details, see DescribeSecurityGroups in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1455183, "end_char_idx": 1460119, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0bd08976-3abd-4176-9a94-2f34c3a9f020": {"__data__": {"id_": "0bd08976-3abd-4176-9a94-2f34c3a9f020", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7184676f-8ac9-44c9-a677-80fa23cef7e3", "node_type": "1", "metadata": {}, "hash": "007ffd504b71b668391abcaf3fa1301a66fdddfbac1db836d47019e55cfdf1e3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c404cbe3-2dac-410b-8445-7a2d3de78178", "node_type": "1", "metadata": {}, "hash": "b470d103a0f059598a947ddf2231aa16fc93e2ccfd9023aadb6889ac16238f65", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*/\npublic CompletableFuture describeSecurityGroupArnByNameAsync(String\ngroupName) {\nDescribeSecurityGroupsRequest request =\nDescribeSecurityGroupsRequest.builder()\n.groupNames(groupName)\n.build();\nDescribeSecurityGroupsPublisher paginator =\ngetAsyncClient().describeSecurityGroupsPaginator(request);\nAtomicReference groupIdRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.securityGroups().stream()\n.filter(securityGroup ->\nsecurityGroup.groupName().equals(groupName))\n.findFirst()\n.ifPresent(securityGroup ->\ngroupIdRef.set(securityGroup.groupId()));\n}).thenApply(v -> {\nString groupId = groupIdRef.get();\nif (groupId == null) {\nthrow new RuntimeException(\"No security group found with the name: \"\n+ groupName);\n}\nreturn groupId;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe security group: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe security group\", ex);\n});\n}\n\u2022 For API details, see DescribeSecurityGroups in AWS SDK for Java 2.x API Reference.\nTopics\nAmazon EC2 995\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create a key pair and security group.\n\u2022 Select an Amazon Machine Image (AMI) and compatible instance type, then create an instance.\n\u2022 Stop and restart the instance.\n\u2022 Associate an Elastic IP address with your instance.\n\u2022 Connect to your instance with SSH, then clean up resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun a scenario at a command prompt.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;\nimport software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;\nimport software.amazon.awssdk.services.ec2.model.DisassociateAddressResponse;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nimport software.amazon.awssdk.services.ec2.model.ReleaseAddressResponse;\nimport software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse;\nimport software.amazon.awssdk.services.ssm.model.Parameter;\nimport java.net.InetAddress;\nBasics 996\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport java.net.UnknownHostException;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\n/**\n* Before running this Java (v2) code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This Java example performs the following tasks:\n*\n* 1. Creates an RSA key pair and saves the private key data as a .pem file.\n* 2. Lists key pairs.\n* 3. Creates a security group for the default VPC.\n* 4. Displays security group information.\n* 5. Gets a list of Amazon Linux 2 AMIs and selects one.\n* 6. Gets additional information about the image.\n* 7. Gets a list of instance types that are compatible with the selected AMI\u2019s\n* architecture.\n* 8. Creates an instance with the key pair, security group, AMI, and an\n* instance type.\n* 9. Displays information about the instance.\n* 10. Stops the instance and waits for it to stop.\n* 11. Starts the instance and waits for it to start.\n* 12. Allocates an Elastic IP address and associates it with the instance.\n* 13. Displays SSH connection info for the instance.\n* 14. Disassociates and deletes the Elastic IP address.\n* 15. Terminates the instance and waits for it to terminate.\n* 16. Deletes the security group.\n* 17. Deletes the key pair.", "mimetype": "text/plain", "start_char_idx": 1459087, "end_char_idx": 1462914, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c404cbe3-2dac-410b-8445-7a2d3de78178": {"__data__": {"id_": "c404cbe3-2dac-410b-8445-7a2d3de78178", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0bd08976-3abd-4176-9a94-2f34c3a9f020", "node_type": "1", "metadata": {}, "hash": "dfbf4beb2ab8139c39be16f158abe135ce21e4dda4233f060b6aa454c46b328b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b51d85ae-2c1f-43a3-b1bf-bfe1c30f4433", "node_type": "1", "metadata": {}, "hash": "7d4458a380cb2d6e8dc652b7da7fb915d19ee36554c1b303563fb17e146f8ff0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* 6. Gets additional information about the image.\n* 7. Gets a list of instance types that are compatible with the selected AMI\u2019s\n* architecture.\n* 8. Creates an instance with the key pair, security group, AMI, and an\n* instance type.\n* 9. Displays information about the instance.\n* 10. Stops the instance and waits for it to stop.\n* 11. Starts the instance and waits for it to start.\n* 12. Allocates an Elastic IP address and associates it with the instance.\n* 13. Displays SSH connection info for the instance.\n* 14. Disassociates and deletes the Elastic IP address.\n* 15. Terminates the instance and waits for it to terminate.\n* 16. Deletes the security group.\n* 17. Deletes the key pair.\n*/\npublic class EC2Scenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\nprivate static final Logger logger = LoggerFactory.getLogger(EC2Scenario.class);\npublic static void main(String[] args) throws InterruptedException,\nUnknownHostException {\nlogger.info(\"\"\"\nBasics 997\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUsage:\n \nWhere:\nkeyName - A key pair name (for example, TestKeyPair).\\s\nfileName - A file name where the key information is written to.\\s\ngroupName - The name of the security group.\\s\ngroupDesc - The description of the security group.\\s\n\"\"\");\nScanner scanner = new Scanner(System.in);\nEC2Actions ec2Actions = new EC2Actions();\nString keyName = \"TestKeyPair7\" ;\nString fileName = \"ec2Key.pem\";\nString groupName = \"TestSecGroup7\" ;\nString groupDesc = \"Test Group\" ;\nString vpcId = ec2Actions.describeFirstEC2VpcAsync().join().vpcId();\nInetAddress localAddress = InetAddress.getLocalHost();\nString myIpAddress = localAddress.getHostAddress();\nlogger.info(\"\"\"\nAmazon Elastic Compute Cloud (EC2) is a web service that provides\nsecure, resizable compute\ncapacity in the cloud. It allows developers and organizations to easily\nlaunch and manage\nvirtual server instances, known as EC2 instances, to run their\napplications.\nEC2 provides a wide range of instance types, each with different\ncompute, memory,\nand storage capabilities, to meet the diverse needs of various\nworkloads. Developers\ncan choose the appropriate instance type based on their application's\nrequirements,\nsuch as high-performance computing, memory-intensive tasks, or GPU-\naccelerated workloads.\nThe `Ec2AsyncClient` interface in the AWS SDK for Java 2.x provides a\nset of methods to\nprogrammatically interact with the Amazon EC2 service. This allows\ndevelopers to\nautomate the provisioning, management, and monitoring of EC2 instances\nas part of their\nBasics 998\nAWS SDK for Java 2.x Developer Guide for version 2.x\napplication deployment pipelines. With EC2, teams can focus on building\nand deploying\ntheir applications without having to worry about the underlying\ninfrastructure\nrequired to host and manage physical servers.\nThis scenario walks you through how to perform key operations for this\nservice.\nLet's get started...\n\"\"\");\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"1. Create an RSA key pair and save the private key material as\na .pem file.\");\nlogger.info(\"\"\"\nAn RSA key pair for Amazon EC2 is a security mechanism used to\nauthenticate and secure\naccess to your EC2 instances. It consists of a public key and a private\nkey,\nwhich are generated as a pair.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.createKeyPairAsync(keyName, fileName);\nCreateKeyPairResponse response = future.join();\nlogger.info(\"Key Pair successfully created. Key Fingerprint: \" +\nresponse.keyFingerprint());\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nif (ec2Ex.getMessage().contains(\"already exists\")) {\n// Key pair already exists.\nlogger.info(\"The key pair '\" + keyName + \"' already exists.", "mimetype": "text/plain", "start_char_idx": 1462224, "end_char_idx": 1466129, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b51d85ae-2c1f-43a3-b1bf-bfe1c30f4433": {"__data__": {"id_": "b51d85ae-2c1f-43a3-b1bf-bfe1c30f4433", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c404cbe3-2dac-410b-8445-7a2d3de78178", "node_type": "1", "metadata": {}, "hash": "b470d103a0f059598a947ddf2231aa16fc93e2ccfd9023aadb6889ac16238f65", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c5cbb8ea-7756-49ab-8d37-6e0b28eb2e35", "node_type": "1", "metadata": {}, "hash": "f5989cc374abb9b06c8268fa8a980090507e86fe41712d918eb2dfd276e7cd08", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Create an RSA key pair and save the private key material as\na .pem file.\");\nlogger.info(\"\"\"\nAn RSA key pair for Amazon EC2 is a security mechanism used to\nauthenticate and secure\naccess to your EC2 instances. It consists of a public key and a private\nkey,\nwhich are generated as a pair.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.createKeyPairAsync(keyName, fileName);\nCreateKeyPairResponse response = future.join();\nlogger.info(\"Key Pair successfully created. Key Fingerprint: \" +\nresponse.keyFingerprint());\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nif (ec2Ex.getMessage().contains(\"already exists\")) {\n// Key pair already exists.\nlogger.info(\"The key pair '\" + keyName + \"' already exists.\nMoving on...\");\n} else {\nlogger.info(\"EC2 error occurred: Error message: {}, Error code\n{}\", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n}\nBasics 999\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else {\nlogger.info(\"An unexpected error occurred: \" + (rt.getMessage()));\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"2. List key pairs.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.describeKeysAsync();\nDescribeKeyPairsResponse keyPairsResponse = future.join();\nkeyPairsResponse.keyPairs().forEach(keyPair -> logger.info(\n\"Found key pair with name {} and fingerprint {}\",\nkeyPair.keyName(),\nkeyPair.keyFingerprint()));\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Error message: {}, Error code {}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", (cause != null ?\ncause.getMessage() : rt.getMessage()));\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"3. Create a security group.\");\nlogger.info(\"\"\"\nAn AWS EC2 Security Group is a virtual firewall that controls the\ninbound and outbound traffic to an EC2 instance. It acts as a first\nline\nof defense for your EC2 instances, allowing you to specify the rules\nthat\ngovern the network traffic entering and leaving your instances.\nBasics 1000\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"\"\");\nwaitForInputToContinue(scanner);\nString groupId = \"\";\ntry {\nCompletableFuture future =\nec2Actions.createSecurityGroupAsync(groupName, groupDesc, vpcId, myIpAddress);\nfuture.join();\nlogger.info(\"Created security group\") ;\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nif (ec2Ex.awsErrorDetails().errorMessage().contains(\"already\nexists\")) {\nlogger.info(\"The Security Group already exists. Moving on...\");\n} else {\nlogger.error(\"An unexpected error occurred: {}\",\nec2Ex.awsErrorDetails().errorMessage());\nreturn;\n}\n} else {\nlogger.error(\"An unexpected error occurred: {}\",\ncause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"4. Display security group information for the new security\ngroup.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.describeSecurityGroupArnByNameAsync(groupName);\ngroupId = future.join();\nlogger.info(\"The security group Id is \"+groupId);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nString errorCode = ec2Ex.awsErrorDetails().errorCode();\nif (\"InvalidGroup.NotFound\".equals(errorCode)) {\nBasics 1001\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Security group '{}' does not exist. Error Code:\n{}\", groupName, errorCode);\n} else {\nlogger.info(\"EC2 error occurred: Message {}, Error Code: {}\",\nec2Ex.getMessage(), errorCode);\n}\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"5. Get a list of Amazon Linux 2 AMIs and select one with amzn2\nin the name.\");\nlogger.info(\"\"\"\nAn Amazon EC2 AMI (Amazon Machine Image) is a pre-configured virtual\nmachine image that\nserves as a template for launching EC2 instances.", "mimetype": "text/plain", "start_char_idx": 1465308, "end_char_idx": 1469657, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c5cbb8ea-7756-49ab-8d37-6e0b28eb2e35": {"__data__": {"id_": "c5cbb8ea-7756-49ab-8d37-6e0b28eb2e35", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b51d85ae-2c1f-43a3-b1bf-bfe1c30f4433", "node_type": "1", "metadata": {}, "hash": "7d4458a380cb2d6e8dc652b7da7fb915d19ee36554c1b303563fb17e146f8ff0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0d805e0a-e9f7-4b32-83be-681e14b0476a", "node_type": "1", "metadata": {}, "hash": "32fc2730662bd55c348ee303aae6735373dbfab11bb28432361f43cc712a3a31", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Error Code:\n{}\", groupName, errorCode);\n} else {\nlogger.info(\"EC2 error occurred: Message {}, Error Code: {}\",\nec2Ex.getMessage(), errorCode);\n}\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"5. Get a list of Amazon Linux 2 AMIs and select one with amzn2\nin the name.\");\nlogger.info(\"\"\"\nAn Amazon EC2 AMI (Amazon Machine Image) is a pre-configured virtual\nmachine image that\nserves as a template for launching EC2 instances. It contains all the\nnecessary software and\nconfigurations required to run an application or operating system on an\nEC2 instance.\n\"\"\");\nwaitForInputToContinue(scanner);\nString instanceAMI=\"\";\ntry {\nCompletableFuture future =\nec2Actions.getParaValuesAsync();\nGetParametersByPathResponse pathResponse = future.join();\nList parameterList = pathResponse.parameters();\nfor (Parameter para : parameterList) {\nif (filterName(para.name())) {\ninstanceAMI = para.value();\nbreak;\n}\n}\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nBasics 1002\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nlogger.info(\"The AMI value with amzn2 is: {}\", instanceAMI);\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"6. Get the (Amazon Machine Image) AMI value from the amzn2\nimage.\");\nlogger.info(\"\"\"\nAn AMI value represents a specific version of a virtual machine (VM) or\nserver image.\nIt uniquely identifies a particular version of an EC2 instance, including\nits operating system,\npre-installed software, and any custom configurations. This allows you to\nconsistently deploy the same\nVM image across your infrastructure.\n\"\"\");\nwaitForInputToContinue(scanner);\nString amiValue;\ntry {\nCompletableFuture future =\nec2Actions.describeImageAsync(instanceAMI);\namiValue = future.join();\n} catch (CompletionException ce) {\nThrowable cause = ce.getCause();\nif (cause instanceof Ec2Exception) {\nEc2Exception ec2Ex = (Ec2Exception) cause;\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nBasics 1003\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"7. Retrieves an instance type available in the current AWS\nregion.\");\nwaitForInputToContinue(scanner);\nString instanceType;\ntry {\nCompletableFuture future = ec2Actions.getInstanceTypesAsync();\ninstanceType = future.join();\nif (!instanceType.isEmpty()) {\nlogger.info(\"Found instance type: \" + instanceType);\n} else {\nlogger.info(\"Desired instance type not found.\");\n}\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"8. Create an Amazon EC2 instance using the key pair, the\ninstance type, the security group, and the EC2 AMI value.\");\nlogger.info(\"Once the EC2 instance is created, it is placed into a running\nstate.\");\nwaitForInputToContinue(scanner);\nString newInstanceId;\ntry {\nCompletableFuture future =\nec2Actions.runInstanceAsync(instanceType, keyName, groupName, amiValue);\nnewInstanceId = future.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception) {\nEc2Exception ec2Ex = (Ec2Exception) cause;\nswitch (ec2Ex.awsErrorDetails().errorCode()) {\ncase \"InvalidParameterValue\":\nBasics 1004\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nbreak;\ncase \"InsufficientInstanceCapacity\":\n// Handle insufficient instance capacity.", "mimetype": "text/plain", "start_char_idx": 1469110, "end_char_idx": 1473483, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "0d805e0a-e9f7-4b32-83be-681e14b0476a": {"__data__": {"id_": "0d805e0a-e9f7-4b32-83be-681e14b0476a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c5cbb8ea-7756-49ab-8d37-6e0b28eb2e35", "node_type": "1", "metadata": {}, "hash": "f5989cc374abb9b06c8268fa8a980090507e86fe41712d918eb2dfd276e7cd08", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c1b0ee22-7e73-40d2-b685-0f7d82f61339", "node_type": "1", "metadata": {}, "hash": "972036a6d4e0c9aaea7e29bc394aee8d8de2adb5ffe8bcc043637bd5b1536e94", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nlogger.info(\"Once the EC2 instance is created, it is placed into a running\nstate.\");\nwaitForInputToContinue(scanner);\nString newInstanceId;\ntry {\nCompletableFuture future =\nec2Actions.runInstanceAsync(instanceType, keyName, groupName, amiValue);\nnewInstanceId = future.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception) {\nEc2Exception ec2Ex = (Ec2Exception) cause;\nswitch (ec2Ex.awsErrorDetails().errorCode()) {\ncase \"InvalidParameterValue\":\nBasics 1004\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nbreak;\ncase \"InsufficientInstanceCapacity\":\n// Handle insufficient instance capacity.\nlogger.info(\"Insufficient instance capacity: {}, {}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nbreak;\ncase \"InvalidGroup.NotFound\":\n// Handle security group not found.\nlogger.info(\"Security group not found: {},{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nbreak;\ndefault:\nlogger.info(\"EC2 error occurred: {} (Code: {}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nbreak;\n}\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", (cause != null ?\ncause.getMessage() : rt.getMessage()));\nreturn;\n}\n}\nlogger.info(\"The instance Id is \" + newInstanceId);\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"9. Display information about the running instance. \");\nwaitForInputToContinue(scanner);\nString publicIp;\ntry {\nCompletableFuture future =\nec2Actions.describeEC2InstancesAsync(newInstanceId);\npublicIp = future.join();\nlogger.info(\"EC2 instance public IP {}\", publicIp);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nBasics 1005\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nlogger.info(\"You can SSH to the instance using this command:\");\nlogger.info(\"ssh -i \" + fileName + \" ec2-user@\" + publicIp);\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"10. Stop the instance using a waiter (this may take a few\nmins).\");\n// Remove the 2nd one\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.stopInstanceAsync(newInstanceId);\nfuture.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"11. Start the instance using a waiter (this may take a few\nmins).\");\ntry {\nCompletableFuture future =\nec2Actions.startInstanceAsync(newInstanceId);\nfuture.join();\nBasics 1006\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\n// Handle EC2 exceptions.\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"12. Allocate an Elastic IP address and associate it with the\ninstance.\");\nlogger.info(\"\"\"\nAn Elastic IP address is a static public IP address that you can\nassociate with your EC2 instance.\nThis allows you to have a fixed, predictable IP address that remains the\nsame even if your instance\nis stopped, terminated, or replaced.\nThis is particularly useful for applications or services that need to be\naccessed consistently from a\nknown IP address.\nAn EC2 Allocation ID (also known as a Reserved Instance Allocation\nID) is a unique identifier associated with a Reserved Instance (RI) that you have\npurchased in AWS.\nWhen you purchase a Reserved Instance, AWS assigns a unique Allocation\nID to it.", "mimetype": "text/plain", "start_char_idx": 1472703, "end_char_idx": 1477060, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "c1b0ee22-7e73-40d2-b685-0f7d82f61339": {"__data__": {"id_": "c1b0ee22-7e73-40d2-b685-0f7d82f61339", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0d805e0a-e9f7-4b32-83be-681e14b0476a", "node_type": "1", "metadata": {}, "hash": "32fc2730662bd55c348ee303aae6735373dbfab11bb28432361f43cc712a3a31", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "825d64b5-8bd2-44c8-9765-1bba4faa0ddc", "node_type": "1", "metadata": {}, "hash": "10bd50d97fdbd9a1b69cc801dfe4a39bcb27b1fe233705530c2570fc9877a7bb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Allocate an Elastic IP address and associate it with the\ninstance.\");\nlogger.info(\"\"\"\nAn Elastic IP address is a static public IP address that you can\nassociate with your EC2 instance.\nThis allows you to have a fixed, predictable IP address that remains the\nsame even if your instance\nis stopped, terminated, or replaced.\nThis is particularly useful for applications or services that need to be\naccessed consistently from a\nknown IP address.\nAn EC2 Allocation ID (also known as a Reserved Instance Allocation\nID) is a unique identifier associated with a Reserved Instance (RI) that you have\npurchased in AWS.\nWhen you purchase a Reserved Instance, AWS assigns a unique Allocation\nID to it.\nThis Allocation ID is used to track and identify the specific RI you\nhave purchased,\nand it is important for managing and monitoring your Reserved Instances.\n\"\"\");\nwaitForInputToContinue(scanner);\nString allocationId;\ntry {\nCompletableFuture future = ec2Actions.allocateAddressAsync();\nBasics 1007\nAWS SDK for Java 2.x Developer Guide for version 2.x\nallocationId = future.join();\nlogger.info(\"Successfully allocated address with ID: \" +allocationId);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nlogger.info(\"The allocation Id value is \" + allocationId);\nwaitForInputToContinue(scanner);\nString associationId;\ntry {\nCompletableFuture future =\nec2Actions.associateAddressAsync(newInstanceId, allocationId);\nassociationId = future.join();\nlogger.info(\"Successfully associated address with ID: \" +associationId);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"13. Describe the instance again. Note that the public IP\naddress has changed\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.describeEC2InstancesAsync(newInstanceId);\npublicIp = future.join();\nlogger.info(\"EC2 instance public IP: \" + publicIp);\nBasics 1008\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"You can SSH to the instance using this command:\");\nlogger.info(\"ssh -i \" + fileName + \" ec2-user@\" + publicIp);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"14. Disassociate and release the Elastic IP address.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.disassociateAddressAsync(associationId);\nfuture.join();\nlogger.info(\"Address successfully disassociated.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\n// Handle EC2 exceptions.\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.releaseEC2AddressAsync(allocationId);\nfuture.join(); // Wait for the operation to complete\nlogger.info(\"Elastic IP address successfully released.\");\n} catch (RuntimeException rte) {\nlogger.info(\"An unexpected error occurred: {}\", rte.getMessage());\nBasics 1009\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"15. Terminate the instance and use a waiter (this may take a\nfew mins).\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.terminateEC2Async(newInstanceId);\nfuture.join();\nlogger.info(\"EC2 instance successfully terminated.", "mimetype": "text/plain", "start_char_idx": 1476371, "end_char_idx": 1480862, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "825d64b5-8bd2-44c8-9765-1bba4faa0ddc": {"__data__": {"id_": "825d64b5-8bd2-44c8-9765-1bba4faa0ddc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c1b0ee22-7e73-40d2-b685-0f7d82f61339", "node_type": "1", "metadata": {}, "hash": "972036a6d4e0c9aaea7e29bc394aee8d8de2adb5ffe8bcc043637bd5b1536e94", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a8ffab7c-f34e-491f-81a3-969b7f39ce19", "node_type": "1", "metadata": {}, "hash": "a488786a2ee072bc76ecb432c3163ae88520508a637a4957d254c8d9df0725e2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} catch (RuntimeException rte) {\nlogger.info(\"An unexpected error occurred: {}\", rte.getMessage());\nBasics 1009\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"15. Terminate the instance and use a waiter (this may take a\nfew mins).\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.terminateEC2Async(newInstanceId);\nfuture.join();\nlogger.info(\"EC2 instance successfully terminated.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\n// Handle EC2 exceptions.\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"16. Delete the security group.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.deleteEC2SecGroupAsync(groupId);\nfuture.join();\nlogger.info(\"Security group successfully deleted.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nBasics 1010\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"17. Delete the key.\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nec2Actions.deleteKeysAsync(keyName);\nfuture.join();\nlogger.info(\"Successfully deleted key pair named \" + keyName);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof Ec2Exception ec2Ex) {\nlogger.info(\"EC2 error occurred: Message {}, Error Code:{}\",\nec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());\nreturn;\n} else {\nlogger.info(\"An unexpected error occurred: {}\", cause.getMessage());\nreturn;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(DASHES);\nlogger.info(\"You successfully completed the Amazon EC2 scenario.\");\nlogger.info(DASHES);\n}\npublic static boolean filterName(String name) {\nString[] parts = name.split(\"/\");\nString myValue = parts[4];\nreturn myValue.contains(\"amzn2\");\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nBasics 1011\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\n// Handle invalid input.\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nDefine a class that wraps EC2 actions.", "mimetype": "text/plain", "start_char_idx": 1480336, "end_char_idx": 1483326, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a8ffab7c-f34e-491f-81a3-969b7f39ce19": {"__data__": {"id_": "a8ffab7c-f34e-491f-81a3-969b7f39ce19", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "825d64b5-8bd2-44c8-9765-1bba4faa0ddc", "node_type": "1", "metadata": {}, "hash": "10bd50d97fdbd9a1b69cc801dfe4a39bcb27b1fe233705530c2570fc9877a7bb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4e31807-a78d-4cc3-9f84-5015ff0dae18", "node_type": "1", "metadata": {}, "hash": "3a845e2a83b4129fb979962b5f7e11f5aefb19ead9bf9dc6b4b26b6740381622", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nlogger.info(DASHES);\n}\npublic static boolean filterName(String name) {\nString[] parts = name.split(\"/\");\nString myValue = parts[4];\nreturn myValue.contains(\"amzn2\");\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nBasics 1011\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\n// Handle invalid input.\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nDefine a class that wraps EC2 actions.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.AllocateAddressRequest;\nimport software.amazon.awssdk.services.ec2.model.AllocateAddressResponse;\nimport software.amazon.awssdk.services.ec2.model.AssociateAddressRequest;\nimport software.amazon.awssdk.services.ec2.model.AssociateAddressResponse;\nimport\nsoftware.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;\nimport software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;\nimport software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;\nimport software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;\nimport software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest;\nimport software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;\nimport software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupRequest;\nimport software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeImagesRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeInstanceTypesRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeInstanceTypesResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;\nimport software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;\nimport software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest;\nBasics 1012\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.ec2.model.DisassociateAddressRequest;\nimport software.amazon.awssdk.services.ec2.model.DisassociateAddressResponse;\nimport software.amazon.awssdk.services.ec2.model.DomainType;\nimport software.amazon.awssdk.services.ec2.model.Ec2Exception;\nimport software.amazon.awssdk.services.ec2.model.Filter;\nimport software.amazon.awssdk.services.ec2.model.InstanceTypeInfo;\nimport software.amazon.awssdk.services.ec2.model.IpPermission;\nimport software.amazon.awssdk.services.ec2.model.IpRange;\nimport software.amazon.awssdk.services.ec2.model.ReleaseAddressRequest;\nimport software.amazon.awssdk.services.ec2.model.ReleaseAddressResponse;\nimport software.amazon.awssdk.services.ec2.model.RunInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.RunInstancesResponse;\nimport software.amazon.awssdk.services.ec2.model.StopInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.StartInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.TerminateInstancesRequest;\nimport software.amazon.awssdk.services.ec2.model.Vpc;\nimport software.amazon.awssdk.services.ec2.paginators.DescribeImagesPublisher;\nimport software.amazon.awssdk.services.ec2.paginators.DescribeInstancesPublisher;\nimport\nsoftware.amazon.awssdk.services.ec2.paginators.DescribeSecurityGroupsPublisher;\nimport software.amazon.awssdk.services.ec2.paginators.DescribeVpcsPublisher;\nimport software.amazon.awssdk.services.ec2.waiters.Ec2AsyncWaiter;\nimport software.amazon.awssdk.services.ssm.SsmAsyncClient;\nimport software.amazon.awssdk.services.ssm.model.GetParametersByPathRequest;\nimport software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse;\nimport software.amazon.awssdk.services.ec2.model.TerminateInstancesResponse;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\nimport java.util.concurrent.atomic.AtomicReference;\npublic class EC2Actions {\nprivate static final Logger logger = LoggerFactory.getLogger(EC2Actions.class);\nprivate static Ec2AsyncClient ec2AsyncClient;\n/**\n* Retrieves an asynchronous Amazon Elastic Container Registry (ECR) client.", "mimetype": "text/plain", "start_char_idx": 1482659, "end_char_idx": 1487557, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b4e31807-a78d-4cc3-9f84-5015ff0dae18": {"__data__": {"id_": "b4e31807-a78d-4cc3-9f84-5015ff0dae18", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a8ffab7c-f34e-491f-81a3-969b7f39ce19", "node_type": "1", "metadata": {}, "hash": "a488786a2ee072bc76ecb432c3163ae88520508a637a4957d254c8d9df0725e2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1fa0bb22-6ade-4b0f-a66c-cd24b1300982", "node_type": "1", "metadata": {}, "hash": "8805883448b91a9a669aaba981dc8a16a84755e8c2589763afcecb27607c8da6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @return the configured ECR asynchronous client.\n*/\nBasics 1013\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate static Ec2AsyncClient getAsyncClient() {\nif (ec2AsyncClient == null) {\n/*\nThe `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java,\nversion 2,\nand it is designed to provide a high-performance, asynchronous HTTP\nclient for interacting with AWS services.\nIt uses the Netty framework to handle the underlying network\ncommunication and the Java NIO API to\nprovide a non-blocking, event-driven approach to HTTP requests and\nresponses.\n*/\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(50) // Adjust as needed.\n.connectionTimeout(Duration.ofSeconds(60)) // Set the connection\ntimeout.\n.readTimeout(Duration.ofSeconds(60)) // Set the read timeout.\n.writeTimeout(Duration.ofSeconds(60)) // Set the write timeout.\n.build();\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2)) // Set the overall API call\ntimeout.\n.apiCallAttemptTimeout(Duration.ofSeconds(90)) // Set the\nindividual call attempt timeout.\n.build();\nec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn ec2AsyncClient;\n}\n/**\n* Deletes a key pair asynchronously.\n*\n* @param keyPair the name of the key pair to delete\n* @return a {@link CompletableFuture} that represents the result of the\nasynchronous operation.\nBasics 1014\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* The {@link CompletableFuture} will complete with a {@link\nDeleteKeyPairResponse} object\n* that provides the result of the key pair deletion operation.\n*/\npublic CompletableFuture deleteKeysAsync(String keyPair)\n{\nDeleteKeyPairRequest request = DeleteKeyPairRequest.builder()\n.keyName(keyPair)\n.build();\n// Initiate the asynchronous request to delete the key pair.\nCompletableFuture response =\ngetAsyncClient().deleteKeyPair(request);\nreturn response.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete key pair: \" + keyPair,\nex);\n} else if (resp == null) {\nthrow new RuntimeException(\"No response received for deleting key\npair: \" + keyPair);\n}\n});\n}\n/**\n* Deletes an EC2 security group asynchronously.\n*\n* @param groupId the ID of the security group to delete\n* @return a CompletableFuture that completes when the security group is deleted\n*/\npublic CompletableFuture deleteEC2SecGroupAsync(String groupId) {\nDeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()\n.groupId(groupId)\n.build();\nCompletableFuture response =\ngetAsyncClient().deleteSecurityGroup(request);\nreturn response.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete security group with Id\n\" + groupId, ex);\n} else if (resp == null) {\nthrow new RuntimeException(\"No response received for deleting\nsecurity group with Id \" + groupId);\nBasics 1015\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}).thenApply(resp -> null);\n}\n/**\n* Terminates an EC2 instance asynchronously and waits for it to reach the\nterminated state.\n*\n* @param instanceId the ID of the EC2 instance to terminate\n* @return a {@link CompletableFuture} that completes when the instance has been\nterminated\n* @throws RuntimeException if there is no response from the AWS SDK or if there\nis a failure during the termination process\n*/\npublic CompletableFuture terminateEC2Async(String instanceId) {\nTerminateInstancesRequest terminateRequest =\nTerminateInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().terminateInstances(terminateRequest);\nreturn responseFuture.thenCompose(terminateResponse -> {\nif (terminateResponse == null) {\nthrow new RuntimeException(\"No response received for terminating\ninstance \" + instanceId);\n}\nSystem.out.println(\"Going to terminate an EC2 instance and use a waiter\nto wait for it to be in terminated state\");\nreturn getAsyncClient().waiter()\n.waitUntilInstanceTerminated(r -> r.instanceIds(instanceId))\n.thenApply(waiterResponse -> null);\n}).exceptionally(throwable -> {\n// Handle any exceptions that occurred during the async call\nthrow new RuntimeException(\"Failed to terminate EC2 instance: \" +\nthrowable.getMessage(), throwable);\n});\n}\n/**\n* Releases an Elastic IP address asynchronously.", "mimetype": "text/plain", "start_char_idx": 1487558, "end_char_idx": 1492078, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1fa0bb22-6ade-4b0f-a66c-cd24b1300982": {"__data__": {"id_": "1fa0bb22-6ade-4b0f-a66c-cd24b1300982", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b4e31807-a78d-4cc3-9f84-5015ff0dae18", "node_type": "1", "metadata": {}, "hash": "3a845e2a83b4129fb979962b5f7e11f5aefb19ead9bf9dc6b4b26b6740381622", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "32ac2345-4985-4dd4-877a-ff2959a8d9b6", "node_type": "1", "metadata": {}, "hash": "eb62d4cfe9615bc90c753df56d599fd7943936069d19ba5e278116e12c9fed09", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param allocId the allocation ID of the Elastic IP address to be released\nBasics 1016\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof releasing the Elastic IP address\n*/\npublic CompletableFuture releaseEC2AddressAsync(String\nallocId) {\nReleaseAddressRequest request = ReleaseAddressRequest.builder()\n.allocationId(allocId)\n.build();\nCompletableFuture response =\ngetAsyncClient().releaseAddress(request);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to release Elastic IP address\",\nex);\n}\n});\nreturn response;\n}\n/**\n* Disassociates an Elastic IP address from an instance asynchronously.\n*\n* @param associationId The ID of the association you want to disassociate.\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof disassociating the address. The\n* {@link CompletableFuture} will complete with a {@link\nDisassociateAddressResponse} when the operation is\n* finished.\n* @throws RuntimeException if the disassociation of the address fails.\n*/\npublic CompletableFuture\ndisassociateAddressAsync(String associationId) {\nEc2AsyncClient ec2 = getAsyncClient();\nDisassociateAddressRequest addressRequest =\nDisassociateAddressRequest.builder()\n.associationId(associationId)\n.build();\n// Disassociate the address asynchronously.\nCompletableFuture response =\nec2.disassociateAddress(addressRequest);\nresponse.whenComplete((resp, ex) -> {\nBasics 1017\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (ex != null) {\nthrow new RuntimeException(\"Failed to disassociate address\", ex);\n}\n});\nreturn response;\n}\n/**\n* Associates an Elastic IP address with an EC2 instance asynchronously.\n*\n* @param instanceId the ID of the EC2 instance to associate the Elastic IP\naddress with\n* @param allocationId the allocation ID of the Elastic IP address to associate\n* @return a {@link CompletableFuture} that completes with the association ID\nwhen the operation is successful,\n* or throws a {@link RuntimeException} if the operation fails\n*/\npublic CompletableFuture associateAddressAsync(String instanceId, String\nallocationId) {\nAssociateAddressRequest associateRequest = AssociateAddressRequest.builder()\n.instanceId(instanceId)\n.allocationId(allocationId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().associateAddress(associateRequest);\nreturn responseFuture.thenApply(response -> {\nif (response.associationId() != null) {\nreturn response.associationId();\n} else {\nthrow new RuntimeException(\"Association ID is null after associating\naddress.\");\n}\n}).whenComplete((result, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to associate address\", ex);\n}\n});\n}\n/**\n* Allocates an Elastic IP address asynchronously in the VPC domain.\n*\nBasics 1018\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} containing the allocation ID of the\nallocated Elastic IP address\n*/\npublic CompletableFuture allocateAddressAsync() {\nAllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()\n.domain(DomainType.VPC)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().allocateAddress(allocateRequest);\nreturn\nresponseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result,\nex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to allocate address\", ex);\n}\n});\n}\n/**\n* Asynchronously describes the state of an EC2 instance.\n* The paginator helps you iterate over multiple pages of results.\n*\n* @param newInstanceId the ID of the EC2 instance to describe\n* @return a {@link CompletableFuture} that, when completed, contains a string\ndescribing the state of the EC2 instance\n*/\npublic CompletableFuture describeEC2InstancesAsync(String newInstanceId)\n{\nDescribeInstancesRequest request = DescribeInstancesRequest.builder()\n.instanceIds(newInstanceId)\n.build();\nDescribeInstancesPublisher paginator =\ngetAsyncClient().describeInstancesPaginator(request);\nAtomicReference publicIpAddressRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.reservations().stream()\n.flatMap(reservation -> reservation.instances().stream())\n.filter(instance -> instance.instanceId().equals(newInstanceId))\n.findFirst()\n.ifPresent(instance ->\npublicIpAddressRef.set(instance.publicIpAddress()));\n}).thenApply(v -> {\nBasics 1019\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString publicIpAddress = publicIpAddressRef.get();\nif (publicIpAddress == null) {\nthrow new RuntimeException(\"Instance with ID \" + newInstanceId + \"\nnot found.", "mimetype": "text/plain", "start_char_idx": 1492079, "end_char_idx": 1496864, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "32ac2345-4985-4dd4-877a-ff2959a8d9b6": {"__data__": {"id_": "32ac2345-4985-4dd4-877a-ff2959a8d9b6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1fa0bb22-6ade-4b0f-a66c-cd24b1300982", "node_type": "1", "metadata": {}, "hash": "8805883448b91a9a669aaba981dc8a16a84755e8c2589763afcecb27607c8da6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2d0bff93-13f8-4b98-bda4-cdde6c7af180", "node_type": "1", "metadata": {}, "hash": "39c1f3af8a2d5c33fdb8dc33aa9f2ab1c082bfe5e7bb46993c1b63d0c07bebb0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\nreturn publicIpAddress;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe instances: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe instances\", ex);\n});\n}\n/**\n* Runs an EC2 instance asynchronously.\n*\n* @param instanceType The instance type to use for the EC2 instance.\n* @param keyName The name of the key pair to associate with the EC2 instance.\n* @param groupName The name of the security group to associate with the EC2\ninstance.\n* @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2\ninstance.\n* @return A {@link CompletableFuture} that completes with the ID of the started\nEC2 instance.\n* @throws RuntimeException If there is an error running the EC2 instance.\n*/\npublic CompletableFuture runInstanceAsync(String instanceType, String\nkeyName, String groupName, String amiId) {\nRunInstancesRequest runRequest = RunInstancesRequest.builder()\n.instanceType(instanceType)\n.keyName(keyName)\n.securityGroups(groupName)\n.maxCount(1)\n.minCount(1)\n.imageId(amiId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().runInstances(runRequest);\nreturn responseFuture.thenCompose(response -> {\nString instanceIdVal = response.instances().get(0).instanceId();\nSystem.out.println(\"Going to start an EC2 instance and use a waiter to\nwait for it to be in running state\");\nreturn getAsyncClient().waiter()\n.waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal))\nBasics 1020\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.thenCompose(waitResponse -> getAsyncClient().waiter()\n.waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal))\n.thenApply(runningResponse -> instanceIdVal));\n}).exceptionally(throwable -> {\n// Handle any exceptions that occurred during the async call\nthrow new RuntimeException(\"Failed to run EC2 instance: \" +\nthrowable.getMessage(), throwable);\n});\n}\n/**\n* Asynchronously retrieves the instance types available in the current AWS\nregion.\n*

\n* This method uses the AWS SDK's asynchronous API to fetch the available\ninstance types\n* and then processes the response. It logs the memory information, network\ninformation,\n* and instance type for each instance type returned. Additionally, it returns a\n* {@link CompletableFuture} that resolves to the instance type string for the\n\"t2.2xlarge\"\n* instance type, if it is found in the response. If the \"t2.2xlarge\" instance\ntype is not\n* found, an empty string is returned.\n*

\n*\n* @return a {@link CompletableFuture} that resolves to the instance type string\nfor the\n* \"t2.2xlarge\" instance type, or an empty string if the instance type is not\nfound\n*/\npublic CompletableFuture getInstanceTypesAsync() {\nDescribeInstanceTypesRequest typesRequest =\nDescribeInstanceTypesRequest.builder()\n.maxResults(10)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeInstanceTypes(typesRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nList instanceTypes = resp.instanceTypes();\nfor (InstanceTypeInfo type : instanceTypes) {\nBasics 1021\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"The memory information of this type is \" +\ntype.memoryInfo().sizeInMiB());\nlogger.info(\"Network information is \" +\ntype.networkInfo().toString());\nlogger.info(\"Instance type is \" +\ntype.instanceType().toString());\n}\n} else {\nthrow (RuntimeException) ex;\n}\n});\nreturn response.thenApply(resp -> {\nfor (InstanceTypeInfo type : resp.instanceTypes()) {\nString instanceType = type.instanceType().toString();\nif (instanceType.equals(\"t2.2xlarge\")) {\nreturn instanceType;\n}\n}\nreturn \"\";\n});\n}\n/**\n* Asynchronously describes an AWS EC2 image with the specified image ID.", "mimetype": "text/plain", "start_char_idx": 1496864, "end_char_idx": 1500573, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2d0bff93-13f8-4b98-bda4-cdde6c7af180": {"__data__": {"id_": "2d0bff93-13f8-4b98-bda4-cdde6c7af180", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "32ac2345-4985-4dd4-877a-ff2959a8d9b6", "node_type": "1", "metadata": {}, "hash": "eb62d4cfe9615bc90c753df56d599fd7943936069d19ba5e278116e12c9fed09", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "15311a2c-b9fe-41a7-adb3-b81ffb855d2f", "node_type": "1", "metadata": {}, "hash": "34d62052ac9c6a55f7c8cb7d3682034a189c065a8ff7e9bc5c4db49cc8d0fc49", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param imageId the ID of the image to be described\n* @return a {@link CompletableFuture} that, when completed, contains the ID of\nthe described image\n* @throws RuntimeException if no images are found with the provided image ID,\nor if an error occurs during the AWS API call\n*/\npublic CompletableFuture describeImageAsync(String imageId) {\nDescribeImagesRequest imagesRequest = DescribeImagesRequest.builder()\n.imageIds(imageId)\n.build();\nAtomicReference imageIdRef = new AtomicReference<>();\nDescribeImagesPublisher paginator =\ngetAsyncClient().describeImagesPaginator(imagesRequest);\nreturn paginator.subscribe(response -> {\nresponse.images().stream()\n.filter(image -> image.imageId().equals(imageId))\n.findFirst()\nBasics 1022\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.ifPresent(image -> {\nlogger.info(\"The description of the image is \" +\nimage.description());\nlogger.info(\"The name of the image is \" + image.name());\nimageIdRef.set(image.imageId());\n});\n}).thenApply(v -> {\nString id = imageIdRef.get();\nif (id == null) {\nthrow new RuntimeException(\"No images found with the provided image\nID.\");\n}\nreturn id;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe image: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe image\", ex);\n});\n}\n/**\n* Retrieves the parameter values asynchronously using the AWS Systems Manager\n(SSM) API.\n*\n* @return a {@link CompletableFuture} that holds the response from the SSM API\ncall to get parameters by path\n*/\npublic CompletableFuture getParaValuesAsync() {\nSsmAsyncClient ssmClient = SsmAsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\nGetParametersByPathRequest parameterRequest =\nGetParametersByPathRequest.builder()\n.path(\"/aws/service/ami-amazon-linux-latest\")\n.build();\n// Create a CompletableFuture to hold the final result.\nCompletableFuture responseFuture = new\nCompletableFuture<>();\nssmClient.getParametersByPath(parameterRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nresponseFuture.completeExceptionally(new\nRuntimeException(\"Failed to get parameters by path\", exception));\nBasics 1023\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} else {\nresponseFuture.complete(response);\n}\n});\nreturn responseFuture;\n}\n/**\n* Asynchronously describes the security groups for the specified group ID.\n*\n* @param groupName the name of the security group to describe\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of describing the security groups. The future will complete with a\n* {@link DescribeSecurityGroupsResponse} object that contains the\n* security group information.\n*/\npublic CompletableFuture describeSecurityGroupArnByNameAsync(String\ngroupName) {\nDescribeSecurityGroupsRequest request =\nDescribeSecurityGroupsRequest.builder()\n.groupNames(groupName)\n.build();\nDescribeSecurityGroupsPublisher paginator =\ngetAsyncClient().describeSecurityGroupsPaginator(request);\nAtomicReference groupIdRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.securityGroups().stream()\n.filter(securityGroup ->\nsecurityGroup.groupName().equals(groupName))\n.findFirst()\n.ifPresent(securityGroup ->\ngroupIdRef.set(securityGroup.groupId()));\n}).thenApply(v -> {\nString groupId = groupIdRef.get();\nif (groupId == null) {\nthrow new RuntimeException(\"No security group found with the name: \"\n+ groupName);\n}\nreturn groupId;\n}).exceptionally(ex -> {\nBasics 1024\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Failed to describe security group: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe security group\", ex);\n});\n}\n/**\n* Creates a new security group asynchronously with the specified group name,\ndescription, and VPC ID. It also\n* authorizes inbound traffic on ports 80 and 22 from the specified IP address.", "mimetype": "text/plain", "start_char_idx": 1500574, "end_char_idx": 1504484, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "15311a2c-b9fe-41a7-adb3-b81ffb855d2f": {"__data__": {"id_": "15311a2c-b9fe-41a7-adb3-b81ffb855d2f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2d0bff93-13f8-4b98-bda4-cdde6c7af180", "node_type": "1", "metadata": {}, "hash": "39c1f3af8a2d5c33fdb8dc33aa9f2ab1c082bfe5e7bb46993c1b63d0c07bebb0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4aa68656-7ec4-4046-800c-d31aeadf6d87", "node_type": "1", "metadata": {}, "hash": "7cadce83987804b9313ebf46131422038511a228ae5ed91bbd3214558c0134e3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "It also\n* authorizes inbound traffic on ports 80 and 22 from the specified IP address.\n*\n* @param groupName the name of the security group to create\n* @param groupDesc the description of the security group\n* @param vpcId the ID of the VPC in which to create the security group\n* @param myIpAddress the IP address from which to allow inbound traffic (e.g.,\n\"192.168.1.1/0\" to allow traffic from\n* any IP address in the 192.168.1.0/24 subnet)\n* @return a CompletableFuture that, when completed, returns the ID of the\ncreated security group\n* @throws RuntimeException if there was a failure creating the security group\nor authorizing the inbound traffic\n*/\npublic CompletableFuture createSecurityGroupAsync(String groupName,\nString groupDesc, String vpcId, String myIpAddress) {\nCreateSecurityGroupRequest createRequest =\nCreateSecurityGroupRequest.builder()\n.groupName(groupName)\n.description(groupDesc)\n.vpcId(vpcId)\n.build();\nreturn getAsyncClient().createSecurityGroup(createRequest)\n.thenCompose(createResponse -> {\nString groupId = createResponse.groupId();\nIpRange ipRange = IpRange.builder()\n.cidrIp(myIpAddress + \"/32\")\n.build();\nIpPermission ipPerm = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(80)\n.fromPort(80)\n.ipRanges(ipRange)\n.build();\nBasics 1025\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIpPermission ipPerm2 = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(22)\n.fromPort(22)\n.ipRanges(ipRange)\n.build();\nAuthorizeSecurityGroupIngressRequest authRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(groupName)\n.ipPermissions(ipPerm, ipPerm2)\n.build();\nreturn getAsyncClient().authorizeSecurityGroupIngress(authRequest)\n.thenApply(authResponse -> groupId);\n})\n.whenComplete((result, exception) -> {\nif (exception != null) {\nif (exception instanceof CompletionException &&\nexception.getCause() instanceof Ec2Exception) {\nthrow (Ec2Exception) exception.getCause();\n} else {\nthrow new RuntimeException(\"Failed to create security group:\n\" + exception.getMessage(), exception);\n}\n}\n});\n}\n/**\n* Asynchronously describes the key pairs associated with the current AWS\naccount.\n*\n* @return a {@link CompletableFuture} containing the {@link\nDescribeKeyPairsResponse} object, which provides\n* information about the key pairs.\n*/\npublic CompletableFuture describeKeysAsync() {\nCompletableFuture responseFuture =\ngetAsyncClient().describeKeyPairs();\nresponseFuture.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to describe key pairs: \" +\nexception.getMessage(), exception);\nBasics 1026\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n});\nreturn responseFuture;\n}\n/**\n* Creates a new key pair asynchronously.\n*\n* @param keyName the name of the key pair to create\n* @param fileName the name of the file to write the key material to\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of creating the key pair and writing the key material to a file\n*/\npublic CompletableFuture createKeyPairAsync(String\nkeyName, String fileName) {\nCreateKeyPairRequest request = CreateKeyPairRequest.builder()\n.keyName(keyName)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().createKeyPair(request);\nresponseFuture.whenComplete((response, exception) -> {\nif (response != null) {\ntry {\nBufferedWriter writer = new BufferedWriter(new\nFileWriter(fileName));\nwriter.write(response.keyMaterial());\nwriter.close();\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to write key material to\nfile: \" + e.getMessage(), e);\n}\n} else {\nthrow new RuntimeException(\"Failed to create key pair: \" +\nexception.getMessage(), exception);\n}\n});\nreturn responseFuture;\n}\n/**\nBasics 1027\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Describes the first default VPC asynchronously and using a paginator.", "mimetype": "text/plain", "start_char_idx": 1504398, "end_char_idx": 1508328, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4aa68656-7ec4-4046-800c-d31aeadf6d87": {"__data__": {"id_": "4aa68656-7ec4-4046-800c-d31aeadf6d87", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "15311a2c-b9fe-41a7-adb3-b81ffb855d2f", "node_type": "1", "metadata": {}, "hash": "34d62052ac9c6a55f7c8cb7d3682034a189c065a8ff7e9bc5c4db49cc8d0fc49", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a97a3b95-f676-40c4-bdbc-685040931765", "node_type": "1", "metadata": {}, "hash": "850f3b0001c84179cf250144a2fbeabb0439819211bb0d7bb5455074e9fcb48c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @return a {@link CompletableFuture} that, when completed, contains the first\ndefault VPC found.\\\n*/\npublic CompletableFuture describeFirstEC2VpcAsync() {\nFilter myFilter = Filter.builder()\n.name(\"is-default\")\n.values(\"true\")\n.build();\nDescribeVpcsRequest request = DescribeVpcsRequest.builder()\n.filters(myFilter)\n.build();\nDescribeVpcsPublisher paginator =\ngetAsyncClient().describeVpcsPaginator(request);\nAtomicReference vpcRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.vpcs().stream()\n.findFirst()\n.ifPresent(vpcRef::set);\n}).thenApply(v -> {\nVpc vpc = vpcRef.get();\nif (vpc == null) {\nthrow new RuntimeException(\"Default VPC not found\");\n}\nreturn vpc;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe VPCs: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe VPCs\", ex);\n});\n}\n/**\n* Stops the EC2 instance with the specified ID asynchronously and waits for the\ninstance to stop.\n*\n* @param instanceId the ID of the EC2 instance to stop\n* @return a {@link CompletableFuture} that completes when the instance has been\nstopped, or exceptionally if an error occurs\n*/\npublic CompletableFuture stopInstanceAsync(String instanceId) {\nStopInstancesRequest stopRequest = StopInstancesRequest.builder()\nBasics 1028\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.instanceIds(instanceId)\n.build();\nDescribeInstancesRequest describeRequest =\nDescribeInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nEc2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()\n.client(getAsyncClient())\n.build();\nCompletableFuture resultFuture = new CompletableFuture<>();\nlogger.info(\"Stopping instance \" + instanceId + \" and waiting for it to\nstop.\");\ngetAsyncClient().stopInstances(stopRequest)\n.thenCompose(response -> {\nif (response.stoppingInstances().isEmpty()) {\nreturn CompletableFuture.failedFuture(new RuntimeException(\"No\ninstances were stopped. Please check the instance ID: \" + instanceId));\n}\nreturn ec2Waiter.waitUntilInstanceStopped(describeRequest);\n})\n.thenAccept(waiterResponse -> {\nlogger.info(\"Successfully stopped instance \" + instanceId);\nresultFuture.complete(null);\n})\n.exceptionally(throwable -> {\nlogger.error(\"Failed to stop instance \" + instanceId + \": \" +\nthrowable.getMessage(), throwable);\nresultFuture.completeExceptionally(new RuntimeException(\"Failed to\nstop instance: \" + throwable.getMessage(), throwable));\nreturn null;\n});\nreturn resultFuture;\n}\n/**\n* Starts an Amazon EC2 instance asynchronously and waits until it is in the\n\"running\" state.\n*\n* @param instanceId the ID of the instance to start\nBasics 1029\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} that completes when the instance has been\nstarted and is in the \"running\" state, or exceptionally if an error occurs\n*/\npublic CompletableFuture startInstanceAsync(String instanceId) {\nStartInstancesRequest startRequest = StartInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nEc2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()\n.client(getAsyncClient())\n.build();\nDescribeInstancesRequest describeRequest =\nDescribeInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nlogger.info(\"Starting instance \" + instanceId + \" and waiting for it to\nrun.\");\nCompletableFuture resultFuture = new CompletableFuture<>();\nreturn getAsyncClient().startInstances(startRequest)\n.thenCompose(response ->\nec2Waiter.waitUntilInstanceRunning(describeRequest)\n)\n.thenAccept(waiterResponse -> {\nlogger.info(\"Successfully started instance \" + instanceId);\nresultFuture.complete(null);\n})\n.exceptionally(throwable -> {\nresultFuture.completeExceptionally(new RuntimeException(\"Failed to\nstart instance: \" + throwable.getMessage(), throwable));\nreturn null;\n});\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 AllocateAddress\n\u2022 AssociateAddress\n\u2022 AuthorizeSecurityGroupIngress\nBasics 1030\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 CreateKeyPair\n\u2022 CreateSecurityGroup\n\u2022 DeleteKeyPair\n\u2022 DeleteSecurityGroup\n\u2022 DescribeImages\n\u2022 DescribeInstanceTypes\n\u2022 DescribeInstances\n\u2022 DescribeKeyPairs\n\u2022 DescribeSecurityGroups\n\u2022 DisassociateAddress\n\u2022 ReleaseAddress\n\u2022 RunInstances\n\u2022 StartInstances\n\u2022 StopInstances\n\u2022 TerminateInstances\n\u2022 UnmonitorInstances\nActions\nAllocateAddress\nThe following code example shows how to use AllocateAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Allocates an Elastic IP address asynchronously in the VPC domain.", "mimetype": "text/plain", "start_char_idx": 1508329, "end_char_idx": 1512938, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a97a3b95-f676-40c4-bdbc-685040931765": {"__data__": {"id_": "a97a3b95-f676-40c4-bdbc-685040931765", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4aa68656-7ec4-4046-800c-d31aeadf6d87", "node_type": "1", "metadata": {}, "hash": "7cadce83987804b9313ebf46131422038511a228ae5ed91bbd3214558c0134e3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "222216fa-abd2-426d-9177-eaf07b21448f", "node_type": "1", "metadata": {}, "hash": "abe4fa752644b642199b863955a2ad74a3c9489c33e8c9c4f599befe1aebc636", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 AllocateAddress\n\u2022 AssociateAddress\n\u2022 AuthorizeSecurityGroupIngress\nBasics 1030\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 CreateKeyPair\n\u2022 CreateSecurityGroup\n\u2022 DeleteKeyPair\n\u2022 DeleteSecurityGroup\n\u2022 DescribeImages\n\u2022 DescribeInstanceTypes\n\u2022 DescribeInstances\n\u2022 DescribeKeyPairs\n\u2022 DescribeSecurityGroups\n\u2022 DisassociateAddress\n\u2022 ReleaseAddress\n\u2022 RunInstances\n\u2022 StartInstances\n\u2022 StopInstances\n\u2022 TerminateInstances\n\u2022 UnmonitorInstances\nActions\nAllocateAddress\nThe following code example shows how to use AllocateAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Allocates an Elastic IP address asynchronously in the VPC domain.\n*\nActions 1031\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} containing the allocation ID of the\nallocated Elastic IP address\n*/\npublic CompletableFuture allocateAddressAsync() {\nAllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()\n.domain(DomainType.VPC)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().allocateAddress(allocateRequest);\nreturn\nresponseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result,\nex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to allocate address\", ex);\n}\n});\n}\n\u2022 For API details, see AllocateAddress in AWS SDK for Java 2.x API Reference.\nAssociateAddress\nThe following code example shows how to use AssociateAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Associates an Elastic IP address with an EC2 instance asynchronously.\n*\n* @param instanceId the ID of the EC2 instance to associate the Elastic IP\naddress with\n* @param allocationId the allocation ID of the Elastic IP address to associate\n* @return a {@link CompletableFuture} that completes with the association ID\nwhen the operation is successful,\nActions 1032\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* or throws a {@link RuntimeException} if the operation fails\n*/\npublic CompletableFuture associateAddressAsync(String instanceId, String\nallocationId) {\nAssociateAddressRequest associateRequest = AssociateAddressRequest.builder()\n.instanceId(instanceId)\n.allocationId(allocationId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().associateAddress(associateRequest);\nreturn responseFuture.thenApply(response -> {\nif (response.associationId() != null) {\nreturn response.associationId();\n} else {\nthrow new RuntimeException(\"Association ID is null after associating\naddress.\");\n}\n}).whenComplete((result, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to associate address\", ex);\n}\n});\n}\n\u2022 For API details, see AssociateAddress in AWS SDK for Java 2.x API Reference.\nAuthorizeSecurityGroupIngress\nThe following code example shows how to use AuthorizeSecurityGroupIngress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\nActions 1033\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Creates a new security group asynchronously with the specified group name,\ndescription, and VPC ID. It also\n* authorizes inbound traffic on ports 80 and 22 from the specified IP address.", "mimetype": "text/plain", "start_char_idx": 1512197, "end_char_idx": 1515632, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "222216fa-abd2-426d-9177-eaf07b21448f": {"__data__": {"id_": "222216fa-abd2-426d-9177-eaf07b21448f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a97a3b95-f676-40c4-bdbc-685040931765", "node_type": "1", "metadata": {}, "hash": "850f3b0001c84179cf250144a2fbeabb0439819211bb0d7bb5455074e9fcb48c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ae71f509-f2f4-4203-803e-4baf38c35e87", "node_type": "1", "metadata": {}, "hash": "69433555791a16ea89f09717378595555a11aa7e57187b4a945494ee7dc962c6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n}).whenComplete((result, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to associate address\", ex);\n}\n});\n}\n\u2022 For API details, see AssociateAddress in AWS SDK for Java 2.x API Reference.\nAuthorizeSecurityGroupIngress\nThe following code example shows how to use AuthorizeSecurityGroupIngress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\nActions 1033\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Creates a new security group asynchronously with the specified group name,\ndescription, and VPC ID. It also\n* authorizes inbound traffic on ports 80 and 22 from the specified IP address.\n*\n* @param groupName the name of the security group to create\n* @param groupDesc the description of the security group\n* @param vpcId the ID of the VPC in which to create the security group\n* @param myIpAddress the IP address from which to allow inbound traffic (e.g.,\n\"192.168.1.1/0\" to allow traffic from\n* any IP address in the 192.168.1.0/24 subnet)\n* @return a CompletableFuture that, when completed, returns the ID of the\ncreated security group\n* @throws RuntimeException if there was a failure creating the security group\nor authorizing the inbound traffic\n*/\npublic CompletableFuture createSecurityGroupAsync(String groupName,\nString groupDesc, String vpcId, String myIpAddress) {\nCreateSecurityGroupRequest createRequest =\nCreateSecurityGroupRequest.builder()\n.groupName(groupName)\n.description(groupDesc)\n.vpcId(vpcId)\n.build();\nreturn getAsyncClient().createSecurityGroup(createRequest)\n.thenCompose(createResponse -> {\nString groupId = createResponse.groupId();\nIpRange ipRange = IpRange.builder()\n.cidrIp(myIpAddress + \"/32\")\n.build();\nIpPermission ipPerm = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(80)\n.fromPort(80)\n.ipRanges(ipRange)\n.build();\nIpPermission ipPerm2 = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(22)\n.fromPort(22)\n.ipRanges(ipRange)\n.build();\nActions 1034\nAWS SDK for Java 2.x Developer Guide for version 2.x\nAuthorizeSecurityGroupIngressRequest authRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(groupName)\n.ipPermissions(ipPerm, ipPerm2)\n.build();\nreturn getAsyncClient().authorizeSecurityGroupIngress(authRequest)\n.thenApply(authResponse -> groupId);\n})\n.whenComplete((result, exception) -> {\nif (exception != null) {\nif (exception instanceof CompletionException &&\nexception.getCause() instanceof Ec2Exception) {\nthrow (Ec2Exception) exception.getCause();\n} else {\nthrow new RuntimeException(\"Failed to create security group:\n\" + exception.getMessage(), exception);\n}\n}\n});\n}\n\u2022 For API details, see AuthorizeSecurityGroupIngress in AWS SDK for Java 2.x API Reference.\nCreateKeyPair\nThe following code example shows how to use CreateKeyPair.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates a new key pair asynchronously.\n*\nActions 1035\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param keyName the name of the key pair to create\n* @param fileName the name of the file to write the key material to\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of creating the key pair and writing the key material to a file\n*/\npublic CompletableFuture createKeyPairAsync(String\nkeyName, String fileName) {\nCreateKeyPairRequest request = CreateKeyPairRequest.builder()\n.keyName(keyName)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().createKeyPair(request);\nresponseFuture.whenComplete((response, exception) -> {\nif (response != null) {\ntry {\nBufferedWriter writer = new BufferedWriter(new\nFileWriter(fileName));\nwriter.write(response.keyMaterial());\nwriter.close();\n} catch (IOException e) {\nthrow new RuntimeException(\"Failed to write key material to\nfile: \" + e.getMessage(), e);\n}\n} else {\nthrow new RuntimeException(\"Failed to create key pair: \" +\nexception.getMessage(), exception);\n}\n});\nreturn responseFuture;\n}\n\u2022 For API details, see CreateKeyPair in AWS SDK for Java 2.x API Reference.\nCreateSecurityGroup\nThe following code example shows how to use CreateSecurityGroup.\nActions 1036\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1514920, "end_char_idx": 1519301, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ae71f509-f2f4-4203-803e-4baf38c35e87": {"__data__": {"id_": "ae71f509-f2f4-4203-803e-4baf38c35e87", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "222216fa-abd2-426d-9177-eaf07b21448f", "node_type": "1", "metadata": {}, "hash": "abe4fa752644b642199b863955a2ad74a3c9489c33e8c9c4f599befe1aebc636", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fbe50c50-e101-4ead-b036-bd60fce81ad9", "node_type": "1", "metadata": {}, "hash": "f05206d79a93079fbb2238cf100bcdcc75760bb5be6478431f55ea55cbb4f079", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CreateSecurityGroup\nThe following code example shows how to use CreateSecurityGroup.\nActions 1036\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates a new security group asynchronously with the specified group name,\ndescription, and VPC ID. It also\n* authorizes inbound traffic on ports 80 and 22 from the specified IP address.\n*\n* @param groupName the name of the security group to create\n* @param groupDesc the description of the security group\n* @param vpcId the ID of the VPC in which to create the security group\n* @param myIpAddress the IP address from which to allow inbound traffic (e.g.,\n\"192.168.1.1/0\" to allow traffic from\n* any IP address in the 192.168.1.0/24 subnet)\n* @return a CompletableFuture that, when completed, returns the ID of the\ncreated security group\n* @throws RuntimeException if there was a failure creating the security group\nor authorizing the inbound traffic\n*/\npublic CompletableFuture createSecurityGroupAsync(String groupName,\nString groupDesc, String vpcId, String myIpAddress) {\nCreateSecurityGroupRequest createRequest =\nCreateSecurityGroupRequest.builder()\n.groupName(groupName)\n.description(groupDesc)\n.vpcId(vpcId)\n.build();\nreturn getAsyncClient().createSecurityGroup(createRequest)\n.thenCompose(createResponse -> {\nString groupId = createResponse.groupId();\nIpRange ipRange = IpRange.builder()\n.cidrIp(myIpAddress + \"/32\")\n.build();\nIpPermission ipPerm = IpPermission.builder()\n.ipProtocol(\"tcp\")\nActions 1037\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.toPort(80)\n.fromPort(80)\n.ipRanges(ipRange)\n.build();\nIpPermission ipPerm2 = IpPermission.builder()\n.ipProtocol(\"tcp\")\n.toPort(22)\n.fromPort(22)\n.ipRanges(ipRange)\n.build();\nAuthorizeSecurityGroupIngressRequest authRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(groupName)\n.ipPermissions(ipPerm, ipPerm2)\n.build();\nreturn getAsyncClient().authorizeSecurityGroupIngress(authRequest)\n.thenApply(authResponse -> groupId);\n})\n.whenComplete((result, exception) -> {\nif (exception != null) {\nif (exception instanceof CompletionException &&\nexception.getCause() instanceof Ec2Exception) {\nthrow (Ec2Exception) exception.getCause();\n} else {\nthrow new RuntimeException(\"Failed to create security group:\n\" + exception.getMessage(), exception);\n}\n}\n});\n}\n\u2022 For API details, see CreateSecurityGroup in AWS SDK for Java 2.x API Reference.\nDeleteKeyPair\nThe following code example shows how to use DeleteKeyPair.\nActions 1038\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes a key pair asynchronously.\n*\n* @param keyPair the name of the key pair to delete\n* @return a {@link CompletableFuture} that represents the result of the\nasynchronous operation.\n* The {@link CompletableFuture} will complete with a {@link\nDeleteKeyPairResponse} object\n* that provides the result of the key pair deletion operation.\n*/\npublic CompletableFuture deleteKeysAsync(String keyPair)\n{\nDeleteKeyPairRequest request = DeleteKeyPairRequest.builder()\n.keyName(keyPair)\n.build();\n// Initiate the asynchronous request to delete the key pair.\nCompletableFuture response =\ngetAsyncClient().deleteKeyPair(request);\nreturn response.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete key pair: \" + keyPair,\nex);\n} else if (resp == null) {\nthrow new RuntimeException(\"No response received for deleting key\npair: \" + keyPair);\n}\n});\n}\n\u2022 For API details, see DeleteKeyPair in AWS SDK for Java 2.x API Reference.\nActions 1039\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteSecurityGroup\nThe following code example shows how to use DeleteSecurityGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes an EC2 security group asynchronously.", "mimetype": "text/plain", "start_char_idx": 1519105, "end_char_idx": 1523255, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fbe50c50-e101-4ead-b036-bd60fce81ad9": {"__data__": {"id_": "fbe50c50-e101-4ead-b036-bd60fce81ad9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ae71f509-f2f4-4203-803e-4baf38c35e87", "node_type": "1", "metadata": {}, "hash": "69433555791a16ea89f09717378595555a11aa7e57187b4a945494ee7dc962c6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "169414c7-17c4-4f22-8f67-086fafc89663", "node_type": "1", "metadata": {}, "hash": "8cdfd390393b59fae02fc228ac9721534959375c521c98d4ace919d92bc99b69", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CompletableFuture response =\ngetAsyncClient().deleteKeyPair(request);\nreturn response.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete key pair: \" + keyPair,\nex);\n} else if (resp == null) {\nthrow new RuntimeException(\"No response received for deleting key\npair: \" + keyPair);\n}\n});\n}\n\u2022 For API details, see DeleteKeyPair in AWS SDK for Java 2.x API Reference.\nActions 1039\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDeleteSecurityGroup\nThe following code example shows how to use DeleteSecurityGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes an EC2 security group asynchronously.\n*\n* @param groupId the ID of the security group to delete\n* @return a CompletableFuture that completes when the security group is deleted\n*/\npublic CompletableFuture deleteEC2SecGroupAsync(String groupId) {\nDeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()\n.groupId(groupId)\n.build();\nCompletableFuture response =\ngetAsyncClient().deleteSecurityGroup(request);\nreturn response.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to delete security group with Id\n\" + groupId, ex);\n} else if (resp == null) {\nthrow new RuntimeException(\"No response received for deleting\nsecurity group with Id \" + groupId);\n}\n}).thenApply(resp -> null);\n}\n\u2022 For API details, see DeleteSecurityGroup in AWS SDK for Java 2.x API Reference.\nDescribeInstanceTypes\nThe following code example shows how to use DescribeInstanceTypes.\nActions 1040\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously retrieves the instance types available in the current AWS\nregion.\n*

\n* This method uses the AWS SDK's asynchronous API to fetch the available\ninstance types\n* and then processes the response. It logs the memory information, network\ninformation,\n* and instance type for each instance type returned. Additionally, it returns a\n* {@link CompletableFuture} that resolves to the instance type string for the\n\"t2.2xlarge\"\n* instance type, if it is found in the response. If the \"t2.2xlarge\" instance\ntype is not\n* found, an empty string is returned.\n*

\n*\n* @return a {@link CompletableFuture} that resolves to the instance type string\nfor the\n* \"t2.2xlarge\" instance type, or an empty string if the instance type is not\nfound\n*/\npublic CompletableFuture getInstanceTypesAsync() {\nDescribeInstanceTypesRequest typesRequest =\nDescribeInstanceTypesRequest.builder()\n.maxResults(10)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeInstanceTypes(typesRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nList instanceTypes = resp.instanceTypes();\nfor (InstanceTypeInfo type : instanceTypes) {\nActions 1041\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"The memory information of this type is \" +\ntype.memoryInfo().sizeInMiB());\nlogger.info(\"Network information is \" +\ntype.networkInfo().toString());\nlogger.info(\"Instance type is \" +\ntype.instanceType().toString());\n}\n} else {\nthrow (RuntimeException) ex;\n}\n});\nreturn response.thenApply(resp -> {\nfor (InstanceTypeInfo type : resp.instanceTypes()) {\nString instanceType = type.instanceType().toString();\nif (instanceType.equals(\"t2.2xlarge\")) {\nreturn instanceType;\n}\n}\nreturn \"\";\n});\n}\n\u2022 For API details, see DescribeInstanceTypes in AWS SDK for Java 2.x API Reference.\nDescribeInstances\nThe following code example shows how to use DescribeInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously describes an AWS EC2 image with the specified image ID.", "mimetype": "text/plain", "start_char_idx": 1522486, "end_char_idx": 1526506, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "169414c7-17c4-4f22-8f67-086fafc89663": {"__data__": {"id_": "169414c7-17c4-4f22-8f67-086fafc89663", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fbe50c50-e101-4ead-b036-bd60fce81ad9", "node_type": "1", "metadata": {}, "hash": "f05206d79a93079fbb2238cf100bcdcc75760bb5be6478431f55ea55cbb4f079", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2d1ce43c-b23d-4c37-b162-88d69955c814", "node_type": "1", "metadata": {}, "hash": "87c9a1705e2ab50079e4e5f474631b40d71ae08ed1b4070d6530e54f98e4171a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeInstances\nThe following code example shows how to use DescribeInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously describes an AWS EC2 image with the specified image ID.\n*\nActions 1042\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @param imageId the ID of the image to be described\n* @return a {@link CompletableFuture} that, when completed, contains the ID of\nthe described image\n* @throws RuntimeException if no images are found with the provided image ID,\nor if an error occurs during the AWS API call\n*/\npublic CompletableFuture describeImageAsync(String imageId) {\nDescribeImagesRequest imagesRequest = DescribeImagesRequest.builder()\n.imageIds(imageId)\n.build();\nAtomicReference imageIdRef = new AtomicReference<>();\nDescribeImagesPublisher paginator =\ngetAsyncClient().describeImagesPaginator(imagesRequest);\nreturn paginator.subscribe(response -> {\nresponse.images().stream()\n.filter(image -> image.imageId().equals(imageId))\n.findFirst()\n.ifPresent(image -> {\nlogger.info(\"The description of the image is \" +\nimage.description());\nlogger.info(\"The name of the image is \" + image.name());\nimageIdRef.set(image.imageId());\n});\n}).thenApply(v -> {\nString id = imageIdRef.get();\nif (id == null) {\nthrow new RuntimeException(\"No images found with the provided image\nID.\");\n}\nreturn id;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe image: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe image\", ex);\n});\n}\n\u2022 For API details, see DescribeInstances in AWS SDK for Java 2.x API Reference.\nDescribeKeyPairs\nThe following code example shows how to use DescribeKeyPairs.\nActions 1043\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously describes the key pairs associated with the current AWS\naccount.\n*\n* @return a {@link CompletableFuture} containing the {@link\nDescribeKeyPairsResponse} object, which provides\n* information about the key pairs.\n*/\npublic CompletableFuture describeKeysAsync() {\nCompletableFuture responseFuture =\ngetAsyncClient().describeKeyPairs();\nresponseFuture.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to describe key pairs: \" +\nexception.getMessage(), exception);\n}\n});\nreturn responseFuture;\n}\n\u2022 For API details, see DescribeKeyPairs in AWS SDK for Java 2.x API Reference.\nDescribeSecurityGroups\nThe following code example shows how to use DescribeSecurityGroups.\nActions 1044\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously describes the security groups for the specified group ID.\n*\n* @param groupName the name of the security group to describe\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation\n* of describing the security groups. The future will complete with a\n* {@link DescribeSecurityGroupsResponse} object that contains the\n* security group information.\n*/\npublic CompletableFuture describeSecurityGroupArnByNameAsync(String\ngroupName) {\nDescribeSecurityGroupsRequest request =\nDescribeSecurityGroupsRequest.builder()\n.groupNames(groupName)\n.build();\nDescribeSecurityGroupsPublisher paginator =\ngetAsyncClient().describeSecurityGroupsPaginator(request);\nAtomicReference groupIdRef = new AtomicReference<>();\nreturn paginator.subscribe(response -> {\nresponse.securityGroups().stream()\n.filter(securityGroup ->\nsecurityGroup.groupName().equals(groupName))\n.findFirst()\n.ifPresent(securityGroup ->\ngroupIdRef.set(securityGroup.groupId()));\n}).thenApply(v -> {\nString groupId = groupIdRef.get();\nif (groupId == null) {\nthrow new RuntimeException(\"No security group found with the name: \"\n+ groupName);\n}\nActions 1045\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn groupId;\n}).exceptionally(ex -> {\nlogger.info(\"Failed to describe security group: \" + ex.getMessage());\nthrow new RuntimeException(\"Failed to describe security group\", ex);\n});\n}\n\u2022 For API details, see DescribeSecurityGroups in AWS SDK for Java 2.x API Reference.\nDisassociateAddress\nThe following code example shows how to use DisassociateAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Disassociates an Elastic IP address from an instance asynchronously.", "mimetype": "text/plain", "start_char_idx": 1526208, "end_char_idx": 1530950, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2d1ce43c-b23d-4c37-b162-88d69955c814": {"__data__": {"id_": "2d1ce43c-b23d-4c37-b162-88d69955c814", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "169414c7-17c4-4f22-8f67-086fafc89663", "node_type": "1", "metadata": {}, "hash": "8cdfd390393b59fae02fc228ac9721534959375c521c98d4ace919d92bc99b69", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ce5be3b3-5938-4c2c-adb9-c23f925b0bf9", "node_type": "1", "metadata": {}, "hash": "779cd8ff893d7bbf26c018f3794f8d7564cc454ef22c11a63567ab89e172b382", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DisassociateAddress\nThe following code example shows how to use DisassociateAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Disassociates an Elastic IP address from an instance asynchronously.\n*\n* @param associationId The ID of the association you want to disassociate.\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof disassociating the address. The\n* {@link CompletableFuture} will complete with a {@link\nDisassociateAddressResponse} when the operation is\n* finished.\n* @throws RuntimeException if the disassociation of the address fails.\n*/\npublic CompletableFuture\ndisassociateAddressAsync(String associationId) {\nEc2AsyncClient ec2 = getAsyncClient();\nDisassociateAddressRequest addressRequest =\nDisassociateAddressRequest.builder()\n.associationId(associationId)\n.build();\n// Disassociate the address asynchronously.\nActions 1046\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture response =\nec2.disassociateAddress(addressRequest);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to disassociate address\", ex);\n}\n});\nreturn response;\n}\n\u2022 For API details, see DisassociateAddress in AWS SDK for Java 2.x API Reference.\nGetPasswordData\nThe following code example shows how to use GetPasswordData.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ec2.Ec2AsyncClient;\nimport software.amazon.awssdk.services.ec2.model.*;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class GetPasswordData {\npublic static void main(String[] args) {\nActions 1047\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfinal String usage = \"\"\"\nUsage:\n\nWhere:\ninstanceId - An instance id value that you can obtain from the\nAWS Management Console.\\s\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString instanceId = args[0];\nEc2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()\n.region(Region.US_EAST_1)\n.build();\ntry {\nCompletableFuture future = getPasswordDataAsync(ec2AsyncClient,\ninstanceId);\nfuture.join();\n} catch (RuntimeException rte) {\nSystem.err.println(\"An exception occurred: \" + (rte.getCause() != null ?\nrte.getCause().getMessage() : rte.getMessage()));\n}\n}\n/**\n* Fetches the password data for the specified EC2 instance asynchronously.\n*\n* @param ec2AsyncClient the EC2 asynchronous client to use for the request\n* @param instanceId instanceId the ID of the EC2 instance for which you want to\nfetch the password data\n* @return a {@link CompletableFuture} that completes when the password data has\nbeen fetched\n* @throws RuntimeException if there was a failure in fetching the password data\n*/\npublic static CompletableFuture getPasswordDataAsync(Ec2AsyncClient\nec2AsyncClient, String instanceId) {\nGetPasswordDataRequest getPasswordDataRequest =\nGetPasswordDataRequest.builder()\n.instanceId(instanceId)\nActions 1048\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nCompletableFuture response =\nec2AsyncClient.getPasswordData(getPasswordDataRequest);\nresponse.whenComplete((getPasswordDataResponse, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to get password data for\ninstance: \" + instanceId, ex);\n} else if (getPasswordDataResponse == null ||\ngetPasswordDataResponse.passwordData().isEmpty()) {\nthrow new RuntimeException(\"No password data found for instance: \" +\ninstanceId);\n} else {\nString encryptedPasswordData =\ngetPasswordDataResponse.passwordData();\nSystem.out.println(\"Encrypted Password Data: \" +\nencryptedPasswordData);\n}\n});\nreturn response.thenApply(resp -> null);\n}\n}\n\u2022 For API details, see GetPasswordData in AWS SDK for Java 2.x API Reference.\nReleaseAddress\nThe following code example shows how to use ReleaseAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1530650, "end_char_idx": 1535145, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ce5be3b3-5938-4c2c-adb9-c23f925b0bf9": {"__data__": {"id_": "ce5be3b3-5938-4c2c-adb9-c23f925b0bf9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2d1ce43c-b23d-4c37-b162-88d69955c814", "node_type": "1", "metadata": {}, "hash": "87c9a1705e2ab50079e4e5f474631b40d71ae08ed1b4070d6530e54f98e4171a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dfd935ad-6d18-4487-90e2-755c9662650a", "node_type": "1", "metadata": {}, "hash": "cbbe8a6e9b366af0b8e8e843ffd371248f1bd26835686bd8c569ced74fe85f7e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ReleaseAddress\nThe following code example shows how to use ReleaseAddress.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\nActions 1049\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Releases an Elastic IP address asynchronously.\n*\n* @param allocId the allocation ID of the Elastic IP address to be released\n* @return a {@link CompletableFuture} representing the asynchronous operation\nof releasing the Elastic IP address\n*/\npublic CompletableFuture releaseEC2AddressAsync(String\nallocId) {\nReleaseAddressRequest request = ReleaseAddressRequest.builder()\n.allocationId(allocId)\n.build();\nCompletableFuture response =\ngetAsyncClient().releaseAddress(request);\nresponse.whenComplete((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to release Elastic IP address\",\nex);\n}\n});\nreturn response;\n}\n\u2022 For API details, see ReleaseAddress in AWS SDK for Java 2.x API Reference.\nRunInstances\nThe following code example shows how to use RunInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Runs an EC2 instance asynchronously.\nActions 1050\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* @param instanceType The instance type to use for the EC2 instance.\n* @param keyName The name of the key pair to associate with the EC2 instance.\n* @param groupName The name of the security group to associate with the EC2\ninstance.\n* @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2\ninstance.\n* @return A {@link CompletableFuture} that completes with the ID of the started\nEC2 instance.\n* @throws RuntimeException If there is an error running the EC2 instance.\n*/\npublic CompletableFuture runInstanceAsync(String instanceType, String\nkeyName, String groupName, String amiId) {\nRunInstancesRequest runRequest = RunInstancesRequest.builder()\n.instanceType(instanceType)\n.keyName(keyName)\n.securityGroups(groupName)\n.maxCount(1)\n.minCount(1)\n.imageId(amiId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().runInstances(runRequest);\nreturn responseFuture.thenCompose(response -> {\nString instanceIdVal = response.instances().get(0).instanceId();\nSystem.out.println(\"Going to start an EC2 instance and use a waiter to\nwait for it to be in running state\");\nreturn getAsyncClient().waiter()\n.waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal))\n.thenCompose(waitResponse -> getAsyncClient().waiter()\n.waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal))\n.thenApply(runningResponse -> instanceIdVal));\n}).exceptionally(throwable -> {\n// Handle any exceptions that occurred during the async call\nthrow new RuntimeException(\"Failed to run EC2 instance: \" +\nthrowable.getMessage(), throwable);\n});\n}\n\u2022 For API details, see RunInstances in AWS SDK for Java 2.x API Reference.\nActions 1051\nAWS SDK for Java 2.x Developer Guide for version 2.x\nStartInstances\nThe following code example shows how to use StartInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Starts an Amazon EC2 instance asynchronously and waits until it is in the\n\"running\" state.\n*\n* @param instanceId the ID of the instance to start\n* @return a {@link CompletableFuture} that completes when the instance has been\nstarted and is in the \"running\" state, or exceptionally if an error occurs\n*/\npublic CompletableFuture startInstanceAsync(String instanceId) {\nStartInstancesRequest startRequest = StartInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nEc2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()\n.client(getAsyncClient())\n.build();\nDescribeInstancesRequest describeRequest =\nDescribeInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nlogger.info(\"Starting instance \" + instanceId + \" and waiting for it to\nrun.", "mimetype": "text/plain", "start_char_idx": 1534930, "end_char_idx": 1538984, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "dfd935ad-6d18-4487-90e2-755c9662650a": {"__data__": {"id_": "dfd935ad-6d18-4487-90e2-755c9662650a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ce5be3b3-5938-4c2c-adb9-c23f925b0bf9", "node_type": "1", "metadata": {}, "hash": "779cd8ff893d7bbf26c018f3794f8d7564cc454ef22c11a63567ab89e172b382", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f9c264e6-adae-4ec9-9862-e66d315d4464", "node_type": "1", "metadata": {}, "hash": "437b6ff7c9a43a03b443c47a7056aaa8925d03dbf0c0627b7ad9dc9ea9d60d8c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Starts an Amazon EC2 instance asynchronously and waits until it is in the\n\"running\" state.\n*\n* @param instanceId the ID of the instance to start\n* @return a {@link CompletableFuture} that completes when the instance has been\nstarted and is in the \"running\" state, or exceptionally if an error occurs\n*/\npublic CompletableFuture startInstanceAsync(String instanceId) {\nStartInstancesRequest startRequest = StartInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nEc2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()\n.client(getAsyncClient())\n.build();\nDescribeInstancesRequest describeRequest =\nDescribeInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nlogger.info(\"Starting instance \" + instanceId + \" and waiting for it to\nrun.\");\nCompletableFuture resultFuture = new CompletableFuture<>();\nreturn getAsyncClient().startInstances(startRequest)\n.thenCompose(response ->\nec2Waiter.waitUntilInstanceRunning(describeRequest)\n)\n.thenAccept(waiterResponse -> {\nlogger.info(\"Successfully started instance \" + instanceId);\nActions 1052\nAWS SDK for Java 2.x Developer Guide for version 2.x\nresultFuture.complete(null);\n})\n.exceptionally(throwable -> {\nresultFuture.completeExceptionally(new RuntimeException(\"Failed to\nstart instance: \" + throwable.getMessage(), throwable));\nreturn null;\n});\n}\n\u2022 For API details, see StartInstances in AWS SDK for Java 2.x API Reference.\nStopInstances\nThe following code example shows how to use StopInstances.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Stops the EC2 instance with the specified ID asynchronously and waits for the\ninstance to stop.\n*\n* @param instanceId the ID of the EC2 instance to stop\n* @return a {@link CompletableFuture} that completes when the instance has been\nstopped, or exceptionally if an error occurs\n*/\npublic CompletableFuture stopInstanceAsync(String instanceId) {\nStopInstancesRequest stopRequest = StopInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nDescribeInstancesRequest describeRequest =\nDescribeInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nActions 1053\nAWS SDK for Java 2.x Developer Guide for version 2.x\nEc2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()\n.client(getAsyncClient())\n.build();\nCompletableFuture resultFuture = new CompletableFuture<>();\nlogger.info(\"Stopping instance \" + instanceId + \" and waiting for it to\nstop.\");\ngetAsyncClient().stopInstances(stopRequest)\n.thenCompose(response -> {\nif (response.stoppingInstances().isEmpty()) {\nreturn CompletableFuture.failedFuture(new RuntimeException(\"No\ninstances were stopped. Please check the instance ID: \" + instanceId));\n}\nreturn ec2Waiter.waitUntilInstanceStopped(describeRequest);\n})\n.thenAccept(waiterResponse -> {\nlogger.info(\"Successfully stopped instance \" + instanceId);\nresultFuture.complete(null);\n})\n.exceptionally(throwable -> {\nlogger.error(\"Failed to stop instance \" + instanceId + \": \" +\nthrowable.getMessage(), throwable);\nresultFuture.completeExceptionally(new RuntimeException(\"Failed to\nstop instance: \" + throwable.getMessage(), throwable));\nreturn null;\n});\nreturn resultFuture;\n}\n\u2022 For API details, see StopInstances in AWS SDK for Java 2.x API Reference.\nTerminateInstances\nThe following code example shows how to use TerminateInstances.\nActions 1054\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Terminates an EC2 instance asynchronously and waits for it to reach the\nterminated state.", "mimetype": "text/plain", "start_char_idx": 1538082, "end_char_idx": 1541905, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f9c264e6-adae-4ec9-9862-e66d315d4464": {"__data__": {"id_": "f9c264e6-adae-4ec9-9862-e66d315d4464", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dfd935ad-6d18-4487-90e2-755c9662650a", "node_type": "1", "metadata": {}, "hash": "cbbe8a6e9b366af0b8e8e843ffd371248f1bd26835686bd8c569ced74fe85f7e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "36629fb8-d963-4eef-90d1-e0790f676d74", "node_type": "1", "metadata": {}, "hash": "4a34fca4790138bb32aaa5dee04be5582ca8cedbf1bed8c8cd4b510d86d10e64", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "TerminateInstances\nThe following code example shows how to use TerminateInstances.\nActions 1054\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Terminates an EC2 instance asynchronously and waits for it to reach the\nterminated state.\n*\n* @param instanceId the ID of the EC2 instance to terminate\n* @return a {@link CompletableFuture} that completes when the instance has been\nterminated\n* @throws RuntimeException if there is no response from the AWS SDK or if there\nis a failure during the termination process\n*/\npublic CompletableFuture terminateEC2Async(String instanceId) {\nTerminateInstancesRequest terminateRequest =\nTerminateInstancesRequest.builder()\n.instanceIds(instanceId)\n.build();\nCompletableFuture responseFuture =\ngetAsyncClient().terminateInstances(terminateRequest);\nreturn responseFuture.thenCompose(terminateResponse -> {\nif (terminateResponse == null) {\nthrow new RuntimeException(\"No response received for terminating\ninstance \" + instanceId);\n}\nSystem.out.println(\"Going to terminate an EC2 instance and use a waiter\nto wait for it to be in terminated state\");\nreturn getAsyncClient().waiter()\n.waitUntilInstanceTerminated(r -> r.instanceIds(instanceId))\n.thenApply(waiterResponse -> null);\n}).exceptionally(throwable -> {\n// Handle any exceptions that occurred during the async call\nthrow new RuntimeException(\"Failed to terminate EC2 instance: \" +\nthrowable.getMessage(), throwable);\n});\n}\nActions 1055\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see TerminateInstances in AWS SDK for Java 2.x API Reference.\nScenarios\nBuild and manage a resilient service\nThe following code example shows how to create a load-balanced web service that returns book,\nmovie, and song recommendations. The example shows how the service responds to failures, and\nhow to restructure the service for more resilience when failures occur.\n\u2022 Use an Amazon EC2 Auto Scaling group to create Amazon Elastic Compute Cloud (Amazon EC2)\ninstances based on a launch template and to keep the number of instances in a specified range.\n\u2022 Handle and distribute HTTP requests with Elastic Load Balancing.\n\u2022 Monitor the health of instances in an Auto Scaling group and forward requests only to healthy\ninstances.\n\u2022 Run a Python web server on each EC2 instance to handle HTTP requests. The web server\nresponds with recommendations and health checks.\n\u2022 Simulate a recommendation service with an Amazon DynamoDB table.\n\u2022 Control web server response to requests and health checks by updating AWS Systems Manager\nparameters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.\npublic static final String tableName = \"doc-example-recommendation-service\";\nScenarios 1056\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static final String startScript = \"C:\\\\AWS\\\\resworkflow\\\n\\server_startup_script.sh\"; // Modify file location.\npublic static final String policyFile = \"C:\\\\AWS\\\\resworkflow\\\n\\instance_policy.json\"; // Modify file location.\npublic static final String ssmJSON = \"C:\\\\AWS\\\\resworkflow\\\n\\ssm_only_policy.json\"; // Modify file location.", "mimetype": "text/plain", "start_char_idx": 1541520, "end_char_idx": 1545045, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "36629fb8-d963-4eef-90d1-e0790f676d74": {"__data__": {"id_": "36629fb8-d963-4eef-90d1-e0790f676d74", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f9c264e6-adae-4ec9-9862-e66d315d4464", "node_type": "1", "metadata": {}, "hash": "437b6ff7c9a43a03b443c47a7056aaa8925d03dbf0c0627b7ad9dc9ea9d60d8c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7bd72be9-7db4-48dd-b3c6-59268a6f9c01", "node_type": "1", "metadata": {}, "hash": "5c399d408bfa1eed1e0fc0b4c23287be36ac4ffbbbd2af0ccbf73001383065d3", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.\npublic static final String tableName = \"doc-example-recommendation-service\";\nScenarios 1056\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static final String startScript = \"C:\\\\AWS\\\\resworkflow\\\n\\server_startup_script.sh\"; // Modify file location.\npublic static final String policyFile = \"C:\\\\AWS\\\\resworkflow\\\n\\instance_policy.json\"; // Modify file location.\npublic static final String ssmJSON = \"C:\\\\AWS\\\\resworkflow\\\n\\ssm_only_policy.json\"; // Modify file location.\npublic static final String failureResponse = \"doc-example-resilient-\narchitecture-failure-response\";\npublic static final String healthCheck = \"doc-example-resilient-architecture-\nhealth-check\";\npublic static final String templateName = \"doc-example-resilience-template\";\npublic static final String roleName = \"doc-example-resilience-role\";\npublic static final String policyName = \"doc-example-resilience-pol\";\npublic static final String profileName = \"doc-example-resilience-prof\";\npublic static final String badCredsProfileName = \"doc-example-resilience-prof-\nbc\";\npublic static final String targetGroupName = \"doc-example-resilience-tg\";\npublic static final String autoScalingGroupName = \"doc-example-resilience-\ngroup\";\npublic static final String lbName = \"doc-example-resilience-lb\";\npublic static final String protocol = \"HTTP\";\npublic static final int port = 80;\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws IOException, InterruptedException\n{\nScanner in = new Scanner(System.in);\nDatabase database = new Database();\nAutoScaler autoScaler = new AutoScaler();\nLoadBalancer loadBalancer = new LoadBalancer();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the demonstration of How to Build and Manage\na Resilient Service!\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"A - SETUP THE RESOURCES\");\nSystem.out.println(\"Press Enter when you're ready to start deploying\nresources.\");\nin.nextLine();\nScenarios 1057\nAWS SDK for Java 2.x Developer Guide for version 2.x\ndeploy(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"B - DEMO THE RESILIENCE FUNCTIONALITY\");\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\ndemo(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"C - DELETE THE RESOURCES\");\nSystem.out.println(\"\"\"\nThis concludes the demo of how to build and manage a resilient\nservice.\nTo keep things tidy and to avoid unwanted charges on your account,\nwe can clean up all AWS resources\nthat were created for this demo.\n\"\"\");\nSystem.out.println(\"\\n Do you want to delete the resources (y/n)? \");\nString userInput = in.nextLine().trim().toLowerCase(); // Capture user input\nif (userInput.equals(\"y\")) {\n// Delete resources here\ndeleteResources(loadBalancer, autoScaler, database);\nSystem.out.println(\"Resources deleted.\");\n} else {\nSystem.out.println(\"\"\"\nOkay, we'll leave the resources intact.\nDon't forget to delete them when you're done with them or you\nmight incur unexpected charges.\n\"\"\");\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The example has completed. \");\nSystem.out.println(\"\\n Thanks for watching!\");\nSystem.out.println(DASHES);\n}\n// Deletes the AWS resources used in this example.\nprivate static void deleteResources(LoadBalancer loadBalancer, AutoScaler\nautoScaler, Database database)\nScenarios 1058\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrows IOException, InterruptedException {\nloadBalancer.deleteLoadBalancer(lbName);\nSystem.out.println(\"*** Wait 30 secs for resource to be deleted\");\nTimeUnit.SECONDS.sleep(30);\nloadBalancer.deleteTargetGroup(targetGroupName);\nautoScaler.deleteAutoScaleGroup(autoScalingGroupName);\nautoScaler.deleteRolesPolicies(policyName, roleName, profileName);\nautoScaler.deleteTemplate(templateName);\ndatabase.deleteTable(tableName);\n}\nprivate static void deploy(LoadBalancer loadBalancer) throws\nInterruptedException, IOException {\nScanner in = new Scanner(System.in);\nSystem.out.println(\n\"\"\"\nFor this demo, we'll use the AWS SDK for Java (v2) to create\nseveral AWS resources\nto set up a load-balanced web service endpoint and explore\nsome ways to make it resilient\nagainst various kinds of failures.", "mimetype": "text/plain", "start_char_idx": 1544242, "end_char_idx": 1548874, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7bd72be9-7db4-48dd-b3c6-59268a6f9c01": {"__data__": {"id_": "7bd72be9-7db4-48dd-b3c6-59268a6f9c01", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "36629fb8-d963-4eef-90d1-e0790f676d74", "node_type": "1", "metadata": {}, "hash": "4a34fca4790138bb32aaa5dee04be5582ca8cedbf1bed8c8cd4b510d86d10e64", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ef37754c-2af3-4fab-bace-b174b3ebee98", "node_type": "1", "metadata": {}, "hash": "d5e90886bac7127b01343fc5a3975ab897e85a39967a2968cd5991ffe2fe8e48", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "private static void deleteResources(LoadBalancer loadBalancer, AutoScaler\nautoScaler, Database database)\nScenarios 1058\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthrows IOException, InterruptedException {\nloadBalancer.deleteLoadBalancer(lbName);\nSystem.out.println(\"*** Wait 30 secs for resource to be deleted\");\nTimeUnit.SECONDS.sleep(30);\nloadBalancer.deleteTargetGroup(targetGroupName);\nautoScaler.deleteAutoScaleGroup(autoScalingGroupName);\nautoScaler.deleteRolesPolicies(policyName, roleName, profileName);\nautoScaler.deleteTemplate(templateName);\ndatabase.deleteTable(tableName);\n}\nprivate static void deploy(LoadBalancer loadBalancer) throws\nInterruptedException, IOException {\nScanner in = new Scanner(System.in);\nSystem.out.println(\n\"\"\"\nFor this demo, we'll use the AWS SDK for Java (v2) to create\nseveral AWS resources\nto set up a load-balanced web service endpoint and explore\nsome ways to make it resilient\nagainst various kinds of failures.\nSome of the resources create by this demo are:\n\\t* A DynamoDB table that the web service depends on to\nprovide book, movie, and song recommendations.\n\\t* An EC2 launch template that defines EC2 instances that\neach contain a Python web server.\n\\t* An EC2 Auto Scaling group that manages EC2 instances\nacross several Availability Zones.\n\\t* An Elastic Load Balancing (ELB) load balancer that\ntargets the Auto Scaling group to distribute requests.\n\"\"\");\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating and populating a DynamoDB table named \" +\ntableName);\nDatabase database = new Database();\ndatabase.createTable(tableName, fileName);\nSystem.out.println(DASHES);\nScenarios 1059\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an EC2 launch template that runs '{startup_script}' when an\ninstance starts.\nThis script starts a Python web server defined in the `server.py`\nscript. The web server\nlistens to HTTP requests on port 80 and responds to requests to '/'\nand to '/healthcheck'.\nFor demo purposes, this server is run as the root user. In\nproduction, the best practice is to\nrun a web server, such as Apache, with least-privileged credentials.\nThe template also defines an IAM policy that each instance uses to\nassume a role that grants\npermissions to access the DynamoDB recommendation table and Systems\nManager parameters\nthat control the flow of the demo.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\ntemplateCreator.createTemplate(policyFile, policyName, profileName,\nstartScript, templateName, roleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\n\"Creating an EC2 Auto Scaling group that maintains three EC2\ninstances, each in a different Availability Zone.\");\nSystem.out.println(\"*** Wait 30 secs for the VPC to be created\");\nTimeUnit.SECONDS.sleep(30);\nAutoScaler autoScaler = new AutoScaler();\nString[] zones = autoScaler.createGroup(3, templateName,\nautoScalingGroupName);\nSystem.out.println(\"\"\"\nAt this point, you have EC2 instances created. Once each instance\nstarts, it listens for\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nScenarios 1060\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances. The load\nbalancer provides a\nsingle endpoint where clients connect and dispatches requests to\ninstances in the group.", "mimetype": "text/plain", "start_char_idx": 1547910, "end_char_idx": 1551861, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ef37754c-2af3-4fab-bace-b174b3ebee98": {"__data__": {"id_": "ef37754c-2af3-4fab-bace-b174b3ebee98", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7bd72be9-7db4-48dd-b3c6-59268a6f9c01", "node_type": "1", "metadata": {}, "hash": "5c399d408bfa1eed1e0fc0b4c23287be36ac4ffbbbd2af0ccbf73001383065d3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fa046099-e812-4e4d-8c35-5143c9caca45", "node_type": "1", "metadata": {}, "hash": "32301d9281702e70d8d762b1281b49dcdc9138b31271e9eab5188699667deb66", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Once each instance\nstarts, it listens for\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nScenarios 1060\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances. The load\nbalancer provides a\nsingle endpoint where clients connect and dispatches requests to\ninstances in the group.\n\"\"\");\nString vpcId = autoScaler.getDefaultVPC();\nList subnets = autoScaler.getSubnets(vpcId, zones);\nSystem.out.println(\"You have retrieved a list with \" + subnets.size() + \"\nsubnets\");\nString targetGroupArn = loadBalancer.createTargetGroup(protocol, port,\nvpcId, targetGroupName);\nString elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn,\nlbName, port, protocol);\nautoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName,\ntargetGroupArn);\nSystem.out.println(\"Verifying access to the load balancer endpoint...\");\nboolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);\nif (!wasSuccessul) {\nSystem.out.println(\"Couldn't connect to the load balancer, verifying\nthat the port is open...\");\nCloseableHttpClient httpClient = HttpClients.createDefault();\n// Create an HTTP GET request to \"http://checkip.amazonaws.com\"\nHttpGet httpGet = new HttpGet(\"http://checkip.amazonaws.com\");\ntry {\n// Execute the request and get the response\nHttpResponse response = httpClient.execute(httpGet);\n// Read the response content.\nString ipAddress =\nIOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();\nScenarios 1061\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Print the public IP address.\nSystem.out.println(\"Public IP Address: \" + ipAddress);\nGroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port,\nipAddress);\nif (!groupInfo.isPortOpen()) {\nSystem.out.println(\"\"\"\nFor this example to work, the default security group for\nyour default VPC must\nallow access from this computer. You can either add it\nautomatically from this\nexample or add it yourself using the AWS Management\nConsole.\n\"\"\");\nSystem.out.println(\n\"Do you want to add a rule to security group \" +\ngroupInfo.getGroupName() + \" to allow\");\nSystem.out.println(\"inbound traffic on port \" + port + \" from\nyour computer's IP address (y/n) \");\nString ans = in.nextLine();\nif (\"y\".equalsIgnoreCase(ans)) {\nautoScaler.openInboundPort(groupInfo.getGroupName(),\nString.valueOf(port), ipAddress);\nSystem.out.println(\"Security group rule added.\");\n} else {\nSystem.out.println(\"No security group rule added.\");\n}\n}\n} catch (AutoScalingException e) {\ne.printStackTrace();\n}\n} else if (wasSuccessul) {\nSystem.out.println(\"Your load balancer is ready. You can access it by\nbrowsing to:\");\nSystem.out.println(\"\\t http://\" + elbDnsName);\n} else {\nSystem.out.println(\"Couldn't get a successful response from the load\nbalancer endpoint. Troubleshoot by\");\nSystem.out.println(\"manually verifying that your VPC and security group\nare configured correctly and that\");\nSystem.out.println(\"you can successfully make a GET request to the load\nbalancer.\");\n}\nScenarios 1062\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Press Enter when you're ready to continue with the\ndemo.\");\nin.nextLine();\n}\n// A method that controls the demo part of the Java program.\npublic static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.", "mimetype": "text/plain", "start_char_idx": 1551062, "end_char_idx": 1555634, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fa046099-e812-4e4d-8c35-5143c9caca45": {"__data__": {"id_": "fa046099-e812-4e4d-8c35-5143c9caca45", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ef37754c-2af3-4fab-bace-b174b3ebee98", "node_type": "1", "metadata": {}, "hash": "d5e90886bac7127b01343fc5a3975ab897e85a39967a2968cd5991ffe2fe8e48", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e0d019d7-cc07-4e51-a797-ba7c9d08bc06", "node_type": "1", "metadata": {}, "hash": "257a008bf302d10e5a4d50d207ab12091287a81dac6840c28c33cfbc3a34891e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nin.nextLine();\n}\n// A method that controls the demo part of the Java program.\npublic static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.\nThe table name is contained in a Systems Manager parameter\nnamed self.param_helper.table.\nTo simulate a failure of the recommendation service, let's\nset this parameter to name a non-existent table.\n\"\"\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\nSystem.out.println(\n\"\"\"\nScenarios 1063\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\\nNow, sending a GET request to the load balancer endpoint\nreturns a failure code. But, the service reports as\nhealthy to the load balancer because shallow health checks\ndon't check for failure of the recommendation service.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nInstead of failing when the recommendation service fails,\nthe web service can return a static response.\nWhile this is not a perfect solution, it presents the\ncustomer with a somewhat better experience than failure.\n\"\"\");\nparamHelper.put(paramHelper.failureResponse, \"static\");\nSystem.out.println(\"\"\"\nNow, sending a GET request to the load balancer endpoint returns a\nstatic response.\nThe service still reports as healthy because health checks are still\nshallow.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"Let's reinstate the recommendation service.\");\nparamHelper.put(paramHelper.tableName, paramHelper.dyntable);\nSystem.out.println(\"\"\"\nLet's also substitute bad credentials for one of the instances in\nthe target group so that it can't\naccess the DynamoDB recommendation table. We will get an instance id\nvalue.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\nAutoScaler autoScaler = new AutoScaler();\n// Create a new instance profile based on badCredsProfileName.\ntemplateCreator.createInstanceProfile(policyFile, policyName,\nbadCredsProfileName, roleName);\nString badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);\nSystem.out.println(\"The bad instance id values used for this demo is \" +\nbadInstanceId);\nScenarios 1064\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);\nSystem.out.println(\"The association Id value is \" + profileAssociationId);\nSystem.out.println(\"Replacing the profile for instance \" + badInstanceId\n+ \" with a profile that contains bad credentials\");\nautoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName,\nprofileAssociationId);\nSystem.out.println(\n\"\"\"\nNow, sending a GET request to the load balancer endpoint\nreturns either a recommendation or a static response,\ndepending on which instance is selected by the load\nbalancer.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"\"\"\nLet's implement a deep health check. For this demo, a deep health\ncheck tests whether\nthe web service can access the DynamoDB table that it depends on for\nrecommendations. Note that\nthe deep health check is only for ELB routing and not for Auto\nScaling instance health.\nThis kind of deep health check is not recommended for Auto Scaling\ninstance health, because it\nrisks accidental termination of all instances in the Auto Scaling\ngroup when a dependent service fails.\n\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\nScenarios 1065\nAWS SDK for Java 2.x Developer Guide for version 2.x\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.", "mimetype": "text/plain", "start_char_idx": 1554683, "end_char_idx": 1559355, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e0d019d7-cc07-4e51-a797-ba7c9d08bc06": {"__data__": {"id_": "e0d019d7-cc07-4e51-a797-ba7c9d08bc06", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fa046099-e812-4e4d-8c35-5143c9caca45", "node_type": "1", "metadata": {}, "hash": "32301d9281702e70d8d762b1281b49dcdc9138b31271e9eab5188699667deb66", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2f927671-bdbc-485b-8ca7-e32020558d4a", "node_type": "1", "metadata": {}, "hash": "33a864a4595be6d5ca5d2144d80756eb10e2c892d802e8800627b7363a567114", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This kind of deep health check is not recommended for Auto Scaling\ninstance health, because it\nrisks accidental termination of all instances in the Auto Scaling\ngroup when a dependent service fails.\n\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\nScenarios 1065\nAWS SDK for Java 2.x Developer Guide for version 2.x\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nBecause the instances in this demo are controlled by an auto\nscaler, the simplest way to fix an unhealthy\ninstance is to terminate it and let the auto scaler start a\nnew instance to replace it.\n\"\"\");\nautoScaler.terminateInstance(badInstanceId);\nSystem.out.println(\"\"\"\nEven while the instance is terminating and the new instance is\nstarting, sending a GET\nrequest to the web service continues to get a successful\nrecommendation response because\nthe load balancer routes requests to the healthy instances. After\nthe replacement instance\nstarts and reports as healthy, it is included in the load balancing\nrotation.\nNote that terminating and replacing an instance typically takes\nseveral minutes, during which time you\ncan see the changing health check status until the new instance is\nrunning and healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"If the recommendation service fails now, deep health checks mean\nall instances report as unhealthy.\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\ndemoChoices(loadBalancer);\nparamHelper.reset();\n}\npublic static void demoChoices(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nString[] actions = {\nScenarios 1066\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"Send a GET request to the load balancer endpoint.\",\n\"Check the health of load balancer targets.\",\n\"Go to the next part of the demo.\"\n};\nScanner scanner = new Scanner(System.in);\nwhile (true) {\nSystem.out.println(\"-\".repeat(88));\nSystem.out.println(\"See the current state of the service by selecting\none of the following choices:\");\nfor (int i = 0; i < actions.length; i++) {\nSystem.out.println(i + \": \" + actions[i]);\n}\ntry {\nSystem.out.print(\"\\nWhich action would you like to take? \");\nint choice = scanner.nextInt();\nSystem.out.println(\"-\".repeat(88));\nswitch (choice) {\ncase 0 -> {\nSystem.out.println(\"Request:\\n\");\nSystem.out.println(\"GET http://\" +\nloadBalancer.getEndpoint(lbName));\nCloseableHttpClient httpClient =\nHttpClients.createDefault();\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" +\nloadBalancer.getEndpoint(lbName));\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\n// Display the JSON response\nBufferedReader reader = new BufferedReader(\nnew\nInputStreamReader(response.getEntity().getContent()));\nStringBuilder jsonResponse = new StringBuilder();\nString line;\nwhile ((line = reader.readLine()) != null) {\njsonResponse.append(line);\nScenarios 1067\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nreader.close();\n// Print the formatted JSON response.\nSystem.out.println(\"Full Response:\\n\");\nSystem.out.println(jsonResponse.toString());\n// Close the HTTP client.\nhttpClient.close();\n}\ncase 1 -> {\nSystem.out.println(\"\\nChecking the health of load balancer\ntargets:\\n\");\nList health =\nloadBalancer.checkTargetHealth(targetGroupName);\nfor (TargetHealthDescription target : health) {\nSystem.out.printf(\"\\tTarget %s on port %d is %s%n\",\ntarget.target().id(),\ntarget.target().port(),\ntarget.targetHealth().stateAsString());\n}\nSystem.out.println(\"\"\"\nNote that it can take a minute or two for the health\ncheck to update\nafter changes are made.\n\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nSystem.out.println(\"Invalid input. Please select again.\");\nscanner.nextLine(); // Clear the input buffer.\n}", "mimetype": "text/plain", "start_char_idx": 1558494, "end_char_idx": 1563157, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2f927671-bdbc-485b-8ca7-e32020558d4a": {"__data__": {"id_": "2f927671-bdbc-485b-8ca7-e32020558d4a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e0d019d7-cc07-4e51-a797-ba7c9d08bc06", "node_type": "1", "metadata": {}, "hash": "257a008bf302d10e5a4d50d207ab12091287a81dac6840c28c33cfbc3a34891e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9110a870-98a8-4c39-bbd9-cd1f9df9ebcd", "node_type": "1", "metadata": {}, "hash": "ebc3bf165d30d66b700ec6c032a76eafab42ed619f388b4c10f7cb2dd30c25b0", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nSystem.out.println(\"Invalid input. Please select again.\");\nscanner.nextLine(); // Clear the input buffer.\n}\n}\n}\nScenarios 1068\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static String readFileAsString(String filePath) throws IOException {\nbyte[] bytes = Files.readAllBytes(Paths.get(filePath));\nreturn new String(bytes);\n}\n}\nCreate a class that wraps Auto Scaling and Amazon EC2 actions.\npublic class AutoScaler {\nprivate static Ec2Client ec2Client;\nprivate static AutoScalingClient autoScalingClient;\nprivate static IamClient iamClient;\nprivate static SsmClient ssmClient;\nprivate IamClient getIAMClient() {\nif (iamClient == null) {\niamClient = IamClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn iamClient;\n}\nprivate SsmClient getSSMClient() {\nif (ssmClient == null) {\nssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ssmClient;\n}\nprivate Ec2Client getEc2Client() {\nif (ec2Client == null) {\nec2Client = Ec2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ec2Client;\n}\nScenarios 1069\nAWS SDK for Java 2.x Developer Guide for version 2.x\nprivate AutoScalingClient getAutoScalingClient() {\nif (autoScalingClient == null) {\nautoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn autoScalingClient;\n}\n/**\n* Terminates and instances in an EC2 Auto Scaling group. After an instance is\n* terminated, it can no longer be accessed.\n*/\npublic void terminateInstance(String instanceId) {\nTerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest =\nTerminateInstanceInAutoScalingGroupRequest\n.builder()\n.instanceId(instanceId)\n.shouldDecrementDesiredCapacity(false)\n.build();\ngetAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);\nSystem.out.format(\"Terminated instance %s.\", instanceId);\n}\n/**\n* Replaces the profile associated with a running instance. After the profile is\n* replaced, the instance is rebooted to ensure that it uses the new profile.\n* When\n* the instance is ready, Systems Manager is used to restart the Python web\n* server.\n*/\npublic void replaceInstanceProfile(String instanceId, String\nnewInstanceProfileName, String profileAssociationId)\nthrows InterruptedException {\n// Create an IAM instance profile specification.\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\niamInstanceProfile =\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\n.builder()\n.name(newInstanceProfileName) // Make sure 'newInstanceProfileName'\nis a valid IAM Instance Profile\nScenarios 1070\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// name.\n.build();\n// Replace the IAM instance profile association for the EC2 instance.\nReplaceIamInstanceProfileAssociationRequest replaceRequest =\nReplaceIamInstanceProfileAssociationRequest\n.builder()\n.iamInstanceProfile(iamInstanceProfile)\n.associationId(profileAssociationId) // Make sure\n'profileAssociationId' is a valid association ID.\n.build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.", "mimetype": "text/plain", "start_char_idx": 1562761, "end_char_idx": 1566727, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9110a870-98a8-4c39-bbd9-cd1f9df9ebcd": {"__data__": {"id_": "9110a870-98a8-4c39-bbd9-cd1f9df9ebcd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2f927671-bdbc-485b-8ca7-e32020558d4a", "node_type": "1", "metadata": {}, "hash": "33a864a4595be6d5ca5d2144d80756eb10e2c892d802e8800627b7363a567114", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9e725470-42e9-4f16-a3d3-fd748753387c", "node_type": "1", "metadata": {}, "hash": "87989ac9d84b2731624e011b30fa955495eabf51bce40c9eb8f9b12ce77a9bd2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.\");\n}\ntries++;\ntry {\nTimeUnit.SECONDS.sleep(10);\n} catch (InterruptedException e) {\ne.printStackTrace();\n}\nDescribeInstanceInformationResponse informationResponse =\ngetSSMClient().describeInstanceInformation();\nScenarios 1071\nAWS SDK for Java 2.x Developer Guide for version 2.x\nList instanceInformationList =\ninformationResponse.instanceInformationList();\nfor (InstanceInformation info : instanceInformationList) {\nif (info.instanceId().equals(instanceId)) {\ninstReady = true;\nbreak;\n}\n}\n}\nSendCommandRequest sendCommandRequest = SendCommandRequest.builder()\n.instanceIds(instanceId)\n.documentName(\"AWS-RunShellScript\")\n.parameters(Collections.singletonMap(\"commands\",\nCollections.singletonList(\"cd / && sudo python3 server.py\n80\")))\n.build();\ngetSSMClient().sendCommand(sendCommandRequest);\nSystem.out.println(\"Restarted the Python web server on instance \" +\ninstanceId + \".\");\n}\npublic void openInboundPort(String secGroupId, String port, String ipAddress) {\nAuthorizeSecurityGroupIngressRequest ingressRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(secGroupId)\n.cidrIp(ipAddress)\n.fromPort(Integer.parseInt(port))\n.build();\ngetEc2Client().authorizeSecurityGroupIngress(ingressRequest);\nSystem.out.format(\"Authorized ingress to %s on port %s from %s.\",\nsecGroupId, port, ipAddress);\n}\n/**\n* Detaches a role from an instance profile, detaches policies from the role,\n* and deletes all the resources.\n*/\npublic void deleteInstanceProfile(String roleName, String profileName) {\ntry {\nScenarios 1072\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\ngetInstanceProfileRequest =\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\n.builder()\n.instanceProfileName(profileName)\n.build();\nGetInstanceProfileResponse response =\ngetIAMClient().getInstanceProfile(getInstanceProfileRequest);\nString name = response.instanceProfile().instanceProfileName();\nSystem.out.println(name);\nRemoveRoleFromInstanceProfileRequest profileRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.roleName(roleName)\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(profileRequest);\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.build();\ngetIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);\nSystem.out.println(\"Deleted instance profile \" + profileName);\nDeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()\n.roleName(roleName)\n.build();\n// List attached role policies.\nListAttachedRolePoliciesResponse rolesResponse = getIAMClient()\n.listAttachedRolePolicies(role -> role.roleName(roleName));\nList attachedPolicies =\nrolesResponse.attachedPolicies();\nfor (AttachedPolicy attachedPolicy : attachedPolicies) {\nDetachRolePolicyRequest request = DetachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(attachedPolicy.policyArn())\n.build();\ngetIAMClient().detachRolePolicy(request);\nScenarios 1073\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Detached and deleted policy \" +\nattachedPolicy.policyName());\n}\ngetIAMClient().deleteRole(deleteRoleRequest);\nSystem.out.println(\"Instance profile and role deleted.\");\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address.", "mimetype": "text/plain", "start_char_idx": 1566024, "end_char_idx": 1570835, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9e725470-42e9-4f16-a3d3-fd748753387c": {"__data__": {"id_": "9e725470-42e9-4f16-a3d3-fd748753387c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9110a870-98a8-4c39-bbd9-cd1f9df9ebcd", "node_type": "1", "metadata": {}, "hash": "ebc3bf165d30d66b700ec6c032a76eafab42ed619f388b4c10f7cb2dd30c25b0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "37b0f419-52e2-48a9-8e48-58d3e60362cf", "node_type": "1", "metadata": {}, "hash": "a327ecc547bd4b7a2ef03e1908e505fd98f1ee412fed1e71699e6266f0bfd7b2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address. In some situations, such as connecting from a corporate network, you\n* must instead specify a prefix list ID. You can also temporarily open the port\n* to\n* any IP address while running this example. If you do, be sure to remove\n* public\n* access when you're done.\n*\n*/\npublic GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {\nScenarios 1074\nAWS SDK for Java 2.x Developer Guide for version 2.x\nboolean portIsOpen = false;\nGroupInfo groupInfo = new GroupInfo();\ntry {\nFilter filter = Filter.builder()\n.name(\"group-name\")\n.values(\"default\")\n.build();\nFilter filter1 = Filter.builder()\n.name(\"vpc-id\")\n.values(VPC)\n.build();\nDescribeSecurityGroupsRequest securityGroupsRequest =\nDescribeSecurityGroupsRequest.builder()\n.filters(filter, filter1)\n.build();\nDescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()\n.describeSecurityGroups(securityGroupsRequest);\nString securityGroup =\nsecurityGroupsResponse.securityGroups().get(0).groupName();\ngroupInfo.setGroupName(securityGroup);\nfor (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {\nSystem.out.println(\"Found security group: \" + secGroup.groupId());\nfor (IpPermission ipPermission : secGroup.ipPermissions()) {\nif (ipPermission.fromPort() == port) {\nSystem.out.println(\"Found inbound rule: \" + ipPermission);\nfor (IpRange ipRange : ipPermission.ipRanges()) {\nString cidrIp = ipRange.cidrIp();\nif (cidrIp.startsWith(ipAddress) ||\ncidrIp.equals(\"0.0.0.0/0\")) {\nSystem.out.println(cidrIp + \" is applicable\");\nportIsOpen = true;\n}\n}\nif (!ipPermission.prefixListIds().isEmpty()) {\nSystem.out.println(\"Prefix lList is applicable\");\nportIsOpen = true;\n}\nScenarios 1075\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (!portIsOpen) {\nSystem.out\n.println(\"The inbound rule does not appear to be\nopen to either this computer's IP,\"\n+ \" all IP addresses (0.0.0.0/0), or to\na prefix list ID.\");\n} else {\nbreak;\n}\n}\n}\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\ngroupInfo.setPortOpen(portIsOpen);\nreturn groupInfo;\n}\n/*\n* Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto\n* Scaling group.\n* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\nScenarios 1076\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\n// Get availability zones.", "mimetype": "text/plain", "start_char_idx": 1570045, "end_char_idx": 1573882, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "37b0f419-52e2-48a9-8e48-58d3e60362cf": {"__data__": {"id_": "37b0f419-52e2-48a9-8e48-58d3e60362cf", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9e725470-42e9-4f16-a3d3-fd748753387c", "node_type": "1", "metadata": {}, "hash": "87989ac9d84b2731624e011b30fa955495eabf51bce40c9eb8f9b12ce77a9bd2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7d9c2b76-a22d-4eaf-ab56-6ea5d2810be4", "node_type": "1", "metadata": {}, "hash": "da896c7b5b9cd82b395a3a16dca330df1bbc79e6e8d12b5938641893c22a225c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\nScenarios 1076\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\n// Get availability zones.\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\nzonesRequest =\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\n.builder()\n.build();\nDescribeAvailabilityZonesResponse zonesResponse =\ngetEc2Client().describeAvailabilityZones(zonesRequest);\nList availabilityZoneNames =\nzonesResponse.availabilityZones().stream()\n.map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)\n.collect(Collectors.toList());\nString availabilityZones = String.join(\",\", availabilityZoneNames);\nLaunchTemplateSpecification specification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(templateName)\n.version(\"$Default\")\n.build();\nString[] zones = availabilityZones.split(\",\");\nCreateAutoScalingGroupRequest groupRequest =\nCreateAutoScalingGroupRequest.builder()\n.launchTemplate(specification)\n.availabilityZones(zones)\n.maxSize(groupSize)\n.minSize(groupSize)\n.autoScalingGroupName(autoScalingGroupName)\n.build();\ntry {\ngetAutoScalingClient().createAutoScalingGroup(groupRequest);\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nScenarios 1077\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.exit(1);\n}\nSystem.out.println(\"Created an EC2 Auto Scaling group named \" +\nautoScalingGroupName);\nreturn zones;\n}\npublic String getDefaultVPC() {\n// Define the filter.\nFilter defaultFilter = Filter.builder()\n.name(\"is-default\")\n.values(\"true\")\n.build();\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request =\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest\n.builder()\n.filters(defaultFilter)\n.build();\nDescribeVpcsResponse response = getEc2Client().describeVpcs(request);\nreturn response.vpcs().get(0).vpcId();\n}\n// Gets the default subnets in a VPC for a specified list of Availability Zones.\npublic List getSubnets(String vpcId, String[] availabilityZones) {\nList subnets = null;\nFilter vpcFilter = Filter.builder()\n.name(\"vpc-id\")\n.values(vpcId)\n.build();\nFilter azFilter = Filter.builder()\n.name(\"availability-zone\")\n.values(availabilityZones)\n.build();\nFilter defaultForAZ = Filter.builder()\n.name(\"default-for-az\")\n.values(\"true\")\n.build();\nDescribeSubnetsRequest request = DescribeSubnetsRequest.builder()\n.filters(vpcFilter, azFilter, defaultForAZ)\nScenarios 1078\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nDescribeSubnetsResponse response = getEc2Client().describeSubnets(request);\nsubnets = response.subnets();\nreturn subnets;\n}\n// Gets data about the instances in the EC2 Auto Scaling group.\npublic String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.", "mimetype": "text/plain", "start_char_idx": 1572995, "end_char_idx": 1577204, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7d9c2b76-a22d-4eaf-ab56-6ea5d2810be4": {"__data__": {"id_": "7d9c2b76-a22d-4eaf-ab56-6ea5d2810be4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "37b0f419-52e2-48a9-8e48-58d3e60362cf", "node_type": "1", "metadata": {}, "hash": "a327ecc547bd4b7a2ef03e1908e505fd98f1ee412fed1e71699e6266f0bfd7b2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "80dd32c6-b3b8-4117-8ea6-5bba69ed5151", "node_type": "1", "metadata": {}, "hash": "07c4fb6dd243858ee3748d82d7f230407d7f1afd3a53ffcc7e030626f889f320", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.\npublic String getInstanceProfile(String instanceId) {\nFilter filter = Filter.builder()\n.name(\"instance-id\")\n.values(instanceId)\n.build();\nDescribeIamInstanceProfileAssociationsRequest associationsRequest =\nDescribeIamInstanceProfileAssociationsRequest\n.builder()\n.filters(filter)\n.build();\nDescribeIamInstanceProfileAssociationsResponse response = getEc2Client()\n.describeIamInstanceProfileAssociations(associationsRequest);\nScenarios 1079\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn response.iamInstanceProfileAssociations().get(0).associationId();\n}\npublic void deleteRolesPolicies(String policyName, String roleName, String\nInstanceProfile) {\nListPoliciesRequest listPoliciesRequest =\nListPoliciesRequest.builder().build();\nListPoliciesResponse listPoliciesResponse =\ngetIAMClient().listPolicies(listPoliciesRequest);\nfor (Policy policy : listPoliciesResponse.policies()) {\nif (policy.policyName().equals(policyName)) {\n// List the entities (users, groups, roles) that are attached to the\npolicy.\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\nlistEntitiesRequest =\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\n.builder()\n.policyArn(policy.arn())\n.build();\nListEntitiesForPolicyResponse listEntitiesResponse = iamClient\n.listEntitiesForPolicy(listEntitiesRequest);\nif (!listEntitiesResponse.policyGroups().isEmpty() || !\nlistEntitiesResponse.policyUsers().isEmpty()\n|| !listEntitiesResponse.policyRoles().isEmpty()) {\n// Detach the policy from any entities it is attached to.\nDetachRolePolicyRequest detachPolicyRequest =\nDetachRolePolicyRequest.builder()\n.policyArn(policy.arn())\n.roleName(roleName) // Specify the name of the IAM role\n.build();\ngetIAMClient().detachRolePolicy(detachPolicyRequest);\nSystem.out.println(\"Policy detached from entities.\");\n}\n// Now, you can delete the policy.\nDeletePolicyRequest deletePolicyRequest =\nDeletePolicyRequest.builder()\n.policyArn(policy.arn())\n.build();\ngetIAMClient().deletePolicy(deletePolicyRequest);\nSystem.out.println(\"Policy deleted successfully.\");\nScenarios 1080\nAWS SDK for Java 2.x Developer Guide for version 2.x\nbreak;\n}\n}\n// List the roles associated with the instance profile\nListInstanceProfilesForRoleRequest listRolesRequest =\nListInstanceProfilesForRoleRequest.builder()\n.roleName(roleName)\n.build();\n// Detach the roles from the instance profile\nListInstanceProfilesForRoleResponse listRolesResponse =\niamClient.listInstanceProfilesForRole(listRolesRequest);\nfor (software.amazon.awssdk.services.iam.model.InstanceProfile profile :\nlistRolesResponse.instanceProfiles()) {\nRemoveRoleFromInstanceProfileRequest removeRoleRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.roleName(roleName) // Remove the extra dot here\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);\nSystem.out.println(\"Role \" + roleName + \" removed from instance profile\n\" + InstanceProfile);\n}\n// Delete the instance profile after removing all roles\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.build();\ngetIAMClient().deleteInstanceProfile(r ->\nr.instanceProfileName(InstanceProfile));\nSystem.out.println(InstanceProfile + \" Deleted\");\nSystem.out.println(\"All roles and policies are deleted.\");\n}\n}\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\nScenarios 1081\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.", "mimetype": "text/plain", "start_char_idx": 1576462, "end_char_idx": 1581102, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "80dd32c6-b3b8-4117-8ea6-5bba69ed5151": {"__data__": {"id_": "80dd32c6-b3b8-4117-8ea6-5bba69ed5151", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7d9c2b76-a22d-4eaf-ab56-6ea5d2810be4", "node_type": "1", "metadata": {}, "hash": "da896c7b5b9cd82b395a3a16dca330df1bbc79e6e8d12b5938641893c22a225c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f1cee4a3-60e6-4895-b393-ce6a6355e1fa", "node_type": "1", "metadata": {}, "hash": "b4eef14b6e53d1cf664dcbe8c5e3ef222156da607f19b9863d2f48646b598e68", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n}\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\nScenarios 1081\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.\npublic List checkTargetHealth(String targetGroupName) {\nDescribeTargetGroupsRequest targetGroupsRequest =\nDescribeTargetGroupsRequest.builder()\n.names(targetGroupName)\n.build();\nDescribeTargetGroupsResponse tgResponse =\ngetLoadBalancerClient().describeTargetGroups(targetGroupsRequest);\nDescribeTargetHealthRequest healthRequest =\nDescribeTargetHealthRequest.builder()\n.targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())\n.build();\nDescribeTargetHealthResponse healthResponse =\ngetLoadBalancerClient().describeTargetHealth(healthRequest);\nreturn healthResponse.targetHealthDescriptions();\n}\n// Gets the HTTP endpoint of the load balancer.\npublic String getEndpoint(String lbName) {\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nreturn res.loadBalancers().get(0).dnsName();\n}\n// Deletes a load balancer.\npublic void deleteLoadBalancer(String lbName) {\ntry {\n// Use a waiter to delete the Load Balancer.\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\nScenarios 1082\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.describeLoadBalancers(describe -> describe.names(lbName));\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())\n.build();\ngetLoadBalancerClient().deleteLoadBalancer(\nbuilder ->\nbuilder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancersDeleted(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(lbName + \" was deleted.\");\n}\n// Deletes the target group.\npublic void deleteTargetGroup(String targetGroupName) {\ntry {\nDescribeTargetGroupsResponse res = getLoadBalancerClient()\n.describeTargetGroups(describe ->\ndescribe.names(targetGroupName));\ngetLoadBalancerClient()\n.deleteTargetGroup(builder ->\nbuilder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(targetGroupName + \" was deleted.\");\n}\n// Verify this computer can successfully send a GET request to the load balancer\n// endpoint.\npublic boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException,\nInterruptedException {\nboolean success = false;\nint retries = 3;\nCloseableHttpClient httpClient = HttpClients.createDefault();\nScenarios 1083\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" + elbDnsName);\ntry {\nwhile ((!success) && (retries > 0)) {\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.", "mimetype": "text/plain", "start_char_idx": 1580563, "end_char_idx": 1584759, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f1cee4a3-60e6-4895-b393-ce6a6355e1fa": {"__data__": {"id_": "f1cee4a3-60e6-4895-b393-ce6a6355e1fa", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "80dd32c6-b3b8-4117-8ea6-5bba69ed5151", "node_type": "1", "metadata": {}, "hash": "07c4fb6dd243858ee3748d82d7f230407d7f1afd3a53ffcc7e030626f889f320", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "386b7615-6e06-4c6a-9fc8-78807f19f493", "node_type": "1", "metadata": {}, "hash": "789a2f969bd9f0ebb2b071425894fcef0dd2aaa470cc84783d84355bd3fa561c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "HttpGet httpGet = new HttpGet(\"http://\" + elbDnsName);\ntry {\nwhile ((!success) && (retries > 0)) {\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.\n*/\npublic String createTargetGroup(String protocol, int port, String vpcId, String\ntargetGroupName) {\nCreateTargetGroupRequest targetGroupRequest =\nCreateTargetGroupRequest.builder()\n.healthCheckPath(\"/healthcheck\")\n.healthCheckTimeoutSeconds(5)\n.port(port)\n.vpcId(vpcId)\n.name(targetGroupName)\n.protocol(protocol)\n.build();\nScenarios 1084\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreateTargetGroupResponse targetGroupResponse =\ngetLoadBalancerClient().createTargetGroup(targetGroupRequest);\nString targetGroupArn =\ntargetGroupResponse.targetGroups().get(0).targetGroupArn();\nString targetGroup =\ntargetGroupResponse.targetGroups().get(0).targetGroupName();\nSystem.out.println(\"The \" + targetGroup + \" was created with ARN\" +\ntargetGroupArn);\nreturn targetGroupArn;\n}\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.\n*/\npublic String createLoadBalancer(List subnetIds, String targetGroupARN,\nString lbName, int port,\nString protocol) {\ntry {\nList subnetIdStrings = subnetIds.stream()\n.map(Subnet::subnetId)\n.collect(Collectors.toList());\nCreateLoadBalancerRequest balancerRequest =\nCreateLoadBalancerRequest.builder()\n.subnets(subnetIdStrings)\n.name(lbName)\n.scheme(\"internet-facing\")\n.build();\n// Create and wait for the load balancer to become available.\nCreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(lbARN)\n.build();\nScenarios 1085\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\n// Get the DNS name (endpoint) of the load balancer.\nString lbDNSName = lsResponse.loadBalancers().get(0).dnsName();\nSystem.out.println(\"*** Load Balancer DNS Name: \" + lbDNSName);\n// Create a listener for the load balance.\nAction action = Action.builder()\n.targetGroupArn(targetGroupARN)\n.type(\"forward\")\n.build();\nCreateListenerRequest listenerRequest = CreateListenerRequest.builder()\n.loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())\n.defaultActions(action)\n.port(port)\n.protocol(protocol)\n.defaultActions(action)\n.build();\ngetLoadBalancerClient().createListener(listenerRequest);\nSystem.out.println(\"Created listener to forward traffic from load\nbalancer \" + lbName + \" to target group \"\n+ targetGroupARN);\n// Return the load balancer DNS name.\nreturn lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nScenarios 1086\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.", "mimetype": "text/plain", "start_char_idx": 1583926, "end_char_idx": 1588341, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "386b7615-6e06-4c6a-9fc8-78807f19f493": {"__data__": {"id_": "386b7615-6e06-4c6a-9fc8-78807f19f493", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f1cee4a3-60e6-4895-b393-ce6a6355e1fa", "node_type": "1", "metadata": {}, "hash": "b4eef14b6e53d1cf664dcbe8c5e3ef222156da607f19b9863d2f48646b598e68", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b4e04e6c-6ed5-4aaa-8279-d8453623b203", "node_type": "1", "metadata": {}, "hash": "2aeccf6d88ee36af1491082500e70f9d74d5c352a7453da76b03b0c03cac01bf", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nScenarios 1086\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.\nDescribeTableRequest describeTableRequest =\nDescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ngetDynamoDbClient().describeTable(describeTableRequest);\nSystem.out.println(\"Table '\" + tableName + \"' exists.\");\nreturn true;\n} catch (ResourceNotFoundException e) {\nSystem.out.println(\"Table '\" + tableName + \"' does not exist.\");\n} catch (DynamoDbException e) {\nSystem.err.println(\"Error checking table existence: \" + e.getMessage());\n}\nreturn false;\n}\n/*\n* Creates a DynamoDB table to use a recommendation service. The table has a\n* hash key named 'MediaType' that defines the type of media recommended, such\n* as\n* Book or Movie, and a range key named 'ItemId' that, combined with the\n* MediaType,\n* forms a unique identifier for the recommended item.\n*/\nScenarios 1087\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void createTable(String tableName, String fileName) throws IOException {\n// First check to see if the table exists.\nboolean doesExist = doesTableExist(tableName);\nif (!doesExist) {\nDynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();\nCreateTableRequest createTableRequest = CreateTableRequest.builder()\n.tableName(tableName)\n.attributeDefinitions(\nAttributeDefinition.builder()\n.attributeName(\"MediaType\")\n.attributeType(ScalarAttributeType.S)\n.build(),\nAttributeDefinition.builder()\n.attributeName(\"ItemId\")\n.attributeType(ScalarAttributeType.N)\n.build())\n.keySchema(\nKeySchemaElement.builder()\n.attributeName(\"MediaType\")\n.keyType(KeyType.HASH)\n.build(),\nKeySchemaElement.builder()\n.attributeName(\"ItemId\")\n.keyType(KeyType.RANGE)\n.build())\n.provisionedThroughput(\nProvisionedThroughput.builder()\n.readCapacityUnits(5L)\n.writeCapacityUnits(5L)\n.build())\n.build();\ngetDynamoDbClient().createTable(createTableRequest);\nSystem.out.println(\"Creating table \" + tableName + \"...\");\n// Wait until the Amazon DynamoDB table is created.\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Table \" + tableName + \" created.\");\nScenarios 1088\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Add records to the table.\npopulateTable(fileName, tableName);\n}\n}\npublic void deleteTable(String tableName) {\ngetDynamoDbClient().deleteTable(table -> table.tableName(tableName));\nSystem.out.println(\"Table \" + tableName + \" deleted.\");\n}\n// Populates the table with data located in a JSON file using the DynamoDB\n// enhanced client.\npublic void populateTable(String fileName, String tableName) throws IOException\n{\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(getDynamoDbClient())\n.build();\nObjectMapper objectMapper = new ObjectMapper();\nFile jsonFile = new File(fileName);\nJsonNode rootNode = objectMapper.readTree(jsonFile);\nDynamoDbTable mappedTable = enhancedClient.table(tableName,\nTableSchema.fromBean(Recommendation.class));\nfor (JsonNode currentNode : rootNode) {\nString mediaType = currentNode.path(\"MediaType\").path(\"S\").asText();\nint itemId = currentNode.path(\"ItemId\").path(\"N\").asInt();\nString title = currentNode.path(\"Title\").path(\"S\").asText();\nString creator = currentNode.path(\"Creator\").path(\"S\").asText();\n// Create a Recommendation object and set its properties.\nRecommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nScenarios 1089\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that wraps Systems Manager actions.", "mimetype": "text/plain", "start_char_idx": 1587685, "end_char_idx": 1592187, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b4e04e6c-6ed5-4aaa-8279-d8453623b203": {"__data__": {"id_": "b4e04e6c-6ed5-4aaa-8279-d8453623b203", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "386b7615-6e06-4c6a-9fc8-78807f19f493", "node_type": "1", "metadata": {}, "hash": "789a2f969bd9f0ebb2b071425894fcef0dd2aaa470cc84783d84355bd3fa561c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a27a86b3-b6e3-4c23-9496-7930ffbfd243", "node_type": "1", "metadata": {}, "hash": "3dda6b9517614c0fa3dab1004f03b77b0907332baa73e783f8007d3623fe7dfd", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Recommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nScenarios 1089\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that wraps Systems Manager actions.\npublic class ParameterHelper {\nString tableName = \"doc-example-resilient-architecture-table\";\nString dyntable = \"doc-example-recommendation-service\";\nString failureResponse = \"doc-example-resilient-architecture-failure-response\";\nString healthCheck = \"doc-example-resilient-architecture-health-check\";\npublic void reset() {\nput(dyntable, tableName);\nput(failureResponse, \"none\");\nput(healthCheck, \"shallow\");\n}\npublic void put(String name, String value) {\nSsmClient ssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\nPutParameterRequest parameterRequest = PutParameterRequest.builder()\n.name(name)\n.value(value)\n.overwrite(true)\n.type(\"String\")\n.build();\nssmClient.putParameter(parameterRequest);\nSystem.out.printf(\"Setting demo parameter %s to '%s'.\", name, value);\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 AttachLoadBalancerTargetGroups\n\u2022 CreateAutoScalingGroup\n\u2022 CreateInstanceProfile\n\u2022 CreateLaunchTemplate\n\u2022 CreateListener\nScenarios 1090\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 CreateLoadBalancer\n\u2022 CreateTargetGroup\n\u2022 DeleteAutoScalingGroup\n\u2022 DeleteInstanceProfile\n\u2022 DeleteLaunchTemplate\n\u2022 DeleteLoadBalancer\n\u2022 DeleteTargetGroup\n\u2022 DescribeAutoScalingGroups\n\u2022 DescribeAvailabilityZones\n\u2022 DescribeIamInstanceProfileAssociations\n\u2022 DescribeInstances\n\u2022 DescribeLoadBalancers\n\u2022 DescribeSubnets\n\u2022 DescribeTargetGroups\n\u2022 DescribeTargetHealth\n\u2022 DescribeVpcs\n\u2022 RebootInstances\n\u2022 ReplaceIamInstanceProfileAssociation\n\u2022 TerminateInstanceInAutoScalingGroup\n\u2022 UpdateAutoScalingGroup\nAmazon ECR examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon ECR.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\ntAom aszeont EuCRp and run the code in context. 1091\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGet started\nHello Amazon ECR\nThe following code examples show how to get started using Amazon ECR.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecr.EcrClient;\nimport software.amazon.awssdk.services.ecr.model.EcrException;\nimport software.amazon.awssdk.services.ecr.model.ListImagesRequest;\nimport software.amazon.awssdk.services.ecr.paginators.ListImagesIterable;\npublic class HelloECR {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\nrepositoryName - The name of the Amazon ECR repository.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString repoName = args[0];\nEcrClient ecrClient = EcrClient.builder()\n.region(Region.US_EAST_1)\n.build();\nlistImageTags(ecrClient, repoName);\n}\nAmazon ECR 1092\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void listImageTags(EcrClient ecrClient, String repoName){\nListImagesRequest listImagesPaginator = ListImagesRequest.builder()\n.repositoryName(repoName)\n.build();\nListImagesIterable imagesIterable =\necrClient.listImagesPaginator(listImagesPaginator);\nimagesIterable.stream()\n.flatMap(r -> r.imageIds().stream())\n.forEach(image -> System.out.println(\"The docker image tag is: \"\n+image.imageTag()));\n}\n}\n\u2022 For API details, see listImages in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create an Amazon ECR repository.\n\u2022 Set repository policies.\n\u2022 Retrieve repository URIs.\n\u2022 Get Amazon ECR authorization tokens.", "mimetype": "text/plain", "start_char_idx": 1591755, "end_char_idx": 1596142, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a27a86b3-b6e3-4c23-9496-7930ffbfd243": {"__data__": {"id_": "a27a86b3-b6e3-4c23-9496-7930ffbfd243", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b4e04e6c-6ed5-4aaa-8279-d8453623b203", "node_type": "1", "metadata": {}, "hash": "2aeccf6d88ee36af1491082500e70f9d74d5c352a7453da76b03b0c03cac01bf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8d1f77d9-1082-4918-9027-e3a6e556df29", "node_type": "1", "metadata": {}, "hash": "12eb9a68ca0f6787de1463d1f53db90d9b4865143710fc413d8a5e548b88674c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Topics\n\u2022 Basics\n\u2022 Actions\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create an Amazon ECR repository.\n\u2022 Set repository policies.\n\u2022 Retrieve repository URIs.\n\u2022 Get Amazon ECR authorization tokens.\n\u2022 Set lifecycle policies for Amazon ECR repositories.\n\u2022 Push a Docker image to an Amazon ECR repository.\n\u2022 Verify the existence of an image in an Amazon ECR repository.\n\u2022 List Amazon ECR repositories for your account and get details about them.\n\u2022 Delete Amazon ECR repositories.\nBasics 1093\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun an interactive scenario demonstrating Amazon ECR features.\nimport software.amazon.awssdk.services.ecr.model.EcrException;\nimport software.amazon.awssdk.services.ecr.model.RepositoryPolicyNotFoundException;\nimport java.util.Scanner;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This Java code example requires an IAM Role that has permissions to interact with\nthe Amazon ECR service.\n*\n* To create an IAM role, see:\n*\n* https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html\n*\n* This Java scenario example requires a local docker image named echo-text. Without\na local image,\n* this Java program will not successfully run. For more information including how\nto create the local\n* image, see:\n*\n* /getting_started_scenarios/ecr_scenario/README\n*\n*/\npublic class ECRScenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nBasics 1094\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUsage: \nWhere:\niamRoleARN - The IAM role ARN that has the necessary permissions to\naccess and manage the Amazon ECR repository.\naccountId - Your AWS account number.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nreturn;\n}\nECRActions ecrActions = new ECRActions();\nString iamRole = args[0];\nString accountId = args[1];\nString localImageName;\nScanner scanner = new Scanner(System.in);\nSystem.out.println(\"\"\"\nThe Amazon Elastic Container Registry (ECR) is a fully-managed Docker\ncontainer registry\nservice provided by AWS. It allows developers and organizations to\nsecurely\nstore, manage, and deploy Docker container images.\nECR provides a simple and scalable way to manage container images\nthroughout their lifecycle,\nfrom building and testing to production deployment.\\s\nThe `EcrAsyncClient` interface in the AWS SDK for Java 2.x provides a\nset of methods to\nprogrammatically interact with the Amazon ECR service. This allows\ndevelopers to\nautomate the storage, retrieval, and management of container images as\npart of their application\ndeployment pipelines. With ECR, teams can focus on building and\ndeploying their\napplications without having to worry about the underlying\ninfrastructure required to\nhost and manage a container registry.\nThis scenario walks you through how to perform key operations for this\nservice.\nLet's get started...\nBasics 1095\nAWS SDK for Java 2.x Developer Guide for version 2.x\nYou have two choices:\n1 - Run the entire program.\n2 - Delete an existing Amazon ECR repository named echo-text (created\nfrom a previous execution of\nthis program that did not complete).\n\"\"\");\nwhile (true) {\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"1\")) {\nSystem.out.println(\"Continuing with the program...\");\nSystem.out.println(\"\");\nbreak;\n} else if (input.trim().equalsIgnoreCase(\"2\")) {\nString repoName = \"echo-text\";\necrActions.deleteECRRepository(repoName);\nreturn;\n} else {\n// Handle invalid input.\nSystem.out.println(\"Invalid input. Please try again.\");\n}\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n1. Create an ECR repository.\nThe first task is to ensure we have a local Docker image named echo-\ntext.\nIf this image exists, then an Amazon ECR repository is created.\nAn ECR repository is a private Docker container repository provided\nby Amazon Web Services (AWS). It is a managed service that makes it easy\nto store, manage, and deploy Docker container images.\\s\n\"\"\" );\n// Ensure that a local docker image named echo-text exists.", "mimetype": "text/plain", "start_char_idx": 1595923, "end_char_idx": 1600403, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8d1f77d9-1082-4918-9027-e3a6e556df29": {"__data__": {"id_": "8d1f77d9-1082-4918-9027-e3a6e556df29", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a27a86b3-b6e3-4c23-9496-7930ffbfd243", "node_type": "1", "metadata": {}, "hash": "3dda6b9517614c0fa3dab1004f03b77b0907332baa73e783f8007d3623fe7dfd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "daf29cfd-8944-491b-9d79-0e55a170d556", "node_type": "1", "metadata": {}, "hash": "b6de89828578c3014dfd0a9e49ed11f4229d0b14340d016efc185525d8a27cb8", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "System.out.println(\"Invalid input. Please try again.\");\n}\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n1. Create an ECR repository.\nThe first task is to ensure we have a local Docker image named echo-\ntext.\nIf this image exists, then an Amazon ECR repository is created.\nAn ECR repository is a private Docker container repository provided\nby Amazon Web Services (AWS). It is a managed service that makes it easy\nto store, manage, and deploy Docker container images.\\s\n\"\"\" );\n// Ensure that a local docker image named echo-text exists.\nboolean doesExist = ecrActions.isEchoTextImagePresent();\nString repoName;\nif (!doesExist){\nSystem.out.println(\"The local image named echo-text does not exist\");\nBasics 1096\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn;\n} else {\nlocalImageName = \"echo-text\";\nrepoName = \"echo-text\";\n}\ntry {\nString repoArn = ecrActions.createECRRepository(repoName);\nSystem.out.println(\"The ARN of the ECR repository is \" + repoArn);\n} catch (IllegalArgumentException e) {\nSystem.err.println(\"Invalid repository name: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while creating the ECR repository:\n\" + e.getMessage());\ne.printStackTrace();\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n2. Set an ECR repository policy.\nSetting an ECR repository policy using the `setRepositoryPolicy` function is\ncrucial for maintaining\nthe security and integrity of your container images. The repository policy\nallows you to\ndefine specific rules and restrictions for accessing and managing the images\nstored within your ECR\nrepository.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.setRepoPolicy(repoName, iamRole);\n} catch (RepositoryPolicyNotFoundException e) {\nSystem.err.println(\"Invalid repository name: \" + e.getMessage());\nreturn;\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nBasics 1097\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(\"An error occurred while creating the ECR repository:\n\" + e.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n3. Display ECR repository policy.\nNow we will retrieve the ECR policy to ensure it was successfully set.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nString policyText = ecrActions.getRepoPolicy(repoName);\nSystem.out.println(\"Policy Text:\");\nSystem.out.println(policyText);\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while creating the ECR repository:\n\" + e.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n4. Retrieve an ECR authorization token.\nYou need an authorization token to securely access and interact with the\nAmazon ECR registry.\nThe `getAuthorizationToken` method of the `EcrAsyncClient` is responsible\nfor securely accessing\nand interacting with an Amazon ECR repository. This operation is responsible\nfor obtaining a\nvalid authorization token, which is required to authenticate your requests\nto the ECR service.\nWithout a valid authorization token, you would not be able to perform any\noperations on the\nBasics 1098\nAWS SDK for Java 2.x Developer Guide for version 2.x\nECR repository, such as pushing, pulling, or managing your Docker images.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.getAuthToken();\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while retrieving the authorization\ntoken: \" + e.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n5. Get the ECR Repository URI.\nThe URI of an Amazon ECR repository is important. When you want to deploy a\ncontainer image to\na container orchestration platform like Amazon Elastic Kubernetes Service\n(EKS)\nor Amazon Elastic Container Service (ECS), you need to specify the full\nimage URI,\nwhich includes the ECR repository URI. This allows the container runtime to\npull the\ncorrect container image from the ECR repository.", "mimetype": "text/plain", "start_char_idx": 1599828, "end_char_idx": 1604191, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "daf29cfd-8944-491b-9d79-0e55a170d556": {"__data__": {"id_": "daf29cfd-8944-491b-9d79-0e55a170d556", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8d1f77d9-1082-4918-9027-e3a6e556df29", "node_type": "1", "metadata": {}, "hash": "12eb9a68ca0f6787de1463d1f53db90d9b4865143710fc413d8a5e548b88674c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ff4de598-30fc-448c-b5f7-7e11176b9380", "node_type": "1", "metadata": {}, "hash": "18b00851b64603f71abf93b38e5d1ef8745e0ca2fcfdc19262967c2354e0213a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.getAuthToken();\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while retrieving the authorization\ntoken: \" + e.getMessage());\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n5. Get the ECR Repository URI.\nThe URI of an Amazon ECR repository is important. When you want to deploy a\ncontainer image to\na container orchestration platform like Amazon Elastic Kubernetes Service\n(EKS)\nor Amazon Elastic Container Service (ECS), you need to specify the full\nimage URI,\nwhich includes the ECR repository URI. This allows the container runtime to\npull the\ncorrect container image from the ECR repository.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.getRepositoryURI(repoName);\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while retrieving the URI: \" +\ne.getMessage());\nreturn;\nBasics 1099\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n6. Set an ECR Lifecycle Policy.\nAn ECR Lifecycle Policy is used to manage the lifecycle of Docker images\nstored in your ECR repositories.\nThese policies allow you to automatically remove old or unused Docker\nimages from your repositories,\nfreeing up storage space and reducing costs.\nThis example policy helps to maintain the size and efficiency of the\ncontainer registry\nby automatically removing older and potentially unused images, ensuring\nthat the\nstorage is optimized and the registry remains up-to-date.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.setLifeCyclePolicy(repoName);\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while setting the lifecycle\npolicy: \" + e.getMessage());\ne.printStackTrace();\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\n7. Push a docker image to the Amazon ECR Repository.\nThe `pushImageCmd()` method pushes a local Docker image to an Amazon ECR\nrepository.\nIt sets up the Docker client by connecting to the local Docker host using\nthe default port.\nIt then retrieves the authorization token for the ECR repository by making a\ncall to the AWS SDK.\nThe method uses the authorization token to create an `AuthConfig` object,\nwhich is used to authenticate\nBasics 1100\nAWS SDK for Java 2.x Developer Guide for version 2.x\nthe Docker client when pushing the image. Finally, the method tags the\nDocker image with the specified\nrepository name and image tag, and then pushes the image to the ECR\nrepository using the Docker client.\nIf the push operation is successful, the method prints a message indicating\nthat the image was pushed to ECR.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.pushDockerImage(repoName, localImageName);\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred while pushing a local Docker image\nto Amazon ECR: \" + e.getMessage());\ne.printStackTrace();\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"8. Verify if the image is in the ECR Repository.\");\nwaitForInputToContinue(scanner);\ntry {\necrActions.verifyImage(repoName, localImageName);\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nSystem.err.println(\"An error occurred \" + e.getMessage());\ne.printStackTrace();\nreturn;\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"9. As an optional step, you can interact with the image\nin Amazon ECR by using the CLI.\");\nSystem.out.println(\"Would you like to view instructions on how to use the\nCLI to run the image? (y/n)\");\nString ans = scanner.nextLine().trim();\nif (ans.equalsIgnoreCase(\"y\")) {\nString instructions = \"\"\"\nBasics 1101\nAWS SDK for Java 2.x Developer Guide for version 2.x\n1. Authenticate with ECR - Before you can pull the image from Amazon\nECR, you need to authenticate with the registry. You can do this using the AWS CLI:\naws ecr get-login-password --region us-east-1 | docker login --\nusername AWS --password-stdin %s.dkr.ecr.us-east-1.amazonaws.com\n2. Describe the image using this command:\naws ecr describe-images --repository-name %s --image-ids imageTag=%s\n3.", "mimetype": "text/plain", "start_char_idx": 1603368, "end_char_idx": 1607858, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ff4de598-30fc-448c-b5f7-7e11176b9380": {"__data__": {"id_": "ff4de598-30fc-448c-b5f7-7e11176b9380", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "daf29cfd-8944-491b-9d79-0e55a170d556", "node_type": "1", "metadata": {}, "hash": "b6de89828578c3014dfd0a9e49ed11f4229d0b14340d016efc185525d8a27cb8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4d81e891-2aa8-4c0e-82c8-6d2b27457eca", "node_type": "1", "metadata": {}, "hash": "c9f490d96f999a4ba4bd92d1c794bf7dd3f2eac47ea55b3f80999729c82ab4da", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "As an optional step, you can interact with the image\nin Amazon ECR by using the CLI.\");\nSystem.out.println(\"Would you like to view instructions on how to use the\nCLI to run the image? (y/n)\");\nString ans = scanner.nextLine().trim();\nif (ans.equalsIgnoreCase(\"y\")) {\nString instructions = \"\"\"\nBasics 1101\nAWS SDK for Java 2.x Developer Guide for version 2.x\n1. Authenticate with ECR - Before you can pull the image from Amazon\nECR, you need to authenticate with the registry. You can do this using the AWS CLI:\naws ecr get-login-password --region us-east-1 | docker login --\nusername AWS --password-stdin %s.dkr.ecr.us-east-1.amazonaws.com\n2. Describe the image using this command:\naws ecr describe-images --repository-name %s --image-ids imageTag=%s\n3. Run the Docker container and view the output using this command:\ndocker run --rm %s.dkr.ecr.us-east-1.amazonaws.com/%s:%s\n\"\"\";\ninstructions = String.format(instructions, accountId, repoName,\nlocalImageName, accountId, repoName, localImageName);\nSystem.out.println(instructions);\n}\nwaitForInputToContinue(scanner);\nSystem.out.println(DASHES);\nSystem.out.println(\"10. Delete the ECR Repository.\");\nSystem.out.println(\n\"\"\"\nIf the repository isn't empty, you must either delete the contents of the\nrepository\nor use the force option (used in this scenario) to delete the repository and\nhave Amazon ECR delete all of its contents\non your behalf.\n\"\"\");\nSystem.out.println(\"Would you like to delete the Amazon ECR Repository? (y/\nn)\");\nString delAns = scanner.nextLine().trim();\nif (delAns.equalsIgnoreCase(\"y\")) {\nSystem.out.println(\"You selected to delete the AWS ECR resources.\");\ntry {\necrActions.deleteECRRepository(repoName);\n} catch (EcrException e) {\nSystem.err.println(\"An ECR exception occurred: \" + e.getMessage());\nreturn;\n} catch (RuntimeException e) {\nBasics 1102\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(\"An error occurred while deleting the Docker\nimage: \" + e.getMessage());\ne.printStackTrace();\nreturn;\n}\n}\nSystem.out.println(DASHES);\nSystem.out.println(\"This concludes the Amazon ECR SDK scenario\");\nSystem.out.println(DASHES);\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nSystem.out.println(\"\");\nSystem.out.println(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nSystem.out.println(\"Continuing with the program...\");\nSystem.out.println(\"\");\nbreak;\n} else {\n// Handle invalid input.\nSystem.out.println(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nA wrapper class for Amazon ECR SDK methods.", "mimetype": "text/plain", "start_char_idx": 1607106, "end_char_idx": 1609702, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4d81e891-2aa8-4c0e-82c8-6d2b27457eca": {"__data__": {"id_": "4d81e891-2aa8-4c0e-82c8-6d2b27457eca", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ff4de598-30fc-448c-b5f7-7e11176b9380", "node_type": "1", "metadata": {}, "hash": "18b00851b64603f71abf93b38e5d1ef8745e0ca2fcfdc19262967c2354e0213a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "77461967-9c4f-489d-a9e3-34f6ef018ec8", "node_type": "1", "metadata": {}, "hash": "0517b307587fdfdc16d48e321f102e0a552b433a6e10c7707e39ca6fd755d55f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "System.out.println(\"Invalid input. Please try again.\");\n}\n}\n}\n}\nA wrapper class for Amazon ECR SDK methods.\nimport com.github.dockerjava.api.DockerClient;\nimport com.github.dockerjava.api.exception.DockerClientException;\nimport com.github.dockerjava.api.model.AuthConfig;\nimport com.github.dockerjava.api.model.Image;\nimport com.github.dockerjava.core.DockerClientBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nBasics 1103\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecr.EcrAsyncClient;\nimport software.amazon.awssdk.services.ecr.model.AuthorizationData;\nimport software.amazon.awssdk.services.ecr.model.CreateRepositoryRequest;\nimport software.amazon.awssdk.services.ecr.model.CreateRepositoryResponse;\nimport software.amazon.awssdk.services.ecr.model.DeleteRepositoryRequest;\nimport software.amazon.awssdk.services.ecr.model.DeleteRepositoryResponse;\nimport software.amazon.awssdk.services.ecr.model.DescribeImagesRequest;\nimport software.amazon.awssdk.services.ecr.model.DescribeImagesResponse;\nimport software.amazon.awssdk.services.ecr.model.DescribeRepositoriesRequest;\nimport software.amazon.awssdk.services.ecr.model.DescribeRepositoriesResponse;\nimport software.amazon.awssdk.services.ecr.model.EcrException;\nimport software.amazon.awssdk.services.ecr.model.GetAuthorizationTokenResponse;\nimport software.amazon.awssdk.services.ecr.model.GetRepositoryPolicyRequest;\nimport software.amazon.awssdk.services.ecr.model.GetRepositoryPolicyResponse;\nimport software.amazon.awssdk.services.ecr.model.ImageIdentifier;\nimport software.amazon.awssdk.services.ecr.model.Repository;\nimport software.amazon.awssdk.services.ecr.model.RepositoryPolicyNotFoundException;\nimport software.amazon.awssdk.services.ecr.model.SetRepositoryPolicyRequest;\nimport software.amazon.awssdk.services.ecr.model.SetRepositoryPolicyResponse;\nimport software.amazon.awssdk.services.ecr.model.StartLifecyclePolicyPreviewRequest;\nimport\nsoftware.amazon.awssdk.services.ecr.model.StartLifecyclePolicyPreviewResponse;\nimport com.github.dockerjava.api.command.DockerCmdExecFactory;\nimport com.github.dockerjava.netty.NettyDockerCmdExecFactory;\nimport java.time.Duration;\nimport java.util.Base64;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\npublic class ECRActions {\nprivate static EcrAsyncClient ecrClient;\nprivate static DockerClient dockerClient;\nprivate static Logger logger = LoggerFactory.getLogger(ECRActions.class);\n/**\n* Creates an Amazon Elastic Container Registry (Amazon ECR) repository.\n*\n* @param repoName the name of the repository to create.\n* @return the Amazon Resource Name (ARN) of the created repository, or an empty\nstring if the operation failed.\nBasics 1104\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws IllegalArgumentException If repository name is invalid.\n* @throws RuntimeException if an error occurs while creating the\nrepository.\n*/\npublic String createECRRepository(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nCreateRepositoryRequest request = CreateRepositoryRequest.builder()\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().createRepository(request);\ntry {\nCreateRepositoryResponse result = response.join();\nif (result != null) {\nSystem.out.println(\"The \" + repoName + \" repository was created\nsuccessfully.\");\nreturn result.repository().repositoryArn();\n} else {\nthrow new RuntimeException(\"Unexpected response type\");\n}\n} catch (CompletionException e) {\nThrowable cause = e.getCause();\nif (cause instanceof EcrException ex) {\nif\n(\"RepositoryAlreadyExistsException\".equals(ex.awsErrorDetails().errorCode())) {\nSystem.out.println(\"The Amazon ECR repository already exists,\nmoving on...\");\nDescribeRepositoriesRequest describeRequest =\nDescribeRepositoriesRequest.builder()\n.repositoryNames(repoName)\n.build();\nDescribeRepositoriesResponse describeResponse =\ngetAsyncClient().describeRepositories(describeRequest).join();\nreturn describeResponse.repositories().get(0).repositoryArn();\n} else {\nthrow new RuntimeException(ex);\n}\n} else {\nthrow new RuntimeException(e);\nBasics 1105\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n}\n/**\n* Deletes an ECR (Elastic Container Registry) repository.\n*\n* @param repoName the name of the repository to delete.\n* @throws IllegalArgumentException if the repository name is null or empty.\n* @throws EcrException if there is an error deleting the repository.\n* @throws RuntimeException if an unexpected error occurs during the deletion\nprocess.", "mimetype": "text/plain", "start_char_idx": 1609595, "end_char_idx": 1614563, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "77461967-9c4f-489d-a9e3-34f6ef018ec8": {"__data__": {"id_": "77461967-9c4f-489d-a9e3-34f6ef018ec8", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4d81e891-2aa8-4c0e-82c8-6d2b27457eca", "node_type": "1", "metadata": {}, "hash": "c9f490d96f999a4ba4bd92d1c794bf7dd3f2eac47ea55b3f80999729c82ab4da", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "94d21098-8d58-46c4-bf79-5a600dfc9a87", "node_type": "1", "metadata": {}, "hash": "6a6a5127b704d51064c68d6d70518075a028c4b5b44dd64ed69eb0362862bdbc", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* @param repoName the name of the repository to delete.\n* @throws IllegalArgumentException if the repository name is null or empty.\n* @throws EcrException if there is an error deleting the repository.\n* @throws RuntimeException if an unexpected error occurs during the deletion\nprocess.\n*/\npublic void deleteECRRepository(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nDeleteRepositoryRequest repositoryRequest =\nDeleteRepositoryRequest.builder()\n.force(true)\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().deleteRepository(repositoryRequest);\nresponse.whenComplete((deleteRepositoryResponse, ex) -> {\nif (deleteRepositoryResponse != null) {\nSystem.out.println(\"You have successfully deleted the \" + repoName +\n\" repository\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n}\n});\n// Wait for the CompletableFuture to complete\nresponse.join();\nBasics 1106\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nprivate static DockerClient getDockerClient() {\nString osName = System.getProperty(\"os.name\");\nif (osName.startsWith(\"Windows\")) {\n// Make sure Docker Desktop is running.\nString dockerHost = \"tcp://localhost:2375\"; // Use the Docker Desktop\ndefault port.\nDockerCmdExecFactory dockerCmdExecFactory = new\nNettyDockerCmdExecFactory().withReadTimeout(20000).withConnectTimeout(20000);\ndockerClient =\nDockerClientBuilder.getInstance(dockerHost).withDockerCmdExecFactory(dockerCmdExecFactory).build();\n} else {\ndockerClient = DockerClientBuilder.getInstance().build();\n}\nreturn dockerClient;\n}\n/**\n* Retrieves an asynchronous Amazon Elastic Container Registry (ECR) client.\n*\n* @return the configured ECR asynchronous client.\n*/\nprivate static EcrAsyncClient getAsyncClient() {\n/*\nThe `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java,\nversion 2,\nand it is designed to provide a high-performance, asynchronous HTTP client\nfor interacting with AWS services.\nIt uses the Netty framework to handle the underlying network communication\nand the Java NIO API to\nprovide a non-blocking, event-driven approach to HTTP requests and\nresponses.\n*/\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(50) // Adjust as needed.\n.connectionTimeout(Duration.ofSeconds(60)) // Set the connection\ntimeout.\n.readTimeout(Duration.ofSeconds(60)) // Set the read timeout.\n.writeTimeout(Duration.ofSeconds(60)) // Set the write timeout.\n.build();\nBasics 1107\nAWS SDK for Java 2.x Developer Guide for version 2.x\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2)) // Set the overall API call\ntimeout.\n.apiCallAttemptTimeout(Duration.ofSeconds(90)) // Set the individual\ncall attempt timeout.\n.build();\nif (ecrClient == null) {\necrClient = EcrAsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn ecrClient;\n}\n/**\n* Sets the lifecycle policy for the specified repository.\n*\n* @param repoName the name of the repository for which to set the lifecycle\npolicy.\n*/\npublic void setLifeCyclePolicy(String repoName) {\n/*\nThis policy helps to maintain the size and efficiency of the container\nregistry\nby automatically removing older and potentially unused images,\nensuring that the storage is optimized and the registry remains up-to-\ndate.\n*/\nString polText = \"\"\"\n{\n\"rules\": [\n{\n\"rulePriority\": 1,\n\"description\": \"Expire images older than 14 days\",\n\"selection\": {\n\"tagStatus\": \"any\",\n\"countType\": \"sinceImagePushed\",\n\"countUnit\": \"days\",\n\"countNumber\": 14\nBasics 1108\nAWS SDK for Java 2.x Developer Guide for version 2.x\n},\n\"action\": {\n\"type\": \"expire\"\n}\n}\n]\n}\n\"\"\";\nStartLifecyclePolicyPreviewRequest lifecyclePolicyPreviewRequest =\nStartLifecyclePolicyPreviewRequest.builder()\n.lifecyclePolicyText(polText)\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().startLifecyclePolicyPreview(lifecyclePolicyPreviewRequest);\nresponse.whenComplete((lifecyclePolicyPreviewResponse, ex) -> {\nif (lifecyclePolicyPreviewResponse != null) {\nSystem.out.println(\"Lifecycle policy preview started\nsuccessfully.", "mimetype": "text/plain", "start_char_idx": 1614275, "end_char_idx": 1618713, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "94d21098-8d58-46c4-bf79-5a600dfc9a87": {"__data__": {"id_": "94d21098-8d58-46c4-bf79-5a600dfc9a87", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "77461967-9c4f-489d-a9e3-34f6ef018ec8", "node_type": "1", "metadata": {}, "hash": "0517b307587fdfdc16d48e321f102e0a552b433a6e10c7707e39ca6fd755d55f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9db9c519-1a93-4985-b1ea-d89065c6f50e", "node_type": "1", "metadata": {}, "hash": "90678a5bc3c12c2ffaf523d6995b3de06e1c9f3f1afe5621854d87c704da4a5a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*/\nString polText = \"\"\"\n{\n\"rules\": [\n{\n\"rulePriority\": 1,\n\"description\": \"Expire images older than 14 days\",\n\"selection\": {\n\"tagStatus\": \"any\",\n\"countType\": \"sinceImagePushed\",\n\"countUnit\": \"days\",\n\"countNumber\": 14\nBasics 1108\nAWS SDK for Java 2.x Developer Guide for version 2.x\n},\n\"action\": {\n\"type\": \"expire\"\n}\n}\n]\n}\n\"\"\";\nStartLifecyclePolicyPreviewRequest lifecyclePolicyPreviewRequest =\nStartLifecyclePolicyPreviewRequest.builder()\n.lifecyclePolicyText(polText)\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().startLifecyclePolicyPreview(lifecyclePolicyPreviewRequest);\nresponse.whenComplete((lifecyclePolicyPreviewResponse, ex) -> {\nif (lifecyclePolicyPreviewResponse != null) {\nSystem.out.println(\"Lifecycle policy preview started\nsuccessfully.\");\n} else {\nif (ex.getCause() instanceof EcrException) {\nthrow (EcrException) ex.getCause();\n} else {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n}\n});\n// Wait for the CompletableFuture to complete.\nresponse.join();\n}\n/**\n* Verifies the existence of an image in an Amazon Elastic Container Registry\n(Amazon ECR) repository asynchronously.\n*\n* @param repositoryName The name of the Amazon ECR repository.\n* @param imageTag The tag of the image to verify.\n* @throws EcrException if there is an error retrieving the image\ninformation from Amazon ECR.\nBasics 1109\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.\n*/\npublic void verifyImage(String repositoryName, String imageTag) {\nDescribeImagesRequest request = DescribeImagesRequest.builder()\n.repositoryName(repositoryName)\n.imageIds(ImageIdentifier.builder().imageTag(imageTag).build())\n.build();\nCompletableFuture response =\ngetAsyncClient().describeImages(request);\nresponse.whenComplete((describeImagesResponse, ex) -> {\nif (ex != null) {\nif (ex instanceof CompletionException) {\nThrowable cause = ex.getCause();\nif (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\nex.getCause());\n}\n} else if (describeImagesResponse != null && !\ndescribeImagesResponse.imageDetails().isEmpty()) {\nSystem.out.println(\"Image is present in the repository.\");\n} else {\nSystem.out.println(\"Image is not present in the repository.\");\n}\n});\n// Wait for the CompletableFuture to complete.\nresponse.join();\n}\n/**\n* Retrieves the repository URI for the specified repository name.\n*\n* @param repoName the name of the repository to retrieve the URI for.\n* @return the repository URI for the specified repository name.\n* @throws EcrException if there is an error retrieving the repository\ninformation.\nBasics 1110\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.\n*/\npublic void getRepositoryURI(String repoName) {\nDescribeRepositoriesRequest request = DescribeRepositoriesRequest.builder()\n.repositoryNames(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeRepositories(request);\nresponse.whenComplete((describeRepositoriesResponse, ex) -> {\nif (ex != null) {\nThrowable cause = ex.getCause();\nif (cause instanceof InterruptedException) {\nThread.currentThread().interrupt();\nString errorMessage = \"Thread interrupted while waiting for\nasynchronous operation: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\n} else {\nif (describeRepositoriesResponse != null) {\nif (!describeRepositoriesResponse.repositories().isEmpty()) {\nString repositoryUri =\ndescribeRepositoriesResponse.repositories().get(0).repositoryUri();\nSystem.out.println(\"Repository URI found: \" +\nrepositoryUri);\n} else {\nSystem.out.println(\"No repositories found for the given\nname.\");\n}\n} else {\nSystem.err.println(\"No response received from\ndescribeRepositories.\");\n}\n}\n});\nresponse.join();\n}\nBasics 1111\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Retrieves the authorization token for Amazon Elastic Container Registry\n(ECR).\n* This method makes an asynchronous call to the ECR client to retrieve the\nauthorization token.\n* If the operation is successful, the method prints the token to the console.\n* If an exception occurs, the method handles the exception and prints the error\nmessage.\n*\n* @throws EcrException if there is an error retrieving the authorization\ntoken from ECR.", "mimetype": "text/plain", "start_char_idx": 1617890, "end_char_idx": 1622713, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9db9c519-1a93-4985-b1ea-d89065c6f50e": {"__data__": {"id_": "9db9c519-1a93-4985-b1ea-d89065c6f50e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "94d21098-8d58-46c4-bf79-5a600dfc9a87", "node_type": "1", "metadata": {}, "hash": "6a6a5127b704d51064c68d6d70518075a028c4b5b44dd64ed69eb0362862bdbc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "97f7b4d8-ff60-4c55-b574-13354765b508", "node_type": "1", "metadata": {}, "hash": "661766ebe27881a216b0cb38390380e99293573322dc6b67b73de15d7b611c5c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n} else {\nSystem.err.println(\"No response received from\ndescribeRepositories.\");\n}\n}\n});\nresponse.join();\n}\nBasics 1111\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Retrieves the authorization token for Amazon Elastic Container Registry\n(ECR).\n* This method makes an asynchronous call to the ECR client to retrieve the\nauthorization token.\n* If the operation is successful, the method prints the token to the console.\n* If an exception occurs, the method handles the exception and prints the error\nmessage.\n*\n* @throws EcrException if there is an error retrieving the authorization\ntoken from ECR.\n* @throws RuntimeException if there is an unexpected error during the\noperation.\n*/\npublic void getAuthToken() {\nCompletableFuture response =\ngetAsyncClient().getAuthorizationToken();\nresponse.whenComplete((authorizationTokenResponse, ex) -> {\nif (authorizationTokenResponse != null) {\nAuthorizationData authorizationData =\nauthorizationTokenResponse.authorizationData().get(0);\nString token = authorizationData.authorizationToken();\nif (!token.isEmpty()) {\nSystem.out.println(\"The token was successfully retrieved.\");\n}\n} else {\nif (ex.getCause() instanceof EcrException) {\nthrow (EcrException) ex.getCause();\n} else {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex); // Rethrow the\nexception\n}\n}\n});\nresponse.join();\n}\n/**\n* Gets the repository policy for the specified repository.\n*\n* @param repoName the name of the repository.\nBasics 1112\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws EcrException if an AWS error occurs while getting the repository\npolicy.\n*/\npublic String getRepoPolicy(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nGetRepositoryPolicyRequest getRepositoryPolicyRequest =\nGetRepositoryPolicyRequest.builder()\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().getRepositoryPolicy(getRepositoryPolicyRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nSystem.out.println(\"Repository policy retrieved successfully.\");\n} else {\nif (ex.getCause() instanceof EcrException) {\nthrow (EcrException) ex.getCause();\n} else {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n}\n});\nGetRepositoryPolicyResponse result = response.join();\nreturn result != null ? result.policyText() : null;\n}\n/**\n* Sets the repository policy for the specified ECR repository.\n*\n* @param repoName the name of the ECR repository.\n* @param iamRole the IAM role to be granted access to the repository.\n* @throws RepositoryPolicyNotFoundException if the repository policy does not\nexist.\n* @throws EcrException if there is an unexpected error\nsetting the repository policy.\n*/\nBasics 1113\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void setRepoPolicy(String repoName, String iamRole) {\n/*\nThis example policy document grants the specified AWS principal the\npermission to perform the\n`ecr:BatchGetImage` action. This policy is designed to allow the specified\nprincipal\nto retrieve Docker images from the ECR repository.\n*/\nString policyDocumentTemplate = \"\"\"\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : [ {\n\"Sid\" : \"new statement\",\n\"Effect\" : \"Allow\",\n\"Principal\" : {\n\"AWS\" : \"%s\"\n},\n\"Action\" : \"ecr:BatchGetImage\"\n} ]\n}\n\"\"\";\nString policyDocument = String.format(policyDocumentTemplate, iamRole);\nSetRepositoryPolicyRequest setRepositoryPolicyRequest =\nSetRepositoryPolicyRequest.builder()\n.repositoryName(repoName)\n.policyText(policyDocument)\n.build();\nCompletableFuture response =\ngetAsyncClient().setRepositoryPolicy(setRepositoryPolicyRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nSystem.out.println(\"Repository policy set successfully.\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof RepositoryPolicyNotFoundException) {\nthrow (RepositoryPolicyNotFoundException) cause;\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\nBasics 1114\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n});\nresponse.join();\n}\n/**\n* Pushes a Docker image to an Amazon Elastic Container Registry (ECR)\nrepository.\n*\n* @param repoName the name of the ECR repository to push the image to.\n* @param imageName the name of the Docker image.", "mimetype": "text/plain", "start_char_idx": 1622097, "end_char_idx": 1626717, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "97f7b4d8-ff60-4c55-b574-13354765b508": {"__data__": {"id_": "97f7b4d8-ff60-4c55-b574-13354765b508", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9db9c519-1a93-4985-b1ea-d89065c6f50e", "node_type": "1", "metadata": {}, "hash": "90678a5bc3c12c2ffaf523d6995b3de06e1c9f3f1afe5621854d87c704da4a5a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fedc6767-8cb2-43cb-88e9-4d3286e9e7e5", "node_type": "1", "metadata": {}, "hash": "3f531c531f437cfdcb0debdc1553b667d95ab9018974e9fa29f71c4dec4668eb", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof RepositoryPolicyNotFoundException) {\nthrow (RepositoryPolicyNotFoundException) cause;\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\nBasics 1114\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n});\nresponse.join();\n}\n/**\n* Pushes a Docker image to an Amazon Elastic Container Registry (ECR)\nrepository.\n*\n* @param repoName the name of the ECR repository to push the image to.\n* @param imageName the name of the Docker image.\n*/\npublic void pushDockerImage(String repoName, String imageName) {\nSystem.out.println(\"Pushing \" + imageName + \" to Amazon ECR will take a few\nseconds.\");\nCompletableFuture authResponseFuture =\ngetAsyncClient().getAuthorizationToken()\n.thenApply(response -> {\nString token =\nresponse.authorizationData().get(0).authorizationToken();\nString decodedToken = new String(Base64.getDecoder().decode(token));\nString password = decodedToken.substring(4);\nDescribeRepositoriesResponse descrRepoResponse =\ngetAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();\nRepository repoData =\ndescrRepoResponse.repositories().stream().filter(r ->\nr.repositoryName().equals(repoName)).findFirst().orElse(null);\nassert repoData != null;\nString registryURL = repoData.repositoryUri().split(\"/\")[0];\nAuthConfig authConfig = new AuthConfig()\n.withUsername(\"AWS\")\n.withPassword(password)\n.withRegistryAddress(registryURL);\nreturn authConfig;\n})\n.thenCompose(authConfig -> {\nDescribeRepositoriesResponse descrRepoResponse =\ngetAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();\nRepository repoData =\ndescrRepoResponse.repositories().stream().filter(r ->\nr.repositoryName().equals(repoName)).findFirst().orElse(null);\nBasics 1115\nAWS SDK for Java 2.x Developer Guide for version 2.x\ngetDockerClient().tagImageCmd(imageName + \":latest\",\nrepoData.repositoryUri() + \":latest\", imageName).exec();\ntry {\ngetDockerClient().pushImageCmd(repoData.repositoryUri()).withTag(\"echo-\ntext\").withAuthConfig(authConfig).start().awaitCompletion();\nSystem.out.println(\"The \" + imageName + \" was pushed to ECR\");\n} catch (InterruptedException e) {\nthrow (RuntimeException) e.getCause();\n}\nreturn CompletableFuture.completedFuture(authConfig);\n});\nauthResponseFuture.join();\n}\n// Make sure local image echo-text exists.\npublic boolean isEchoTextImagePresent() {\ntry {\nList images = getDockerClient().listImagesCmd().exec();\nboolean helloWorldFound = false;\nfor (Image image : images) {\nString[] repoTags = image.getRepoTags();\nif (repoTags != null) {\nfor (String tag : repoTags) {\nif (tag.startsWith(\"echo-text\")) {\nSystem.out.println(tag);\nhelloWorldFound = true;\n}\n}\n}\n}\nif (helloWorldFound) {\nSystem.out.println(\"The local image named echo-text exists.\");\nreturn true;\n} else {\nSystem.out.println(\"The local image named echo-text does not\nexist.\");\nreturn false;\n}\n} catch (DockerClientException ex) {\nlogger.error(\"ERROR: \" + ex.getMessage());\nreturn false;\nBasics 1116\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 CreateRepository\n\u2022 DeleteRepository\n\u2022 DescribeImages\n\u2022 DescribeRepositories\n\u2022 GetAuthorizationToken\n\u2022 GetRepositoryPolicy\n\u2022 SetRepositoryPolicy\n\u2022 StartLifecyclePolicyPreview\nActions\nCreateRepository\nThe following code example shows how to use CreateRepository.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates an Amazon Elastic Container Registry (Amazon ECR) repository.\n*\n* @param repoName the name of the repository to create.\n* @return the Amazon Resource Name (ARN) of the created repository, or an empty\nstring if the operation failed.\n* @throws IllegalArgumentException If repository name is invalid.\n* @throws RuntimeException if an error occurs while creating the\nrepository.", "mimetype": "text/plain", "start_char_idx": 1626070, "end_char_idx": 1630150, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "fedc6767-8cb2-43cb-88e9-4d3286e9e7e5": {"__data__": {"id_": "fedc6767-8cb2-43cb-88e9-4d3286e9e7e5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "97f7b4d8-ff60-4c55-b574-13354765b508", "node_type": "1", "metadata": {}, "hash": "661766ebe27881a216b0cb38390380e99293573322dc6b67b73de15d7b611c5c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4569adb4-0a77-4f7b-af02-97ea8b44f642", "node_type": "1", "metadata": {}, "hash": "20fc5204c892a7c5e8e95c32ae7469d9b651f896e93ea3230c7960f510b43989", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\u2022 CreateRepository\n\u2022 DeleteRepository\n\u2022 DescribeImages\n\u2022 DescribeRepositories\n\u2022 GetAuthorizationToken\n\u2022 GetRepositoryPolicy\n\u2022 SetRepositoryPolicy\n\u2022 StartLifecyclePolicyPreview\nActions\nCreateRepository\nThe following code example shows how to use CreateRepository.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates an Amazon Elastic Container Registry (Amazon ECR) repository.\n*\n* @param repoName the name of the repository to create.\n* @return the Amazon Resource Name (ARN) of the created repository, or an empty\nstring if the operation failed.\n* @throws IllegalArgumentException If repository name is invalid.\n* @throws RuntimeException if an error occurs while creating the\nrepository.\nActions 1117\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic String createECRRepository(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nCreateRepositoryRequest request = CreateRepositoryRequest.builder()\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().createRepository(request);\ntry {\nCreateRepositoryResponse result = response.join();\nif (result != null) {\nSystem.out.println(\"The \" + repoName + \" repository was created\nsuccessfully.\");\nreturn result.repository().repositoryArn();\n} else {\nthrow new RuntimeException(\"Unexpected response type\");\n}\n} catch (CompletionException e) {\nThrowable cause = e.getCause();\nif (cause instanceof EcrException ex) {\nif\n(\"RepositoryAlreadyExistsException\".equals(ex.awsErrorDetails().errorCode())) {\nSystem.out.println(\"The Amazon ECR repository already exists,\nmoving on...\");\nDescribeRepositoriesRequest describeRequest =\nDescribeRepositoriesRequest.builder()\n.repositoryNames(repoName)\n.build();\nDescribeRepositoriesResponse describeResponse =\ngetAsyncClient().describeRepositories(describeRequest).join();\nreturn describeResponse.repositories().get(0).repositoryArn();\n} else {\nthrow new RuntimeException(ex);\n}\n} else {\nthrow new RuntimeException(e);\n}\n}\n}\nActions 1118\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see CreateRepository in AWS SDK for Java 2.x API Reference.\nDeleteRepository\nThe following code example shows how to use DeleteRepository.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes an ECR (Elastic Container Registry) repository.\n*\n* @param repoName the name of the repository to delete.\n* @throws IllegalArgumentException if the repository name is null or empty.\n* @throws EcrException if there is an error deleting the repository.\n* @throws RuntimeException if an unexpected error occurs during the deletion\nprocess.\n*/\npublic void deleteECRRepository(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nDeleteRepositoryRequest repositoryRequest =\nDeleteRepositoryRequest.builder()\n.force(true)\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().deleteRepository(repositoryRequest);\nresponse.whenComplete((deleteRepositoryResponse, ex) -> {\nif (deleteRepositoryResponse != null) {\nActions 1119\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"You have successfully deleted the \" + repoName +\n\" repository\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n}\n});\n// Wait for the CompletableFuture to complete\nresponse.join();\n}\n\u2022 For API details, see DeleteRepository in AWS SDK for Java 2.x API Reference.\nDescribeImages\nThe following code example shows how to use DescribeImages.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Verifies the existence of an image in an Amazon Elastic Container Registry\n(Amazon ECR) repository asynchronously.\n*\n* @param repositoryName The name of the Amazon ECR repository.\n* @param imageTag The tag of the image to verify.\n* @throws EcrException if there is an error retrieving the image\ninformation from Amazon ECR.\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.", "mimetype": "text/plain", "start_char_idx": 1629358, "end_char_idx": 1633883, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4569adb4-0a77-4f7b-af02-97ea8b44f642": {"__data__": {"id_": "4569adb4-0a77-4f7b-af02-97ea8b44f642", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fedc6767-8cb2-43cb-88e9-4d3286e9e7e5", "node_type": "1", "metadata": {}, "hash": "3f531c531f437cfdcb0debdc1553b667d95ab9018974e9fa29f71c4dec4668eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c7def5d-59f8-434e-aa74-eb5d8706123c", "node_type": "1", "metadata": {}, "hash": "9ea267e406b527aed893840752abef4c08683282bc71c8c5def00497ee38c4c9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeImages\nThe following code example shows how to use DescribeImages.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Verifies the existence of an image in an Amazon Elastic Container Registry\n(Amazon ECR) repository asynchronously.\n*\n* @param repositoryName The name of the Amazon ECR repository.\n* @param imageTag The tag of the image to verify.\n* @throws EcrException if there is an error retrieving the image\ninformation from Amazon ECR.\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.\nActions 1120\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic void verifyImage(String repositoryName, String imageTag) {\nDescribeImagesRequest request = DescribeImagesRequest.builder()\n.repositoryName(repositoryName)\n.imageIds(ImageIdentifier.builder().imageTag(imageTag).build())\n.build();\nCompletableFuture response =\ngetAsyncClient().describeImages(request);\nresponse.whenComplete((describeImagesResponse, ex) -> {\nif (ex != null) {\nif (ex instanceof CompletionException) {\nThrowable cause = ex.getCause();\nif (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\nex.getCause());\n}\n} else if (describeImagesResponse != null && !\ndescribeImagesResponse.imageDetails().isEmpty()) {\nSystem.out.println(\"Image is present in the repository.\");\n} else {\nSystem.out.println(\"Image is not present in the repository.\");\n}\n});\n// Wait for the CompletableFuture to complete.\nresponse.join();\n}\n\u2022 For API details, see DescribeImages in AWS SDK for Java 2.x API Reference.\nDescribeRepositories\nThe following code example shows how to use DescribeRepositories.\nActions 1121\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves the repository URI for the specified repository name.\n*\n* @param repoName the name of the repository to retrieve the URI for.\n* @return the repository URI for the specified repository name.\n* @throws EcrException if there is an error retrieving the repository\ninformation.\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.\n*/\npublic void getRepositoryURI(String repoName) {\nDescribeRepositoriesRequest request = DescribeRepositoriesRequest.builder()\n.repositoryNames(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().describeRepositories(request);\nresponse.whenComplete((describeRepositoriesResponse, ex) -> {\nif (ex != null) {\nThrowable cause = ex.getCause();\nif (cause instanceof InterruptedException) {\nThread.currentThread().interrupt();\nString errorMessage = \"Thread interrupted while waiting for\nasynchronous operation: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\n} else {\nif (describeRepositoriesResponse != null) {\nif (!describeRepositoriesResponse.repositories().isEmpty()) {\nActions 1122\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString repositoryUri =\ndescribeRepositoriesResponse.repositories().get(0).repositoryUri();\nSystem.out.println(\"Repository URI found: \" +\nrepositoryUri);\n} else {\nSystem.out.println(\"No repositories found for the given\nname.\");\n}\n} else {\nSystem.err.println(\"No response received from\ndescribeRepositories.\");\n}\n}\n});\nresponse.join();\n}\n\u2022 For API details, see DescribeRepositories in AWS SDK for Java 2.x API Reference.\nGetAuthorizationToken\nThe following code example shows how to use GetAuthorizationToken.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves the authorization token for Amazon Elastic Container Registry\n(ECR).\n* This method makes an asynchronous call to the ECR client to retrieve the\nauthorization token.\n* If the operation is successful, the method prints the token to the console.\n* If an exception occurs, the method handles the exception and prints the error\nmessage.\n*\nActions 1123\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws EcrException if there is an error retrieving the authorization\ntoken from ECR.\n* @throws RuntimeException if there is an unexpected error during the\noperation.", "mimetype": "text/plain", "start_char_idx": 1633253, "end_char_idx": 1637943, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "5c7def5d-59f8-434e-aa74-eb5d8706123c": {"__data__": {"id_": "5c7def5d-59f8-434e-aa74-eb5d8706123c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4569adb4-0a77-4f7b-af02-97ea8b44f642", "node_type": "1", "metadata": {}, "hash": "20fc5204c892a7c5e8e95c32ae7469d9b651f896e93ea3230c7960f510b43989", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d0ca82bd-a917-4ae7-afc2-cd6f6b184935", "node_type": "1", "metadata": {}, "hash": "28ef56a4f6b36aab6b68dbd7438d0bf6c3036955d907443e39e55374bc131693", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "GetAuthorizationToken\nThe following code example shows how to use GetAuthorizationToken.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Retrieves the authorization token for Amazon Elastic Container Registry\n(ECR).\n* This method makes an asynchronous call to the ECR client to retrieve the\nauthorization token.\n* If the operation is successful, the method prints the token to the console.\n* If an exception occurs, the method handles the exception and prints the error\nmessage.\n*\nActions 1123\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @throws EcrException if there is an error retrieving the authorization\ntoken from ECR.\n* @throws RuntimeException if there is an unexpected error during the\noperation.\n*/\npublic void getAuthToken() {\nCompletableFuture response =\ngetAsyncClient().getAuthorizationToken();\nresponse.whenComplete((authorizationTokenResponse, ex) -> {\nif (authorizationTokenResponse != null) {\nAuthorizationData authorizationData =\nauthorizationTokenResponse.authorizationData().get(0);\nString token = authorizationData.authorizationToken();\nif (!token.isEmpty()) {\nSystem.out.println(\"The token was successfully retrieved.\");\n}\n} else {\nif (ex.getCause() instanceof EcrException) {\nthrow (EcrException) ex.getCause();\n} else {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex); // Rethrow the\nexception\n}\n}\n});\nresponse.join();\n}\n\u2022 For API details, see GetAuthorizationToken in AWS SDK for Java 2.x API Reference.\nGetRepositoryPolicy\nThe following code example shows how to use GetRepositoryPolicy.\nActions 1124\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Gets the repository policy for the specified repository.\n*\n* @param repoName the name of the repository.\n* @throws EcrException if an AWS error occurs while getting the repository\npolicy.\n*/\npublic String getRepoPolicy(String repoName) {\nif (repoName == null || repoName.isEmpty()) {\nthrow new IllegalArgumentException(\"Repository name cannot be null or\nempty\");\n}\nGetRepositoryPolicyRequest getRepositoryPolicyRequest =\nGetRepositoryPolicyRequest.builder()\n.repositoryName(repoName)\n.build();\nCompletableFuture response =\ngetAsyncClient().getRepositoryPolicy(getRepositoryPolicyRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nSystem.out.println(\"Repository policy retrieved successfully.\");\n} else {\nif (ex.getCause() instanceof EcrException) {\nthrow (EcrException) ex.getCause();\n} else {\nString errorMessage = \"Unexpected error occurred: \" +\nex.getMessage();\nthrow new RuntimeException(errorMessage, ex);\n}\n}\n});\nActions 1125\nAWS SDK for Java 2.x Developer Guide for version 2.x\nGetRepositoryPolicyResponse result = response.join();\nreturn result != null ? result.policyText() : null;\n}\n\u2022 For API details, see GetRepositoryPolicy in AWS SDK for Java 2.x API Reference.\nPushImageCmd\nThe following code example shows how to use PushImageCmd.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Pushes a Docker image to an Amazon Elastic Container Registry (ECR)\nrepository.\n*\n* @param repoName the name of the ECR repository to push the image to.\n* @param imageName the name of the Docker image.\n*/\npublic void pushDockerImage(String repoName, String imageName) {\nSystem.out.println(\"Pushing \" + imageName + \" to Amazon ECR will take a few\nseconds.", "mimetype": "text/plain", "start_char_idx": 1637128, "end_char_idx": 1640858, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "d0ca82bd-a917-4ae7-afc2-cd6f6b184935": {"__data__": {"id_": "d0ca82bd-a917-4ae7-afc2-cd6f6b184935", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5c7def5d-59f8-434e-aa74-eb5d8706123c", "node_type": "1", "metadata": {}, "hash": "9ea267e406b527aed893840752abef4c08683282bc71c8c5def00497ee38c4c9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "90306be2-4db1-4f7f-9fca-e47dd38b0f99", "node_type": "1", "metadata": {}, "hash": "30b7b2fbb402f5c472e2320f2edb42f8b754c6c3316e559591e8a5836039a523", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "result.policyText() : null;\n}\n\u2022 For API details, see GetRepositoryPolicy in AWS SDK for Java 2.x API Reference.\nPushImageCmd\nThe following code example shows how to use PushImageCmd.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Pushes a Docker image to an Amazon Elastic Container Registry (ECR)\nrepository.\n*\n* @param repoName the name of the ECR repository to push the image to.\n* @param imageName the name of the Docker image.\n*/\npublic void pushDockerImage(String repoName, String imageName) {\nSystem.out.println(\"Pushing \" + imageName + \" to Amazon ECR will take a few\nseconds.\");\nCompletableFuture authResponseFuture =\ngetAsyncClient().getAuthorizationToken()\n.thenApply(response -> {\nString token =\nresponse.authorizationData().get(0).authorizationToken();\nString decodedToken = new String(Base64.getDecoder().decode(token));\nString password = decodedToken.substring(4);\nDescribeRepositoriesResponse descrRepoResponse =\ngetAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();\nRepository repoData =\ndescrRepoResponse.repositories().stream().filter(r ->\nr.repositoryName().equals(repoName)).findFirst().orElse(null);\nActions 1126\nAWS SDK for Java 2.x Developer Guide for version 2.x\nassert repoData != null;\nString registryURL = repoData.repositoryUri().split(\"/\")[0];\nAuthConfig authConfig = new AuthConfig()\n.withUsername(\"AWS\")\n.withPassword(password)\n.withRegistryAddress(registryURL);\nreturn authConfig;\n})\n.thenCompose(authConfig -> {\nDescribeRepositoriesResponse descrRepoResponse =\ngetAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();\nRepository repoData =\ndescrRepoResponse.repositories().stream().filter(r ->\nr.repositoryName().equals(repoName)).findFirst().orElse(null);\ngetDockerClient().tagImageCmd(imageName + \":latest\",\nrepoData.repositoryUri() + \":latest\", imageName).exec();\ntry {\ngetDockerClient().pushImageCmd(repoData.repositoryUri()).withTag(\"echo-\ntext\").withAuthConfig(authConfig).start().awaitCompletion();\nSystem.out.println(\"The \" + imageName + \" was pushed to ECR\");\n} catch (InterruptedException e) {\nthrow (RuntimeException) e.getCause();\n}\nreturn CompletableFuture.completedFuture(authConfig);\n});\nauthResponseFuture.join();\n}\n\u2022 For API details, see PushImageCmd in AWS SDK for Java 2.x API Reference.\nSetRepositoryPolicy\nThe following code example shows how to use SetRepositoryPolicy.\nActions 1127\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Sets the repository policy for the specified ECR repository.\n*\n* @param repoName the name of the ECR repository.\n* @param iamRole the IAM role to be granted access to the repository.\n* @throws RepositoryPolicyNotFoundException if the repository policy does not\nexist.\n* @throws EcrException if there is an unexpected error\nsetting the repository policy.\n*/\npublic void setRepoPolicy(String repoName, String iamRole) {\n/*\nThis example policy document grants the specified AWS principal the\npermission to perform the\n`ecr:BatchGetImage` action. This policy is designed to allow the specified\nprincipal\nto retrieve Docker images from the ECR repository.\n*/\nString policyDocumentTemplate = \"\"\"\n{\n\"Version\" : \"2012-10-17\",\n\"Statement\" : [ {\n\"Sid\" : \"new statement\",\n\"Effect\" : \"Allow\",\n\"Principal\" : {\n\"AWS\" : \"%s\"\n},\n\"Action\" : \"ecr:BatchGetImage\"\n} ]\n}\n\"\"\";\nString policyDocument = String.format(policyDocumentTemplate, iamRole);\nActions 1128\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSetRepositoryPolicyRequest setRepositoryPolicyRequest =\nSetRepositoryPolicyRequest.builder()\n.repositoryName(repoName)\n.policyText(policyDocument)\n.build();\nCompletableFuture response =\ngetAsyncClient().setRepositoryPolicy(setRepositoryPolicyRequest);\nresponse.whenComplete((resp, ex) -> {\nif (resp != null) {\nSystem.out.println(\"Repository policy set successfully.\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof RepositoryPolicyNotFoundException) {\nthrow (RepositoryPolicyNotFoundException) cause;\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\n}\n});\nresponse.join();\n}\n\u2022 For API details, see SetRepositoryPolicy in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1640174, "end_char_idx": 1644717, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "90306be2-4db1-4f7f-9fca-e47dd38b0f99": {"__data__": {"id_": "90306be2-4db1-4f7f-9fca-e47dd38b0f99", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d0ca82bd-a917-4ae7-afc2-cd6f6b184935", "node_type": "1", "metadata": {}, "hash": "28ef56a4f6b36aab6b68dbd7438d0bf6c3036955d907443e39e55374bc131693", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c23e5cf-785e-4e75-959f-a41dc81992ea", "node_type": "1", "metadata": {}, "hash": "1a7d3753080e14b0d94d441cfc495d2092709bc01df44e0aefa83ebb817eee33", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} else {\nThrowable cause = ex.getCause();\nif (cause instanceof RepositoryPolicyNotFoundException) {\nthrow (RepositoryPolicyNotFoundException) cause;\n} else if (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nString errorMessage = \"Unexpected error: \" + cause.getMessage();\nthrow new RuntimeException(errorMessage, cause);\n}\n}\n});\nresponse.join();\n}\n\u2022 For API details, see SetRepositoryPolicy in AWS SDK for Java 2.x API Reference.\nStartLifecyclePolicyPreview\nThe following code example shows how to use StartLifecyclePolicyPreview.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\nActions 1129\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* Verifies the existence of an image in an Amazon Elastic Container Registry\n(Amazon ECR) repository asynchronously.\n*\n* @param repositoryName The name of the Amazon ECR repository.\n* @param imageTag The tag of the image to verify.\n* @throws EcrException if there is an error retrieving the image\ninformation from Amazon ECR.\n* @throws CompletionException if the asynchronous operation completes\nexceptionally.\n*/\npublic void verifyImage(String repositoryName, String imageTag) {\nDescribeImagesRequest request = DescribeImagesRequest.builder()\n.repositoryName(repositoryName)\n.imageIds(ImageIdentifier.builder().imageTag(imageTag).build())\n.build();\nCompletableFuture response =\ngetAsyncClient().describeImages(request);\nresponse.whenComplete((describeImagesResponse, ex) -> {\nif (ex != null) {\nif (ex instanceof CompletionException) {\nThrowable cause = ex.getCause();\nif (cause instanceof EcrException) {\nthrow (EcrException) cause;\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\ncause.getMessage(), cause);\n}\n} else {\nthrow new RuntimeException(\"Unexpected error: \" +\nex.getCause());\n}\n} else if (describeImagesResponse != null && !\ndescribeImagesResponse.imageDetails().isEmpty()) {\nSystem.out.println(\"Image is present in the repository.\");\n} else {\nSystem.out.println(\"Image is not present in the repository.\");\n}\n});\n// Wait for the CompletableFuture to complete.\nresponse.join();\n}\nActions 1130\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see StartLifecyclePolicyPreview in AWS SDK for Java 2.x API Reference.\nAmazon ECS examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Amazon ECS.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nTopics\n\u2022 Actions\nActions\nCreateCluster\nThe following code example shows how to use CreateCluster.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.ExecuteCommandConfiguration;\nimport software.amazon.awssdk.services.ecs.model.ExecuteCommandLogging;\nimport software.amazon.awssdk.services.ecs.model.ClusterConfiguration;\nimport software.amazon.awssdk.services.ecs.model.CreateClusterResponse;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nAmazon ECS 1131\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.ecs.model.CreateClusterRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateCluster {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nclusterName - The name of the ECS cluster to create.", "mimetype": "text/plain", "start_char_idx": 1644261, "end_char_idx": 1648411, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "4c23e5cf-785e-4e75-959f-a41dc81992ea": {"__data__": {"id_": "4c23e5cf-785e-4e75-959f-a41dc81992ea", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "90306be2-4db1-4f7f-9fca-e47dd38b0f99", "node_type": "1", "metadata": {}, "hash": "30b7b2fbb402f5c472e2320f2edb42f8b754c6c3316e559591e8a5836039a523", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2a6c0c70-063d-49e3-9e03-a6f255017fc3", "node_type": "1", "metadata": {}, "hash": "2dba7694b487c1ce8cfa86b0d628f781ae9bfde321f3ee6388a63db47f5c57df", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateCluster {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n\\s\nWhere:\nclusterName - The name of the ECS cluster to create.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clusterName = args[0];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\nString clusterArn = createGivenCluster(ecsClient, clusterName);\nSystem.out.println(\"The cluster ARN is \" + clusterArn);\necsClient.close();\n}\npublic static String createGivenCluster(EcsClient ecsClient, String clusterName)\n{\ntry {\nExecuteCommandConfiguration commandConfiguration =\nExecuteCommandConfiguration.builder()\n.logging(ExecuteCommandLogging.DEFAULT)\n.build();\nActions 1132\nAWS SDK for Java 2.x Developer Guide for version 2.x\nClusterConfiguration clusterConfiguration =\nClusterConfiguration.builder()\n.executeCommandConfiguration(commandConfiguration)\n.build();\nCreateClusterRequest clusterRequest = CreateClusterRequest.builder()\n.clusterName(clusterName)\n.configuration(clusterConfiguration)\n.build();\nCreateClusterResponse response =\necsClient.createCluster(clusterRequest);\nreturn response.cluster().clusterArn();\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see CreateCluster in AWS SDK for Java 2.x API Reference.\nCreateService\nThe following code example shows how to use CreateService.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.AwsVpcConfiguration;\nimport software.amazon.awssdk.services.ecs.model.NetworkConfiguration;\nActions 1133\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport software.amazon.awssdk.services.ecs.model.CreateServiceRequest;\nimport software.amazon.awssdk.services.ecs.model.LaunchType;\nimport software.amazon.awssdk.services.ecs.model.CreateServiceResponse;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateService {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \n \nWhere:\nclusterName - The name of the ECS cluster.\nserviceName - The name of the ECS service to\ncreate.\nsecurityGroups - The name of the security group.\nsubnets - The name of the subnet.\ntaskDefinition - The name of the task definition.\n\"\"\";\nif (args.length != 5) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clusterName = args[0];\nString serviceName = args[1];\nString securityGroups = args[2];\nString subnets = args[3];\nString taskDefinition = args[4];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\nActions 1134\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString serviceArn = createNewService(ecsClient, clusterName,\nserviceName, securityGroups, subnets,\ntaskDefinition);\nSystem.out.println(\"The ARN of the service is \" + serviceArn);\necsClient.close();\n}\npublic static String createNewService(EcsClient ecsClient,\nString clusterName,\nString serviceName,\nString securityGroups,\nString subnets,\nString taskDefinition) {\ntry {\nAwsVpcConfiguration vpcConfiguration =\nAwsVpcConfiguration.builder()\n.securityGroups(securityGroups)\n.subnets(subnets)\n.build();\nNetworkConfiguration configuration =\nNetworkConfiguration.builder()\n.awsvpcConfiguration(vpcConfiguration)\n.build();\nCreateServiceRequest serviceRequest =\nCreateServiceRequest.builder()\n.cluster(clusterName)\n.networkConfiguration(configuration)\n.desiredCount(1)\n.launchType(LaunchType.FARGATE)\n.serviceName(serviceName)\n.taskDefinition(taskDefinition)\n.build();\nCreateServiceResponse response =\necsClient.createService(serviceRequest);\nreturn response.service().serviceArn();\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\nActions 1135\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see CreateService in AWS SDK for Java 2.x API Reference.", "mimetype": "text/plain", "start_char_idx": 1648081, "end_char_idx": 1652728, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2a6c0c70-063d-49e3-9e03-a6f255017fc3": {"__data__": {"id_": "2a6c0c70-063d-49e3-9e03-a6f255017fc3", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c23e5cf-785e-4e75-959f-a41dc81992ea", "node_type": "1", "metadata": {}, "hash": "1a7d3753080e14b0d94d441cfc495d2092709bc01df44e0aefa83ebb817eee33", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9f5793e6-e763-420c-9564-87e713fcbba6", "node_type": "1", "metadata": {}, "hash": "1a216695e75504ec1644114ada9190e2e385e6c3010bd616af1677eb83334f27", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteService\nThe following code example shows how to use DeleteService.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.DeleteServiceRequest;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteService {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nActions 1136\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWhere:\nclusterName - The name of the ECS cluster.\nserviceArn - The ARN of the ECS service.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clusterName = args[0];\nString serviceArn = args[1];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\ndeleteSpecificService(ecsClient, clusterName, serviceArn);\necsClient.close();\n}\npublic static void deleteSpecificService(EcsClient ecsClient, String\nclusterName, String serviceArn) {\ntry {\nDeleteServiceRequest serviceRequest = DeleteServiceRequest.builder()\n.cluster(clusterName)\n.service(serviceArn)\n.build();\necsClient.deleteService(serviceRequest);\nSystem.out.println(\"The Service was successfully deleted\");\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DeleteService in AWS SDK for Java 2.x API Reference.\nActions 1137\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeClusters\nThe following code example shows how to use DescribeClusters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.DescribeClustersRequest;\nimport software.amazon.awssdk.services.ecs.model.DescribeClustersResponse;\nimport software.amazon.awssdk.services.ecs.model.Cluster;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DescribeClusters {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nclusterArn - The ARN of the ECS cluster to describe.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nActions 1138\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString clusterArn = args[0];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\ndescCluster(ecsClient, clusterArn);\n}\npublic static void descCluster(EcsClient ecsClient, String clusterArn) {\ntry {\nDescribeClustersRequest clustersRequest =\nDescribeClustersRequest.builder()\n.clusters(clusterArn)\n.build();\nDescribeClustersResponse response =\necsClient.describeClusters(clustersRequest);\nList clusters = response.clusters();\nfor (Cluster cluster : clusters) {\nSystem.out.println(\"The cluster name is \" + cluster.clusterName());\n}\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DescribeClusters in AWS SDK for Java 2.x API Reference.\nDescribeTasks\nThe following code example shows how to use DescribeTasks.\nActions 1139\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.", "mimetype": "text/plain", "start_char_idx": 1652729, "end_char_idx": 1656880, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9f5793e6-e763-420c-9564-87e713fcbba6": {"__data__": {"id_": "9f5793e6-e763-420c-9564-87e713fcbba6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2a6c0c70-063d-49e3-9e03-a6f255017fc3", "node_type": "1", "metadata": {}, "hash": "2dba7694b487c1ce8cfa86b0d628f781ae9bfde321f3ee6388a63db47f5c57df", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b142807f-d90e-48e8-85c2-07fb5882001a", "node_type": "1", "metadata": {}, "hash": "0fd9f768598e0bcc1fb5d56201b8b9ae381b6f4c80dc442d2508d26b099feeda", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DescribeTasks\nThe following code example shows how to use DescribeTasks.\nActions 1139\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.DescribeTasksRequest;\nimport software.amazon.awssdk.services.ecs.model.DescribeTasksResponse;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nimport software.amazon.awssdk.services.ecs.model.Task;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListTaskDefinitions {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage:\n \\s\nWhere:\nclusterArn - The ARN of an ECS cluster.\ntaskId - The task Id value.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clusterArn = args[0];\nActions 1140\nAWS SDK for Java 2.x Developer Guide for version 2.x\nString taskId = args[1];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\ngetAllTasks(ecsClient, clusterArn, taskId);\necsClient.close();\n}\npublic static void getAllTasks(EcsClient ecsClient, String clusterArn, String\ntaskId) {\ntry {\nDescribeTasksRequest tasksRequest = DescribeTasksRequest.builder()\n.cluster(clusterArn)\n.tasks(taskId)\n.build();\nDescribeTasksResponse response = ecsClient.describeTasks(tasksRequest);\nList tasks = response.tasks();\nfor (Task task : tasks) {\nSystem.out.println(\"The task ARN is \" + task.taskDefinitionArn());\n}\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see DescribeTasks in AWS SDK for Java 2.x API Reference.\nListClusters\nThe following code example shows how to use ListClusters.\nActions 1141\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.ListClustersResponse;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListClusters {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\nlistAllClusters(ecsClient);\necsClient.close();\n}\npublic static void listAllClusters(EcsClient ecsClient) {\ntry {\nListClustersResponse response = ecsClient.listClusters();\nList clusters = response.clusterArns();\nfor (String cluster : clusters) {\nSystem.out.println(\"The cluster arn is \" + cluster);\n}\nActions 1142\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListClusters in AWS SDK for Java 2.x API Reference.\nUpdateService\nThe following code example shows how to use UpdateService.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nimport software.amazon.awssdk.services.ecs.model.UpdateServiceRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1656601, "end_char_idx": 1660783, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b142807f-d90e-48e8-85c2-07fb5882001a": {"__data__": {"id_": "b142807f-d90e-48e8-85c2-07fb5882001a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9f5793e6-e763-420c-9564-87e713fcbba6", "node_type": "1", "metadata": {}, "hash": "1a216695e75504ec1644114ada9190e2e385e6c3010bd616af1677eb83334f27", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f81b029b-27aa-4eb2-a5c3-9772012ead06", "node_type": "1", "metadata": {}, "hash": "4d6c7187cbabbbfef52baa4a98bd68aa2bf40d4a8a1a30318d8ba0dc584052a1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "UpdateService\nThe following code example shows how to use UpdateService.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.ecs.EcsClient;\nimport software.amazon.awssdk.services.ecs.model.EcsException;\nimport software.amazon.awssdk.services.ecs.model.UpdateServiceRequest;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class UpdateService {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nActions 1143\nAWS SDK for Java 2.x Developer Guide for version 2.x\nUsage:\n \\s\nWhere:\nclusterName - The cluster name.\nserviceArn - The service ARN value.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString clusterName = args[0];\nString serviceArn = args[1];\nRegion region = Region.US_EAST_1;\nEcsClient ecsClient = EcsClient.builder()\n.region(region)\n.build();\nupdateSpecificService(ecsClient, clusterName, serviceArn);\necsClient.close();\n}\npublic static void updateSpecificService(EcsClient ecsClient, String\nclusterName, String serviceArn) {\ntry {\nUpdateServiceRequest serviceRequest = UpdateServiceRequest.builder()\n.cluster(clusterName)\n.service(serviceArn)\n.desiredCount(0)\n.build();\necsClient.updateService(serviceRequest);\nSystem.out.println(\"The service was modified\");\n} catch (EcsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\nActions 1144\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see UpdateService in AWS SDK for Java 2.x API Reference.\nElastic Load Balancing - Version 2 examples using SDK for Java\n2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with Elastic Load Balancing - Version 2.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello Elastic Load Balancing\nThe following code examples show how to get started using Elastic Load Balancing.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\npublic class HelloLoadBalancer {\npublic static void main(String[] args) {\nElasticLoadBalancingV2Client loadBalancingV2Client =\nElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\nDescribeLoadBalancersResponse loadBalancersResponse =\nloadBalancingV2Client\nElastic Load Balancing - Version 2 1145\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.describeLoadBalancers(r -> r.pageSize(10));\nList loadBalancerList =\nloadBalancersResponse.loadBalancers();\nfor (LoadBalancer lb : loadBalancerList)\nSystem.out.println(\"Load Balancer DNS name = \" +\nlb.dnsName());\n}\n}\n\u2022 For API details, see DescribeLoadBalancers in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateListener\nThe following code example shows how to use CreateListener.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.", "mimetype": "text/plain", "start_char_idx": 1660221, "end_char_idx": 1664179, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f81b029b-27aa-4eb2-a5c3-9772012ead06": {"__data__": {"id_": "f81b029b-27aa-4eb2-a5c3-9772012ead06", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b142807f-d90e-48e8-85c2-07fb5882001a", "node_type": "1", "metadata": {}, "hash": "0fd9f768598e0bcc1fb5d56201b8b9ae381b6f4c80dc442d2508d26b099feeda", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8ed4c149-461b-41be-afa5-579527ee6ffc", "node_type": "1", "metadata": {}, "hash": "c5140ee047fb3b509c8d3989690c0fdcea2a862a5eb63c415a4ec40beaf7a2a4", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Topics\n\u2022 Actions\n\u2022 Scenarios\nActions\nCreateListener\nThe following code example shows how to use CreateListener.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.\n*/\npublic String createLoadBalancer(List subnetIds, String targetGroupARN,\nString lbName, int port,\nString protocol) {\ntry {\nList subnetIdStrings = subnetIds.stream()\nActions 1146\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.map(Subnet::subnetId)\n.collect(Collectors.toList());\nCreateLoadBalancerRequest balancerRequest =\nCreateLoadBalancerRequest.builder()\n.subnets(subnetIdStrings)\n.name(lbName)\n.scheme(\"internet-facing\")\n.build();\n// Create and wait for the load balancer to become available.\nCreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(lbARN)\n.build();\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\n// Get the DNS name (endpoint) of the load balancer.\nString lbDNSName = lsResponse.loadBalancers().get(0).dnsName();\nSystem.out.println(\"*** Load Balancer DNS Name: \" + lbDNSName);\n// Create a listener for the load balance.\nAction action = Action.builder()\n.targetGroupArn(targetGroupARN)\n.type(\"forward\")\n.build();\nCreateListenerRequest listenerRequest = CreateListenerRequest.builder()\n.loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())\n.defaultActions(action)\nActions 1147\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.port(port)\n.protocol(protocol)\n.defaultActions(action)\n.build();\ngetLoadBalancerClient().createListener(listenerRequest);\nSystem.out.println(\"Created listener to forward traffic from load\nbalancer \" + lbName + \" to target group \"\n+ targetGroupARN);\n// Return the load balancer DNS name.\nreturn lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateListener in AWS SDK for Java 2.x API Reference.\nCreateLoadBalancer\nThe following code example shows how to use CreateLoadBalancer.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.\n*/\npublic String createLoadBalancer(List subnetIds, String targetGroupARN,\nString lbName, int port,\nString protocol) {\nActions 1148\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\nList subnetIdStrings = subnetIds.stream()\n.map(Subnet::subnetId)\n.collect(Collectors.toList());\nCreateLoadBalancerRequest balancerRequest =\nCreateLoadBalancerRequest.builder()\n.subnets(subnetIdStrings)\n.name(lbName)\n.scheme(\"internet-facing\")\n.build();\n// Create and wait for the load balancer to become available.\nCreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(lbARN)\n.build();\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\n// Get the DNS name (endpoint) of the load balancer.", "mimetype": "text/plain", "start_char_idx": 1663785, "end_char_idx": 1668073, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "8ed4c149-461b-41be-afa5-579527ee6ffc": {"__data__": {"id_": "8ed4c149-461b-41be-afa5-579527ee6ffc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f81b029b-27aa-4eb2-a5c3-9772012ead06", "node_type": "1", "metadata": {}, "hash": "4d6c7187cbabbbfef52baa4a98bd68aa2bf40d4a8a1a30318d8ba0dc584052a1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca613011-ec7a-44a4-a455-2f43c590eeae", "node_type": "1", "metadata": {}, "hash": "e5b939cf7a2a57f2adc7f9be8b834005da201429aabeddfbabf1e260ec5a2d56", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "CreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(lbARN)\n.build();\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\n// Get the DNS name (endpoint) of the load balancer.\nString lbDNSName = lsResponse.loadBalancers().get(0).dnsName();\nSystem.out.println(\"*** Load Balancer DNS Name: \" + lbDNSName);\n// Create a listener for the load balance.\nAction action = Action.builder()\n.targetGroupArn(targetGroupARN)\n.type(\"forward\")\n.build();\nCreateListenerRequest listenerRequest = CreateListenerRequest.builder()\nActions 1149\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())\n.defaultActions(action)\n.port(port)\n.protocol(protocol)\n.defaultActions(action)\n.build();\ngetLoadBalancerClient().createListener(listenerRequest);\nSystem.out.println(\"Created listener to forward traffic from load\nbalancer \" + lbName + \" to target group \"\n+ targetGroupARN);\n// Return the load balancer DNS name.\nreturn lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n\u2022 For API details, see CreateLoadBalancer in AWS SDK for Java 2.x API Reference.\nCreateTargetGroup\nThe following code example shows how to use CreateTargetGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\nActions 1150\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* health is checked.\n*/\npublic String createTargetGroup(String protocol, int port, String vpcId, String\ntargetGroupName) {\nCreateTargetGroupRequest targetGroupRequest =\nCreateTargetGroupRequest.builder()\n.healthCheckPath(\"/healthcheck\")\n.healthCheckTimeoutSeconds(5)\n.port(port)\n.vpcId(vpcId)\n.name(targetGroupName)\n.protocol(protocol)\n.build();\nCreateTargetGroupResponse targetGroupResponse =\ngetLoadBalancerClient().createTargetGroup(targetGroupRequest);\nString targetGroupArn =\ntargetGroupResponse.targetGroups().get(0).targetGroupArn();\nString targetGroup =\ntargetGroupResponse.targetGroups().get(0).targetGroupName();\nSystem.out.println(\"The \" + targetGroup + \" was created with ARN\" +\ntargetGroupArn);\nreturn targetGroupArn;\n}\n\u2022 For API details, see CreateTargetGroup in AWS SDK for Java 2.x API Reference.\nDeleteLoadBalancer\nThe following code example shows how to use DeleteLoadBalancer.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Deletes a load balancer.\nActions 1151\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void deleteLoadBalancer(String lbName) {\ntry {\n// Use a waiter to delete the Load Balancer.\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())\n.build();\ngetLoadBalancerClient().deleteLoadBalancer(\nbuilder ->\nbuilder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancersDeleted(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(lbName + \" was deleted.\");\n}\n\u2022 For API details, see DeleteLoadBalancer in AWS SDK for Java 2.x API Reference.\nDeleteTargetGroup\nThe following code example shows how to use DeleteTargetGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub.", "mimetype": "text/plain", "start_char_idx": 1667312, "end_char_idx": 1671755, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ca613011-ec7a-44a4-a455-2f43c590eeae": {"__data__": {"id_": "ca613011-ec7a-44a4-a455-2f43c590eeae", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8ed4c149-461b-41be-afa5-579527ee6ffc", "node_type": "1", "metadata": {}, "hash": "c5140ee047fb3b509c8d3989690c0fdcea2a862a5eb63c415a4ec40beaf7a2a4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1a99b2c3-d7dd-4f09-bdab-ad95c3c0dfb4", "node_type": "1", "metadata": {}, "hash": "a2bba7cee949fd15ebfe200890b12172d28f13d56e15240f355b30972e19b2f1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n\u2022 For API details, see DeleteLoadBalancer in AWS SDK for Java 2.x API Reference.\nDeleteTargetGroup\nThe following code example shows how to use DeleteTargetGroup.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Deletes the target group.\nActions 1152\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic void deleteTargetGroup(String targetGroupName) {\ntry {\nDescribeTargetGroupsResponse res = getLoadBalancerClient()\n.describeTargetGroups(describe ->\ndescribe.names(targetGroupName));\ngetLoadBalancerClient()\n.deleteTargetGroup(builder ->\nbuilder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(targetGroupName + \" was deleted.\");\n}\n\u2022 For API details, see DeleteTargetGroup in AWS SDK for Java 2.x API Reference.\nDescribeTargetHealth\nThe following code example shows how to use DescribeTargetHealth.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n// Checks the health of the instances in the target group.\npublic List checkTargetHealth(String targetGroupName) {\nDescribeTargetGroupsRequest targetGroupsRequest =\nDescribeTargetGroupsRequest.builder()\n.names(targetGroupName)\n.build();\nDescribeTargetGroupsResponse tgResponse =\ngetLoadBalancerClient().describeTargetGroups(targetGroupsRequest);\nDescribeTargetHealthRequest healthRequest =\nDescribeTargetHealthRequest.builder()\nActions 1153\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())\n.build();\nDescribeTargetHealthResponse healthResponse =\ngetLoadBalancerClient().describeTargetHealth(healthRequest);\nreturn healthResponse.targetHealthDescriptions();\n}\n\u2022 For API details, see DescribeTargetHealth in AWS SDK for Java 2.x API Reference.\nScenarios\nBuild and manage a resilient service\nThe following code example shows how to create a load-balanced web service that returns book,\nmovie, and song recommendations. The example shows how the service responds to failures, and\nhow to restructure the service for more resilience when failures occur.\n\u2022 Use an Amazon EC2 Auto Scaling group to create Amazon Elastic Compute Cloud (Amazon EC2)\ninstances based on a launch template and to keep the number of instances in a specified range.\n\u2022 Handle and distribute HTTP requests with Elastic Load Balancing.\n\u2022 Monitor the health of instances in an Auto Scaling group and forward requests only to healthy\ninstances.\n\u2022 Run a Python web server on each EC2 instance to handle HTTP requests. The web server\nresponds with recommendations and health checks.\n\u2022 Simulate a recommendation service with an Amazon DynamoDB table.\n\u2022 Control web server response to requests and health checks by updating AWS Systems Manager\nparameters.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nScenarios 1154\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.\npublic static final String tableName = \"doc-example-recommendation-service\";\npublic static final String startScript = \"C:\\\\AWS\\\\resworkflow\\\n\\server_startup_script.sh\"; // Modify file location.\npublic static final String policyFile = \"C:\\\\AWS\\\\resworkflow\\\n\\instance_policy.json\"; // Modify file location.\npublic static final String ssmJSON = \"C:\\\\AWS\\\\resworkflow\\\n\\ssm_only_policy.json\"; // Modify file location.", "mimetype": "text/plain", "start_char_idx": 1671542, "end_char_idx": 1675341, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1a99b2c3-d7dd-4f09-bdab-ad95c3c0dfb4": {"__data__": {"id_": "1a99b2c3-d7dd-4f09-bdab-ad95c3c0dfb4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca613011-ec7a-44a4-a455-2f43c590eeae", "node_type": "1", "metadata": {}, "hash": "e5b939cf7a2a57f2adc7f9be8b834005da201429aabeddfbabf1e260ec5a2d56", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3e26e1ec-034f-43ea-bcca-8c9370a524ea", "node_type": "1", "metadata": {}, "hash": "077bb02f4156d447a005abbbea12c69468fb45466db8f77172d856a3d160992b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "SDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nScenarios 1154\nAWS SDK for Java 2.x Developer Guide for version 2.x\nRun the interactive scenario at a command prompt.\npublic class Main {\npublic static final String fileName = \"C:\\\\AWS\\\\resworkflow\\\n\\recommendations.json\"; // Modify file location.\npublic static final String tableName = \"doc-example-recommendation-service\";\npublic static final String startScript = \"C:\\\\AWS\\\\resworkflow\\\n\\server_startup_script.sh\"; // Modify file location.\npublic static final String policyFile = \"C:\\\\AWS\\\\resworkflow\\\n\\instance_policy.json\"; // Modify file location.\npublic static final String ssmJSON = \"C:\\\\AWS\\\\resworkflow\\\n\\ssm_only_policy.json\"; // Modify file location.\npublic static final String failureResponse = \"doc-example-resilient-\narchitecture-failure-response\";\npublic static final String healthCheck = \"doc-example-resilient-architecture-\nhealth-check\";\npublic static final String templateName = \"doc-example-resilience-template\";\npublic static final String roleName = \"doc-example-resilience-role\";\npublic static final String policyName = \"doc-example-resilience-pol\";\npublic static final String profileName = \"doc-example-resilience-prof\";\npublic static final String badCredsProfileName = \"doc-example-resilience-prof-\nbc\";\npublic static final String targetGroupName = \"doc-example-resilience-tg\";\npublic static final String autoScalingGroupName = \"doc-example-resilience-\ngroup\";\npublic static final String lbName = \"doc-example-resilience-lb\";\npublic static final String protocol = \"HTTP\";\npublic static final int port = 80;\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws IOException, InterruptedException\n{\nScanner in = new Scanner(System.in);\nDatabase database = new Database();\nAutoScaler autoScaler = new AutoScaler();\nLoadBalancer loadBalancer = new LoadBalancer();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the demonstration of How to Build and Manage\na Resilient Service!\");\nScenarios 1155\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"A - SETUP THE RESOURCES\");\nSystem.out.println(\"Press Enter when you're ready to start deploying\nresources.\");\nin.nextLine();\ndeploy(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"B - DEMO THE RESILIENCE FUNCTIONALITY\");\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\ndemo(loadBalancer);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"C - DELETE THE RESOURCES\");\nSystem.out.println(\"\"\"\nThis concludes the demo of how to build and manage a resilient\nservice.\nTo keep things tidy and to avoid unwanted charges on your account,\nwe can clean up all AWS resources\nthat were created for this demo.\n\"\"\");\nSystem.out.println(\"\\n Do you want to delete the resources (y/n)? \");\nString userInput = in.nextLine().trim().toLowerCase(); // Capture user input\nif (userInput.equals(\"y\")) {\n// Delete resources here\ndeleteResources(loadBalancer, autoScaler, database);\nSystem.out.println(\"Resources deleted.\");\n} else {\nSystem.out.println(\"\"\"\nOkay, we'll leave the resources intact.\nDon't forget to delete them when you're done with them or you\nmight incur unexpected charges.\n\"\"\");\n}\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"The example has completed. \");\nScenarios 1156\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"\\n Thanks for watching!\");\nSystem.out.println(DASHES);\n}\n// Deletes the AWS resources used in this example.\nprivate static void deleteResources(LoadBalancer loadBalancer, AutoScaler\nautoScaler, Database database)\nthrows IOException, InterruptedException {\nloadBalancer.deleteLoadBalancer(lbName);\nSystem.out.println(\"*** Wait 30 secs for resource to be deleted\");\nTimeUnit.SECONDS.sleep(30);\nloadBalancer.deleteTargetGroup(targetGroupName);\nautoScaler.deleteAutoScaleGroup(autoScalingGroupName);\nautoScaler.deleteRolesPolicies(policyName, roleName, profileName);\nautoScaler.deleteTemplate(templateName);\ndatabase.deleteTable(tableName);\n}\nprivate static void deploy(LoadBalancer loadBalancer) throws\nInterruptedException, IOException {\nScanner in = new Scanner(System.in);\nSystem.out.println(\n\"\"\"\nFor this demo, we'll use the AWS SDK for Java (v2) to create\nseveral AWS resources\nto set up a load-balanced web service endpoint and explore\nsome ways to make it resilient\nagainst various kinds of failures.", "mimetype": "text/plain", "start_char_idx": 1674538, "end_char_idx": 1679170, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3e26e1ec-034f-43ea-bcca-8c9370a524ea": {"__data__": {"id_": "3e26e1ec-034f-43ea-bcca-8c9370a524ea", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1a99b2c3-d7dd-4f09-bdab-ad95c3c0dfb4", "node_type": "1", "metadata": {}, "hash": "a2bba7cee949fd15ebfe200890b12172d28f13d56e15240f355b30972e19b2f1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6032c5f8-1a1f-41f6-9c30-b279bedafe8d", "node_type": "1", "metadata": {}, "hash": "a50eb17b202fff03fffff23fa51457348e3818b3b5b044a63f8cde10c0ca2fe2", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nSystem.out.println(DASHES);\n}\n// Deletes the AWS resources used in this example.\nprivate static void deleteResources(LoadBalancer loadBalancer, AutoScaler\nautoScaler, Database database)\nthrows IOException, InterruptedException {\nloadBalancer.deleteLoadBalancer(lbName);\nSystem.out.println(\"*** Wait 30 secs for resource to be deleted\");\nTimeUnit.SECONDS.sleep(30);\nloadBalancer.deleteTargetGroup(targetGroupName);\nautoScaler.deleteAutoScaleGroup(autoScalingGroupName);\nautoScaler.deleteRolesPolicies(policyName, roleName, profileName);\nautoScaler.deleteTemplate(templateName);\ndatabase.deleteTable(tableName);\n}\nprivate static void deploy(LoadBalancer loadBalancer) throws\nInterruptedException, IOException {\nScanner in = new Scanner(System.in);\nSystem.out.println(\n\"\"\"\nFor this demo, we'll use the AWS SDK for Java (v2) to create\nseveral AWS resources\nto set up a load-balanced web service endpoint and explore\nsome ways to make it resilient\nagainst various kinds of failures.\nSome of the resources create by this demo are:\n\\t* A DynamoDB table that the web service depends on to\nprovide book, movie, and song recommendations.\n\\t* An EC2 launch template that defines EC2 instances that\neach contain a Python web server.\n\\t* An EC2 Auto Scaling group that manages EC2 instances\nacross several Availability Zones.\n\\t* An Elastic Load Balancing (ELB) load balancer that\ntargets the Auto Scaling group to distribute requests.\n\"\"\");\nSystem.out.println(\"Press Enter when you're ready.\");\nin.nextLine();\nSystem.out.println(DASHES);\nScenarios 1157\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating and populating a DynamoDB table named \" +\ntableName);\nDatabase database = new Database();\ndatabase.createTable(tableName, fileName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an EC2 launch template that runs '{startup_script}' when an\ninstance starts.\nThis script starts a Python web server defined in the `server.py`\nscript. The web server\nlistens to HTTP requests on port 80 and responds to requests to '/'\nand to '/healthcheck'.\nFor demo purposes, this server is run as the root user. In\nproduction, the best practice is to\nrun a web server, such as Apache, with least-privileged credentials.\nThe template also defines an IAM policy that each instance uses to\nassume a role that grants\npermissions to access the DynamoDB recommendation table and Systems\nManager parameters\nthat control the flow of the demo.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\ntemplateCreator.createTemplate(policyFile, policyName, profileName,\nstartScript, templateName, roleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\n\"Creating an EC2 Auto Scaling group that maintains three EC2\ninstances, each in a different Availability Zone.\");\nSystem.out.println(\"*** Wait 30 secs for the VPC to be created\");\nTimeUnit.SECONDS.sleep(30);\nAutoScaler autoScaler = new AutoScaler();\nString[] zones = autoScaler.createGroup(3, templateName,\nautoScalingGroupName);\nSystem.out.println(\"\"\"\nAt this point, you have EC2 instances created. Once each instance\nstarts, it listens for\nScenarios 1158\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances. The load\nbalancer provides a\nsingle endpoint where clients connect and dispatches requests to\ninstances in the group.", "mimetype": "text/plain", "start_char_idx": 1678189, "end_char_idx": 1682157, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6032c5f8-1a1f-41f6-9c30-b279bedafe8d": {"__data__": {"id_": "6032c5f8-1a1f-41f6-9c30-b279bedafe8d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3e26e1ec-034f-43ea-bcca-8c9370a524ea", "node_type": "1", "metadata": {}, "hash": "077bb02f4156d447a005abbbea12c69468fb45466db8f77172d856a3d160992b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6fa5a00c-bc26-4032-83d3-aa34ca5a2d62", "node_type": "1", "metadata": {}, "hash": "1d1cb814d7f3b005ae3733eddecdc9dceb6d2c7538c6e3282488e0bf4a162b12", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Once each instance\nstarts, it listens for\nScenarios 1158\nAWS SDK for Java 2.x Developer Guide for version 2.x\nHTTP requests. You can see these instances in the console or\ncontinue with the demo.\nPress Enter when you're ready to continue.\n\"\"\");\nin.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"Creating variables that control the flow of the demo.\");\nParameterHelper paramHelper = new ParameterHelper();\nparamHelper.reset();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"\"\"\nCreating an Elastic Load Balancing target group and load balancer.\nThe target group\ndefines how the load balancer connects to instances. The load\nbalancer provides a\nsingle endpoint where clients connect and dispatches requests to\ninstances in the group.\n\"\"\");\nString vpcId = autoScaler.getDefaultVPC();\nList subnets = autoScaler.getSubnets(vpcId, zones);\nSystem.out.println(\"You have retrieved a list with \" + subnets.size() + \"\nsubnets\");\nString targetGroupArn = loadBalancer.createTargetGroup(protocol, port,\nvpcId, targetGroupName);\nString elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn,\nlbName, port, protocol);\nautoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName,\ntargetGroupArn);\nSystem.out.println(\"Verifying access to the load balancer endpoint...\");\nboolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);\nif (!wasSuccessul) {\nSystem.out.println(\"Couldn't connect to the load balancer, verifying\nthat the port is open...\");\nCloseableHttpClient httpClient = HttpClients.createDefault();\n// Create an HTTP GET request to \"http://checkip.amazonaws.com\"\nHttpGet httpGet = new HttpGet(\"http://checkip.amazonaws.com\");\ntry {\nScenarios 1159\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Execute the request and get the response\nHttpResponse response = httpClient.execute(httpGet);\n// Read the response content.\nString ipAddress =\nIOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();\n// Print the public IP address.\nSystem.out.println(\"Public IP Address: \" + ipAddress);\nGroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port,\nipAddress);\nif (!groupInfo.isPortOpen()) {\nSystem.out.println(\"\"\"\nFor this example to work, the default security group for\nyour default VPC must\nallow access from this computer. You can either add it\nautomatically from this\nexample or add it yourself using the AWS Management\nConsole.\n\"\"\");\nSystem.out.println(\n\"Do you want to add a rule to security group \" +\ngroupInfo.getGroupName() + \" to allow\");\nSystem.out.println(\"inbound traffic on port \" + port + \" from\nyour computer's IP address (y/n) \");\nString ans = in.nextLine();\nif (\"y\".equalsIgnoreCase(ans)) {\nautoScaler.openInboundPort(groupInfo.getGroupName(),\nString.valueOf(port), ipAddress);\nSystem.out.println(\"Security group rule added.\");\n} else {\nSystem.out.println(\"No security group rule added.\");\n}\n}\n} catch (AutoScalingException e) {\ne.printStackTrace();\n}\n} else if (wasSuccessul) {\nSystem.out.println(\"Your load balancer is ready. You can access it by\nbrowsing to:\");\nSystem.out.println(\"\\t http://\" + elbDnsName);\n} else {\nScenarios 1160\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Couldn't get a successful response from the load\nbalancer endpoint. Troubleshoot by\");\nSystem.out.println(\"manually verifying that your VPC and security group\nare configured correctly and that\");\nSystem.out.println(\"you can successfully make a GET request to the load\nbalancer.\");\n}\nSystem.out.println(\"Press Enter when you're ready to continue with the\ndemo.\");\nin.nextLine();\n}\n// A method that controls the demo part of the Java program.\npublic static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.", "mimetype": "text/plain", "start_char_idx": 1681358, "end_char_idx": 1685930, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6fa5a00c-bc26-4032-83d3-aa34ca5a2d62": {"__data__": {"id_": "6fa5a00c-bc26-4032-83d3-aa34ca5a2d62", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6032c5f8-1a1f-41f6-9c30-b279bedafe8d", "node_type": "1", "metadata": {}, "hash": "a50eb17b202fff03fffff23fa51457348e3818b3b5b044a63f8cde10c0ca2fe2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9bcceae0-5620-4491-8127-b665af9e55d2", "node_type": "1", "metadata": {}, "hash": "548126aa3a2852df6636424d29766e12d7d68813c94c24df25623f22c52c9b25", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nin.nextLine();\n}\n// A method that controls the demo part of the Java program.\npublic static void demo(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nParameterHelper paramHelper = new ParameterHelper();\nSystem.out.println(\"Read the ssm_only_policy.json file\");\nString ssmOnlyPolicy = readFileAsString(ssmJSON);\nSystem.out.println(\"Resetting parameters to starting values for demo.\");\nparamHelper.reset();\nSystem.out.println(\n\"\"\"\nThis part of the demonstration shows how to toggle\ndifferent parts of the system\nto create situations where the web service fails, and shows\nhow using a resilient\narchitecture can keep the web service running in spite of\nthese failures.\nAt the start, the load balancer endpoint returns\nrecommendations and reports that all targets are healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nThe web service running on the EC2 instances gets\nrecommendations by querying a DynamoDB table.\nThe table name is contained in a Systems Manager parameter\nnamed self.param_helper.table.\nScenarios 1161\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTo simulate a failure of the recommendation service, let's\nset this parameter to name a non-existent table.\n\"\"\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\nSystem.out.println(\n\"\"\"\n\\nNow, sending a GET request to the load balancer endpoint\nreturns a failure code. But, the service reports as\nhealthy to the load balancer because shallow health checks\ndon't check for failure of the recommendation service.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nInstead of failing when the recommendation service fails,\nthe web service can return a static response.\nWhile this is not a perfect solution, it presents the\ncustomer with a somewhat better experience than failure.\n\"\"\");\nparamHelper.put(paramHelper.failureResponse, \"static\");\nSystem.out.println(\"\"\"\nNow, sending a GET request to the load balancer endpoint returns a\nstatic response.\nThe service still reports as healthy because health checks are still\nshallow.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"Let's reinstate the recommendation service.\");\nparamHelper.put(paramHelper.tableName, paramHelper.dyntable);\nSystem.out.println(\"\"\"\nLet's also substitute bad credentials for one of the instances in\nthe target group so that it can't\naccess the DynamoDB recommendation table. We will get an instance id\nvalue.\n\"\"\");\nLaunchTemplateCreator templateCreator = new LaunchTemplateCreator();\nAutoScaler autoScaler = new AutoScaler();\nScenarios 1162\nAWS SDK for Java 2.x Developer Guide for version 2.x\n// Create a new instance profile based on badCredsProfileName.\ntemplateCreator.createInstanceProfile(policyFile, policyName,\nbadCredsProfileName, roleName);\nString badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);\nSystem.out.println(\"The bad instance id values used for this demo is \" +\nbadInstanceId);\nString profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);\nSystem.out.println(\"The association Id value is \" + profileAssociationId);\nSystem.out.println(\"Replacing the profile for instance \" + badInstanceId\n+ \" with a profile that contains bad credentials\");\nautoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName,\nprofileAssociationId);\nSystem.out.println(\n\"\"\"\nNow, sending a GET request to the load balancer endpoint\nreturns either a recommendation or a static response,\ndepending on which instance is selected by the load\nbalancer.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\"\"\"\nLet's implement a deep health check. For this demo, a deep health\ncheck tests whether\nthe web service can access the DynamoDB table that it depends on for\nrecommendations. Note that\nthe deep health check is only for ELB routing and not for Auto\nScaling instance health.\nThis kind of deep health check is not recommended for Auto Scaling\ninstance health, because it\nrisks accidental termination of all instances in the Auto Scaling\ngroup when a dependent service fails.\n\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nScenarios 1163\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.", "mimetype": "text/plain", "start_char_idx": 1684979, "end_char_idx": 1689651, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "9bcceae0-5620-4491-8127-b665af9e55d2": {"__data__": {"id_": "9bcceae0-5620-4491-8127-b665af9e55d2", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6fa5a00c-bc26-4032-83d3-aa34ca5a2d62", "node_type": "1", "metadata": {}, "hash": "1d1cb814d7f3b005ae3733eddecdc9dceb6d2c7538c6e3282488e0bf4a162b12", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b021559e-aa8c-4cf8-8a0d-242838d45681", "node_type": "1", "metadata": {}, "hash": "f041fc3f23a2e5191f19afc371fa614d09995a3407084163800afe1622c1212c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "This kind of deep health check is not recommended for Auto Scaling\ninstance health, because it\nrisks accidental termination of all instances in the Auto Scaling\ngroup when a dependent service fails.\n\"\"\");\nSystem.out.println(\"\"\"\nBy implementing deep health checks, the load balancer can detect\nwhen one of the instances is failing\nand take that instance out of rotation.\n\"\"\");\nparamHelper.put(paramHelper.healthCheck, \"deep\");\nScenarios 1163\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"\"\"\nNow, checking target health indicates that the instance with bad\ncredentials\nis unhealthy. Note that it might take a minute or two for the load\nbalancer to detect the unhealthy\ninstance. Sending a GET request to the load balancer endpoint always\nreturns a recommendation, because\nthe load balancer takes unhealthy instances out of its rotation.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"\"\"\nBecause the instances in this demo are controlled by an auto\nscaler, the simplest way to fix an unhealthy\ninstance is to terminate it and let the auto scaler start a\nnew instance to replace it.\n\"\"\");\nautoScaler.terminateInstance(badInstanceId);\nSystem.out.println(\"\"\"\nEven while the instance is terminating and the new instance is\nstarting, sending a GET\nrequest to the web service continues to get a successful\nrecommendation response because\nthe load balancer routes requests to the healthy instances. After\nthe replacement instance\nstarts and reports as healthy, it is included in the load balancing\nrotation.\nNote that terminating and replacing an instance typically takes\nseveral minutes, during which time you\ncan see the changing health check status until the new instance is\nrunning and healthy.\n\"\"\");\ndemoChoices(loadBalancer);\nSystem.out.println(\n\"If the recommendation service fails now, deep health checks mean\nall instances report as unhealthy.\");\nparamHelper.put(paramHelper.tableName, \"this-is-not-a-table\");\ndemoChoices(loadBalancer);\nScenarios 1164\nAWS SDK for Java 2.x Developer Guide for version 2.x\nparamHelper.reset();\n}\npublic static void demoChoices(LoadBalancer loadBalancer) throws IOException,\nInterruptedException {\nString[] actions = {\n\"Send a GET request to the load balancer endpoint.\",\n\"Check the health of load balancer targets.\",\n\"Go to the next part of the demo.\"\n};\nScanner scanner = new Scanner(System.in);\nwhile (true) {\nSystem.out.println(\"-\".repeat(88));\nSystem.out.println(\"See the current state of the service by selecting\none of the following choices:\");\nfor (int i = 0; i < actions.length; i++) {\nSystem.out.println(i + \": \" + actions[i]);\n}\ntry {\nSystem.out.print(\"\\nWhich action would you like to take? \");\nint choice = scanner.nextInt();\nSystem.out.println(\"-\".repeat(88));\nswitch (choice) {\ncase 0 -> {\nSystem.out.println(\"Request:\\n\");\nSystem.out.println(\"GET http://\" +\nloadBalancer.getEndpoint(lbName));\nCloseableHttpClient httpClient =\nHttpClients.createDefault();\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" +\nloadBalancer.getEndpoint(lbName));\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\n// Display the JSON response\nBufferedReader reader = new BufferedReader(\nScenarios 1165\nAWS SDK for Java 2.x Developer Guide for version 2.x\nnew\nInputStreamReader(response.getEntity().getContent()));\nStringBuilder jsonResponse = new StringBuilder();\nString line;\nwhile ((line = reader.readLine()) != null) {\njsonResponse.append(line);\n}\nreader.close();\n// Print the formatted JSON response.\nSystem.out.println(\"Full Response:\\n\");\nSystem.out.println(jsonResponse.toString());\n// Close the HTTP client.\nhttpClient.close();\n}\ncase 1 -> {\nSystem.out.println(\"\\nChecking the health of load balancer\ntargets:\\n\");\nList health =\nloadBalancer.checkTargetHealth(targetGroupName);\nfor (TargetHealthDescription target : health) {\nSystem.out.printf(\"\\tTarget %s on port %d is %s%n\",\ntarget.target().id(),\ntarget.target().port(),\ntarget.targetHealth().stateAsString());\n}\nSystem.out.println(\"\"\"\nNote that it can take a minute or two for the health\ncheck to update\nafter changes are made.\n\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nScenarios 1166\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Invalid input.", "mimetype": "text/plain", "start_char_idx": 1688790, "end_char_idx": 1693448, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b021559e-aa8c-4cf8-8a0d-242838d45681": {"__data__": {"id_": "b021559e-aa8c-4cf8-8a0d-242838d45681", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9bcceae0-5620-4491-8127-b665af9e55d2", "node_type": "1", "metadata": {}, "hash": "548126aa3a2852df6636424d29766e12d7d68813c94c24df25623f22c52c9b25", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "47f2cefa-e49e-47a9-aa74-ddeeae3c1c9b", "node_type": "1", "metadata": {}, "hash": "335b39caac5f71a8f27706030240f4ac3d3ead45128b9c3352a4b169f1258b59", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\n}\ncase 2 -> {\nSystem.out.println(\"\\nOkay, let's move on.\");\nSystem.out.println(\"-\".repeat(88));\nreturn; // Exit the method when choice is 2\n}\ndefault -> System.out.println(\"You must choose a value between\n0-2. Please select again.\");\n}\n} catch (java.util.InputMismatchException e) {\nScenarios 1166\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Invalid input. Please select again.\");\nscanner.nextLine(); // Clear the input buffer.\n}\n}\n}\npublic static String readFileAsString(String filePath) throws IOException {\nbyte[] bytes = Files.readAllBytes(Paths.get(filePath));\nreturn new String(bytes);\n}\n}\nCreate a class that wraps Auto Scaling and Amazon EC2 actions.\npublic class AutoScaler {\nprivate static Ec2Client ec2Client;\nprivate static AutoScalingClient autoScalingClient;\nprivate static IamClient iamClient;\nprivate static SsmClient ssmClient;\nprivate IamClient getIAMClient() {\nif (iamClient == null) {\niamClient = IamClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn iamClient;\n}\nprivate SsmClient getSSMClient() {\nif (ssmClient == null) {\nssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ssmClient;\n}\nprivate Ec2Client getEc2Client() {\nif (ec2Client == null) {\nScenarios 1167\nAWS SDK for Java 2.x Developer Guide for version 2.x\nec2Client = Ec2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn ec2Client;\n}\nprivate AutoScalingClient getAutoScalingClient() {\nif (autoScalingClient == null) {\nautoScalingClient = AutoScalingClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn autoScalingClient;\n}\n/**\n* Terminates and instances in an EC2 Auto Scaling group. After an instance is\n* terminated, it can no longer be accessed.\n*/\npublic void terminateInstance(String instanceId) {\nTerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest =\nTerminateInstanceInAutoScalingGroupRequest\n.builder()\n.instanceId(instanceId)\n.shouldDecrementDesiredCapacity(false)\n.build();\ngetAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);\nSystem.out.format(\"Terminated instance %s.\", instanceId);\n}\n/**\n* Replaces the profile associated with a running instance. After the profile is\n* replaced, the instance is rebooted to ensure that it uses the new profile.\n* When\n* the instance is ready, Systems Manager is used to restart the Python web\n* server.\n*/\npublic void replaceInstanceProfile(String instanceId, String\nnewInstanceProfileName, String profileAssociationId)\nthrows InterruptedException {\n// Create an IAM instance profile specification.\nScenarios 1168\nAWS SDK for Java 2.x Developer Guide for version 2.x\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\niamInstanceProfile =\nsoftware.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification\n.builder()\n.name(newInstanceProfileName) // Make sure 'newInstanceProfileName'\nis a valid IAM Instance Profile\n// name.\n.build();\n// Replace the IAM instance profile association for the EC2 instance.\nReplaceIamInstanceProfileAssociationRequest replaceRequest =\nReplaceIamInstanceProfileAssociationRequest\n.builder()\n.iamInstanceProfile(iamInstanceProfile)\n.associationId(profileAssociationId) // Make sure\n'profileAssociationId' is a valid association ID.\n.build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.", "mimetype": "text/plain", "start_char_idx": 1693057, "end_char_idx": 1697023, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "47f2cefa-e49e-47a9-aa74-ddeeae3c1c9b": {"__data__": {"id_": "47f2cefa-e49e-47a9-aa74-ddeeae3c1c9b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b021559e-aa8c-4cf8-8a0d-242838d45681", "node_type": "1", "metadata": {}, "hash": "f041fc3f23a2e5191f19afc371fa614d09995a3407084163800afe1622c1212c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3adda22e-608c-402a-96e1-04607bb8b80d", "node_type": "1", "metadata": {}, "hash": "c410263df57940d74fb41e73c0859bd1265ce1ff3cb9fc89c85f558afa30d54c", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": ".build();\ntry {\ngetEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);\n// Handle the response as needed.\n} catch (Ec2Exception e) {\n// Handle exceptions, log, or report the error.\nSystem.err.println(\"Error: \" + e.getMessage());\n}\nSystem.out.format(\"Replaced instance profile for association %s with profile\n%s.\", profileAssociationId,\nnewInstanceProfileName);\nTimeUnit.SECONDS.sleep(15);\nboolean instReady = false;\nint tries = 0;\n// Reboot after 60 seconds\nwhile (!instReady) {\nif (tries % 6 == 0) {\ngetEc2Client().rebootInstances(RebootInstancesRequest.builder()\n.instanceIds(instanceId)\n.build());\nSystem.out.println(\"Rebooting instance \" + instanceId + \" and\nwaiting for it to be ready.\");\n}\ntries++;\ntry {\nTimeUnit.SECONDS.sleep(10);\nScenarios 1169\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (InterruptedException e) {\ne.printStackTrace();\n}\nDescribeInstanceInformationResponse informationResponse =\ngetSSMClient().describeInstanceInformation();\nList instanceInformationList =\ninformationResponse.instanceInformationList();\nfor (InstanceInformation info : instanceInformationList) {\nif (info.instanceId().equals(instanceId)) {\ninstReady = true;\nbreak;\n}\n}\n}\nSendCommandRequest sendCommandRequest = SendCommandRequest.builder()\n.instanceIds(instanceId)\n.documentName(\"AWS-RunShellScript\")\n.parameters(Collections.singletonMap(\"commands\",\nCollections.singletonList(\"cd / && sudo python3 server.py\n80\")))\n.build();\ngetSSMClient().sendCommand(sendCommandRequest);\nSystem.out.println(\"Restarted the Python web server on instance \" +\ninstanceId + \".\");\n}\npublic void openInboundPort(String secGroupId, String port, String ipAddress) {\nAuthorizeSecurityGroupIngressRequest ingressRequest =\nAuthorizeSecurityGroupIngressRequest.builder()\n.groupName(secGroupId)\n.cidrIp(ipAddress)\n.fromPort(Integer.parseInt(port))\n.build();\ngetEc2Client().authorizeSecurityGroupIngress(ingressRequest);\nSystem.out.format(\"Authorized ingress to %s on port %s from %s.\",\nsecGroupId, port, ipAddress);\n}\n/**\n* Detaches a role from an instance profile, detaches policies from the role,\nScenarios 1170\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* and deletes all the resources.\n*/\npublic void deleteInstanceProfile(String roleName, String profileName) {\ntry {\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\ngetInstanceProfileRequest =\nsoftware.amazon.awssdk.services.iam.model.GetInstanceProfileRequest\n.builder()\n.instanceProfileName(profileName)\n.build();\nGetInstanceProfileResponse response =\ngetIAMClient().getInstanceProfile(getInstanceProfileRequest);\nString name = response.instanceProfile().instanceProfileName();\nSystem.out.println(name);\nRemoveRoleFromInstanceProfileRequest profileRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.roleName(roleName)\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(profileRequest);\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(profileName)\n.build();\ngetIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);\nSystem.out.println(\"Deleted instance profile \" + profileName);\nDeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()\n.roleName(roleName)\n.build();\n// List attached role policies.\nListAttachedRolePoliciesResponse rolesResponse = getIAMClient()\n.listAttachedRolePolicies(role -> role.roleName(roleName));\nList attachedPolicies =\nrolesResponse.attachedPolicies();\nfor (AttachedPolicy attachedPolicy : attachedPolicies) {\nDetachRolePolicyRequest request = DetachRolePolicyRequest.builder()\n.roleName(roleName)\n.policyArn(attachedPolicy.policyArn())\nScenarios 1171\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\ngetIAMClient().detachRolePolicy(request);\nSystem.out.println(\"Detached and deleted policy \" +\nattachedPolicy.policyName());\n}\ngetIAMClient().deleteRole(deleteRoleRequest);\nSystem.out.println(\"Instance profile and role deleted.\");\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address.", "mimetype": "text/plain", "start_char_idx": 1696320, "end_char_idx": 1701131, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3adda22e-608c-402a-96e1-04607bb8b80d": {"__data__": {"id_": "3adda22e-608c-402a-96e1-04607bb8b80d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "47f2cefa-e49e-47a9-aa74-ddeeae3c1c9b", "node_type": "1", "metadata": {}, "hash": "335b39caac5f71a8f27706030240f4ac3d3ead45128b9c3352a4b169f1258b59", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "72b25be8-34d3-4b5b-9c73-99ecde994fa5", "node_type": "1", "metadata": {}, "hash": "c8184e83771675a8d173f5bae335e94423a3780086ae6753fa6a5bf793f1bd28", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n} catch (IamException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\npublic void deleteTemplate(String templateName) {\ngetEc2Client().deleteLaunchTemplate(name ->\nname.launchTemplateName(templateName));\nSystem.out.format(templateName + \" was deleted.\");\n}\npublic void deleteAutoScaleGroup(String groupName) {\nDeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest =\nDeleteAutoScalingGroupRequest.builder()\n.autoScalingGroupName(groupName)\n.forceDelete(true)\n.build();\ngetAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);\nSystem.out.println(groupName + \" was deleted.\");\n}\n/*\n* Verify the default security group of the specified VPC allows ingress from\n* this\n* computer. This can be done by allowing ingress from this computer's IP\n* address. In some situations, such as connecting from a corporate network, you\n* must instead specify a prefix list ID. You can also temporarily open the port\n* to\n* any IP address while running this example. If you do, be sure to remove\n* public\n* access when you're done.\nScenarios 1172\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n*/\npublic GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {\nboolean portIsOpen = false;\nGroupInfo groupInfo = new GroupInfo();\ntry {\nFilter filter = Filter.builder()\n.name(\"group-name\")\n.values(\"default\")\n.build();\nFilter filter1 = Filter.builder()\n.name(\"vpc-id\")\n.values(VPC)\n.build();\nDescribeSecurityGroupsRequest securityGroupsRequest =\nDescribeSecurityGroupsRequest.builder()\n.filters(filter, filter1)\n.build();\nDescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()\n.describeSecurityGroups(securityGroupsRequest);\nString securityGroup =\nsecurityGroupsResponse.securityGroups().get(0).groupName();\ngroupInfo.setGroupName(securityGroup);\nfor (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {\nSystem.out.println(\"Found security group: \" + secGroup.groupId());\nfor (IpPermission ipPermission : secGroup.ipPermissions()) {\nif (ipPermission.fromPort() == port) {\nSystem.out.println(\"Found inbound rule: \" + ipPermission);\nfor (IpRange ipRange : ipPermission.ipRanges()) {\nString cidrIp = ipRange.cidrIp();\nif (cidrIp.startsWith(ipAddress) ||\ncidrIp.equals(\"0.0.0.0/0\")) {\nSystem.out.println(cidrIp + \" is applicable\");\nportIsOpen = true;\n}\n}\nif (!ipPermission.prefixListIds().isEmpty()) {\nSystem.out.println(\"Prefix lList is applicable\");\nScenarios 1173\nAWS SDK for Java 2.x Developer Guide for version 2.x\nportIsOpen = true;\n}\nif (!portIsOpen) {\nSystem.out\n.println(\"The inbound rule does not appear to be\nopen to either this computer's IP,\"\n+ \" all IP addresses (0.0.0.0/0), or to\na prefix list ID.\");\n} else {\nbreak;\n}\n}\n}\n}\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\ngroupInfo.setPortOpen(portIsOpen);\nreturn groupInfo;\n}\n/*\n* Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto\n* Scaling group.\n* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\nScenarios 1174\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\n// Get availability zones.", "mimetype": "text/plain", "start_char_idx": 1700341, "end_char_idx": 1704178, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "72b25be8-34d3-4b5b-9c73-99ecde994fa5": {"__data__": {"id_": "72b25be8-34d3-4b5b-9c73-99ecde994fa5", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3adda22e-608c-402a-96e1-04607bb8b80d", "node_type": "1", "metadata": {}, "hash": "c410263df57940d74fb41e73c0859bd1265ce1ff3cb9fc89c85f558afa30d54c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b54da3d0-0748-467f-844b-b8c96719a70e", "node_type": "1", "metadata": {}, "hash": "2218c3d8f7d3dd5120051563d8fc885522a167fb0272990be40867ac20544e37", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* The target group specifies how the load balancer forward requests to the\n* instances\n* in the group.\n*/\npublic void attachLoadBalancerTargetGroup(String asGroupName, String\ntargetGroupARN) {\ntry {\nAttachLoadBalancerTargetGroupsRequest targetGroupsRequest =\nAttachLoadBalancerTargetGroupsRequest.builder()\n.autoScalingGroupName(asGroupName)\n.targetGroupARNs(targetGroupARN)\n.build();\ngetAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);\nSystem.out.println(\"Attached load balancer to \" + asGroupName);\nScenarios 1174\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n// Creates an EC2 Auto Scaling group with the specified size.\npublic String[] createGroup(int groupSize, String templateName, String\nautoScalingGroupName) {\n// Get availability zones.\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\nzonesRequest =\nsoftware.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest\n.builder()\n.build();\nDescribeAvailabilityZonesResponse zonesResponse =\ngetEc2Client().describeAvailabilityZones(zonesRequest);\nList availabilityZoneNames =\nzonesResponse.availabilityZones().stream()\n.map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)\n.collect(Collectors.toList());\nString availabilityZones = String.join(\",\", availabilityZoneNames);\nLaunchTemplateSpecification specification =\nLaunchTemplateSpecification.builder()\n.launchTemplateName(templateName)\n.version(\"$Default\")\n.build();\nString[] zones = availabilityZones.split(\",\");\nCreateAutoScalingGroupRequest groupRequest =\nCreateAutoScalingGroupRequest.builder()\n.launchTemplate(specification)\n.availabilityZones(zones)\n.maxSize(groupSize)\n.minSize(groupSize)\n.autoScalingGroupName(autoScalingGroupName)\n.build();\ntry {\ngetAutoScalingClient().createAutoScalingGroup(groupRequest);\nScenarios 1175\nAWS SDK for Java 2.x Developer Guide for version 2.x\n} catch (AutoScalingException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nSystem.out.println(\"Created an EC2 Auto Scaling group named \" +\nautoScalingGroupName);\nreturn zones;\n}\npublic String getDefaultVPC() {\n// Define the filter.\nFilter defaultFilter = Filter.builder()\n.name(\"is-default\")\n.values(\"true\")\n.build();\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request =\nsoftware.amazon.awssdk.services.ec2.model.DescribeVpcsRequest\n.builder()\n.filters(defaultFilter)\n.build();\nDescribeVpcsResponse response = getEc2Client().describeVpcs(request);\nreturn response.vpcs().get(0).vpcId();\n}\n// Gets the default subnets in a VPC for a specified list of Availability Zones.\npublic List getSubnets(String vpcId, String[] availabilityZones) {\nList subnets = null;\nFilter vpcFilter = Filter.builder()\n.name(\"vpc-id\")\n.values(vpcId)\n.build();\nFilter azFilter = Filter.builder()\n.name(\"availability-zone\")\n.values(availabilityZones)\n.build();\nFilter defaultForAZ = Filter.builder()\n.name(\"default-for-az\")\n.values(\"true\")\n.build();\nScenarios 1176\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeSubnetsRequest request = DescribeSubnetsRequest.builder()\n.filters(vpcFilter, azFilter, defaultForAZ)\n.build();\nDescribeSubnetsResponse response = getEc2Client().describeSubnets(request);\nsubnets = response.subnets();\nreturn subnets;\n}\n// Gets data about the instances in the EC2 Auto Scaling group.\npublic String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.", "mimetype": "text/plain", "start_char_idx": 1703291, "end_char_idx": 1707500, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b54da3d0-0748-467f-844b-b8c96719a70e": {"__data__": {"id_": "b54da3d0-0748-467f-844b-b8c96719a70e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "72b25be8-34d3-4b5b-9c73-99ecde994fa5", "node_type": "1", "metadata": {}, "hash": "c8184e83771675a8d173f5bae335e94423a3780086ae6753fa6a5bf793f1bd28", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2cf0a685-df60-490f-8309-64ee903f634c", "node_type": "1", "metadata": {}, "hash": "f6581a327aac5ab3cd82e543fb1c18533735acfda361701da027836891dfa594", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "public String getBadInstance(String groupName) {\nDescribeAutoScalingGroupsRequest request =\nDescribeAutoScalingGroupsRequest.builder()\n.autoScalingGroupNames(groupName)\n.build();\nDescribeAutoScalingGroupsResponse response =\ngetAutoScalingClient().describeAutoScalingGroups(request);\nAutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);\nList instanceIds = autoScalingGroup.instances().stream()\n.map(instance -> instance.instanceId())\n.collect(Collectors.toList());\nString[] instanceIdArray = instanceIds.toArray(new String[0]);\nfor (String instanceId : instanceIdArray) {\nSystem.out.println(\"Instance ID: \" + instanceId);\nreturn instanceId;\n}\nreturn \"\";\n}\n// Gets data about the profile associated with an instance.\npublic String getInstanceProfile(String instanceId) {\nFilter filter = Filter.builder()\n.name(\"instance-id\")\n.values(instanceId)\n.build();\nDescribeIamInstanceProfileAssociationsRequest associationsRequest =\nDescribeIamInstanceProfileAssociationsRequest\n.builder()\n.filters(filter)\n.build();\nScenarios 1177\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeIamInstanceProfileAssociationsResponse response = getEc2Client()\n.describeIamInstanceProfileAssociations(associationsRequest);\nreturn response.iamInstanceProfileAssociations().get(0).associationId();\n}\npublic void deleteRolesPolicies(String policyName, String roleName, String\nInstanceProfile) {\nListPoliciesRequest listPoliciesRequest =\nListPoliciesRequest.builder().build();\nListPoliciesResponse listPoliciesResponse =\ngetIAMClient().listPolicies(listPoliciesRequest);\nfor (Policy policy : listPoliciesResponse.policies()) {\nif (policy.policyName().equals(policyName)) {\n// List the entities (users, groups, roles) that are attached to the\npolicy.\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\nlistEntitiesRequest =\nsoftware.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest\n.builder()\n.policyArn(policy.arn())\n.build();\nListEntitiesForPolicyResponse listEntitiesResponse = iamClient\n.listEntitiesForPolicy(listEntitiesRequest);\nif (!listEntitiesResponse.policyGroups().isEmpty() || !\nlistEntitiesResponse.policyUsers().isEmpty()\n|| !listEntitiesResponse.policyRoles().isEmpty()) {\n// Detach the policy from any entities it is attached to.\nDetachRolePolicyRequest detachPolicyRequest =\nDetachRolePolicyRequest.builder()\n.policyArn(policy.arn())\n.roleName(roleName) // Specify the name of the IAM role\n.build();\ngetIAMClient().detachRolePolicy(detachPolicyRequest);\nSystem.out.println(\"Policy detached from entities.\");\n}\n// Now, you can delete the policy.\nDeletePolicyRequest deletePolicyRequest =\nDeletePolicyRequest.builder()\n.policyArn(policy.arn())\n.build();\nScenarios 1178\nAWS SDK for Java 2.x Developer Guide for version 2.x\ngetIAMClient().deletePolicy(deletePolicyRequest);\nSystem.out.println(\"Policy deleted successfully.\");\nbreak;\n}\n}\n// List the roles associated with the instance profile\nListInstanceProfilesForRoleRequest listRolesRequest =\nListInstanceProfilesForRoleRequest.builder()\n.roleName(roleName)\n.build();\n// Detach the roles from the instance profile\nListInstanceProfilesForRoleResponse listRolesResponse =\niamClient.listInstanceProfilesForRole(listRolesRequest);\nfor (software.amazon.awssdk.services.iam.model.InstanceProfile profile :\nlistRolesResponse.instanceProfiles()) {\nRemoveRoleFromInstanceProfileRequest removeRoleRequest =\nRemoveRoleFromInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.roleName(roleName) // Remove the extra dot here\n.build();\ngetIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);\nSystem.out.println(\"Role \" + roleName + \" removed from instance profile\n\" + InstanceProfile);\n}\n// Delete the instance profile after removing all roles\nDeleteInstanceProfileRequest deleteInstanceProfileRequest =\nDeleteInstanceProfileRequest.builder()\n.instanceProfileName(InstanceProfile)\n.build();\ngetIAMClient().deleteInstanceProfile(r ->\nr.instanceProfileName(InstanceProfile));\nSystem.out.println(InstanceProfile + \" Deleted\");\nSystem.out.println(\"All roles and policies are deleted.\");\n}\n}\nScenarios 1179\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.", "mimetype": "text/plain", "start_char_idx": 1706758, "end_char_idx": 1711398, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "2cf0a685-df60-490f-8309-64ee903f634c": {"__data__": {"id_": "2cf0a685-df60-490f-8309-64ee903f634c", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b54da3d0-0748-467f-844b-b8c96719a70e", "node_type": "1", "metadata": {}, "hash": "2218c3d8f7d3dd5120051563d8fc885522a167fb0272990be40867ac20544e37", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a3d5b7b9-79d3-42bd-99d5-16c1e1cd568b", "node_type": "1", "metadata": {}, "hash": "d0fb02f5f134a9b9cc038accfee8d805919dfd14ef993fb50a2829e378fb5a6e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\n}\n}\nScenarios 1179\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that wraps Elastic Load Balancing actions.\npublic class LoadBalancer {\npublic ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;\npublic ElasticLoadBalancingV2Client getLoadBalancerClient() {\nif (elasticLoadBalancingV2Client == null) {\nelasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn elasticLoadBalancingV2Client;\n}\n// Checks the health of the instances in the target group.\npublic List checkTargetHealth(String targetGroupName) {\nDescribeTargetGroupsRequest targetGroupsRequest =\nDescribeTargetGroupsRequest.builder()\n.names(targetGroupName)\n.build();\nDescribeTargetGroupsResponse tgResponse =\ngetLoadBalancerClient().describeTargetGroups(targetGroupsRequest);\nDescribeTargetHealthRequest healthRequest =\nDescribeTargetHealthRequest.builder()\n.targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())\n.build();\nDescribeTargetHealthResponse healthResponse =\ngetLoadBalancerClient().describeTargetHealth(healthRequest);\nreturn healthResponse.targetHealthDescriptions();\n}\n// Gets the HTTP endpoint of the load balancer.\npublic String getEndpoint(String lbName) {\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nreturn res.loadBalancers().get(0).dnsName();\n}\n// Deletes a load balancer.\npublic void deleteLoadBalancer(String lbName) {\nScenarios 1180\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntry {\n// Use a waiter to delete the Load Balancer.\nDescribeLoadBalancersResponse res = getLoadBalancerClient()\n.describeLoadBalancers(describe -> describe.names(lbName));\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\n.loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())\n.build();\ngetLoadBalancerClient().deleteLoadBalancer(\nbuilder ->\nbuilder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancersDeleted(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(lbName + \" was deleted.\");\n}\n// Deletes the target group.\npublic void deleteTargetGroup(String targetGroupName) {\ntry {\nDescribeTargetGroupsResponse res = getLoadBalancerClient()\n.describeTargetGroups(describe ->\ndescribe.names(targetGroupName));\ngetLoadBalancerClient()\n.deleteTargetGroup(builder ->\nbuilder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));\n} catch (ElasticLoadBalancingV2Exception e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\n}\nSystem.out.println(targetGroupName + \" was deleted.\");\n}\n// Verify this computer can successfully send a GET request to the load balancer\n// endpoint.\npublic boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException,\nInterruptedException {\nScenarios 1181\nAWS SDK for Java 2.x Developer Guide for version 2.x\nboolean success = false;\nint retries = 3;\nCloseableHttpClient httpClient = HttpClients.createDefault();\n// Create an HTTP GET request to the ELB.\nHttpGet httpGet = new HttpGet(\"http://\" + elbDnsName);\ntry {\nwhile ((!success) && (retries > 0)) {\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.", "mimetype": "text/plain", "start_char_idx": 1710859, "end_char_idx": 1715055, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a3d5b7b9-79d3-42bd-99d5-16c1e1cd568b": {"__data__": {"id_": "a3d5b7b9-79d3-42bd-99d5-16c1e1cd568b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2cf0a685-df60-490f-8309-64ee903f634c", "node_type": "1", "metadata": {}, "hash": "f6581a327aac5ab3cd82e543fb1c18533735acfda361701da027836891dfa594", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "86e1e508-7388-4aad-a310-fd55a65635fc", "node_type": "1", "metadata": {}, "hash": "d8a09a313a75118a865fb3867e988b8ec0bc30c64b025fe6f635010e80b261ee", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "HttpGet httpGet = new HttpGet(\"http://\" + elbDnsName);\ntry {\nwhile ((!success) && (retries > 0)) {\n// Execute the request and get the response.\nHttpResponse response = httpClient.execute(httpGet);\nint statusCode = response.getStatusLine().getStatusCode();\nSystem.out.println(\"HTTP Status Code: \" + statusCode);\nif (statusCode == 200) {\nsuccess = true;\n} else {\nretries--;\nSystem.out.println(\"Got connection error from load balancer\nendpoint, retrying...\");\nTimeUnit.SECONDS.sleep(15);\n}\n}\n} catch (org.apache.http.conn.HttpHostConnectException e) {\nSystem.out.println(e.getMessage());\n}\nSystem.out.println(\"Status..\" + success);\nreturn success;\n}\n/*\n* Creates an Elastic Load Balancing target group. The target group specifies\n* how\n* the load balancer forward requests to instances in the group and how instance\n* health is checked.\n*/\npublic String createTargetGroup(String protocol, int port, String vpcId, String\ntargetGroupName) {\nCreateTargetGroupRequest targetGroupRequest =\nCreateTargetGroupRequest.builder()\n.healthCheckPath(\"/healthcheck\")\n.healthCheckTimeoutSeconds(5)\n.port(port)\n.vpcId(vpcId)\nScenarios 1182\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.name(targetGroupName)\n.protocol(protocol)\n.build();\nCreateTargetGroupResponse targetGroupResponse =\ngetLoadBalancerClient().createTargetGroup(targetGroupRequest);\nString targetGroupArn =\ntargetGroupResponse.targetGroups().get(0).targetGroupArn();\nString targetGroup =\ntargetGroupResponse.targetGroups().get(0).targetGroupName();\nSystem.out.println(\"The \" + targetGroup + \" was created with ARN\" +\ntargetGroupArn);\nreturn targetGroupArn;\n}\n/*\n* Creates an Elastic Load Balancing load balancer that uses the specified\n* subnets\n* and forwards requests to the specified target group.\n*/\npublic String createLoadBalancer(List subnetIds, String targetGroupARN,\nString lbName, int port,\nString protocol) {\ntry {\nList subnetIdStrings = subnetIds.stream()\n.map(Subnet::subnetId)\n.collect(Collectors.toList());\nCreateLoadBalancerRequest balancerRequest =\nCreateLoadBalancerRequest.builder()\n.subnets(subnetIdStrings)\n.name(lbName)\n.scheme(\"internet-facing\")\n.build();\n// Create and wait for the load balancer to become available.\nCreateLoadBalancerResponse lsResponse =\ngetLoadBalancerClient().createLoadBalancer(balancerRequest);\nString lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();\nElasticLoadBalancingV2Waiter loadBalancerWaiter =\ngetLoadBalancerClient().waiter();\nDescribeLoadBalancersRequest request =\nDescribeLoadBalancersRequest.builder()\nScenarios 1183\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.loadBalancerArns(lbARN)\n.build();\nSystem.out.println(\"Waiting for Load Balancer \" + lbName + \" to become\navailable.\");\nWaiterResponse waiterResponse =\nloadBalancerWaiter\n.waitUntilLoadBalancerAvailable(request);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Load Balancer \" + lbName + \" is available.\");\n// Get the DNS name (endpoint) of the load balancer.\nString lbDNSName = lsResponse.loadBalancers().get(0).dnsName();\nSystem.out.println(\"*** Load Balancer DNS Name: \" + lbDNSName);\n// Create a listener for the load balance.\nAction action = Action.builder()\n.targetGroupArn(targetGroupARN)\n.type(\"forward\")\n.build();\nCreateListenerRequest listenerRequest = CreateListenerRequest.builder()\n.loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())\n.defaultActions(action)\n.port(port)\n.protocol(protocol)\n.defaultActions(action)\n.build();\ngetLoadBalancerClient().createListener(listenerRequest);\nSystem.out.println(\"Created listener to forward traffic from load\nbalancer \" + lbName + \" to target group \"\n+ targetGroupARN);\n// Return the load balancer DNS name.\nreturn lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nScenarios 1184\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.", "mimetype": "text/plain", "start_char_idx": 1714222, "end_char_idx": 1718637, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "86e1e508-7388-4aad-a310-fd55a65635fc": {"__data__": {"id_": "86e1e508-7388-4aad-a310-fd55a65635fc", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a3d5b7b9-79d3-42bd-99d5-16c1e1cd568b", "node_type": "1", "metadata": {}, "hash": "d0fb02f5f134a9b9cc038accfee8d805919dfd14ef993fb50a2829e378fb5a6e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "822d9bee-e135-445e-99f8-de521a2ffd22", "node_type": "1", "metadata": {}, "hash": "bbec4638142cce537deb2605dfb38fb1b88199dee19035e289ffda9a9c70fd96", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "return lbDNSName;\n} catch (ElasticLoadBalancingV2Exception e) {\ne.printStackTrace();\n}\nreturn \"\";\n}\n}\nScenarios 1184\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCreate a class that uses DynamoDB to simulate a recommendation service.\npublic class Database {\nprivate static DynamoDbClient dynamoDbClient;\npublic static DynamoDbClient getDynamoDbClient() {\nif (dynamoDbClient == null) {\ndynamoDbClient = DynamoDbClient.builder()\n.region(Region.US_EAST_1)\n.build();\n}\nreturn dynamoDbClient;\n}\n// Checks to see if the Amazon DynamoDB table exists.\nprivate boolean doesTableExist(String tableName) {\ntry {\n// Describe the table and catch any exceptions.\nDescribeTableRequest describeTableRequest =\nDescribeTableRequest.builder()\n.tableName(tableName)\n.build();\ngetDynamoDbClient().describeTable(describeTableRequest);\nSystem.out.println(\"Table '\" + tableName + \"' exists.\");\nreturn true;\n} catch (ResourceNotFoundException e) {\nSystem.out.println(\"Table '\" + tableName + \"' does not exist.\");\n} catch (DynamoDbException e) {\nSystem.err.println(\"Error checking table existence: \" + e.getMessage());\n}\nreturn false;\n}\n/*\n* Creates a DynamoDB table to use a recommendation service. The table has a\n* hash key named 'MediaType' that defines the type of media recommended, such\n* as\n* Book or Movie, and a range key named 'ItemId' that, combined with the\nScenarios 1185\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* MediaType,\n* forms a unique identifier for the recommended item.\n*/\npublic void createTable(String tableName, String fileName) throws IOException {\n// First check to see if the table exists.\nboolean doesExist = doesTableExist(tableName);\nif (!doesExist) {\nDynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();\nCreateTableRequest createTableRequest = CreateTableRequest.builder()\n.tableName(tableName)\n.attributeDefinitions(\nAttributeDefinition.builder()\n.attributeName(\"MediaType\")\n.attributeType(ScalarAttributeType.S)\n.build(),\nAttributeDefinition.builder()\n.attributeName(\"ItemId\")\n.attributeType(ScalarAttributeType.N)\n.build())\n.keySchema(\nKeySchemaElement.builder()\n.attributeName(\"MediaType\")\n.keyType(KeyType.HASH)\n.build(),\nKeySchemaElement.builder()\n.attributeName(\"ItemId\")\n.keyType(KeyType.RANGE)\n.build())\n.provisionedThroughput(\nProvisionedThroughput.builder()\n.readCapacityUnits(5L)\n.writeCapacityUnits(5L)\n.build())\n.build();\ngetDynamoDbClient().createTable(createTableRequest);\nSystem.out.println(\"Creating table \" + tableName + \"...\");\n// Wait until the Amazon DynamoDB table is created.\nDescribeTableRequest tableRequest = DescribeTableRequest.builder()\n.tableName(tableName)\n.build();\nScenarios 1186\nAWS SDK for Java 2.x Developer Guide for version 2.x\nWaiterResponse waiterResponse =\ndbWaiter.waitUntilTableExists(tableRequest);\nwaiterResponse.matched().response().ifPresent(System.out::println);\nSystem.out.println(\"Table \" + tableName + \" created.\");\n// Add records to the table.\npopulateTable(fileName, tableName);\n}\n}\npublic void deleteTable(String tableName) {\ngetDynamoDbClient().deleteTable(table -> table.tableName(tableName));\nSystem.out.println(\"Table \" + tableName + \" deleted.\");\n}\n// Populates the table with data located in a JSON file using the DynamoDB\n// enhanced client.\npublic void populateTable(String fileName, String tableName) throws IOException\n{\nDynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()\n.dynamoDbClient(getDynamoDbClient())\n.build();\nObjectMapper objectMapper = new ObjectMapper();\nFile jsonFile = new File(fileName);\nJsonNode rootNode = objectMapper.readTree(jsonFile);\nDynamoDbTable mappedTable = enhancedClient.table(tableName,\nTableSchema.fromBean(Recommendation.class));\nfor (JsonNode currentNode : rootNode) {\nString mediaType = currentNode.path(\"MediaType\").path(\"S\").asText();\nint itemId = currentNode.path(\"ItemId\").path(\"N\").asInt();\nString title = currentNode.path(\"Title\").path(\"S\").asText();\nString creator = currentNode.path(\"Creator\").path(\"S\").asText();\n// Create a Recommendation object and set its properties.\nRecommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nScenarios 1187\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nCreate a class that wraps Systems Manager actions.", "mimetype": "text/plain", "start_char_idx": 1717981, "end_char_idx": 1722483, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "822d9bee-e135-445e-99f8-de521a2ffd22": {"__data__": {"id_": "822d9bee-e135-445e-99f8-de521a2ffd22", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "86e1e508-7388-4aad-a310-fd55a65635fc", "node_type": "1", "metadata": {}, "hash": "d8a09a313a75118a865fb3867e988b8ec0bc30c64b025fe6f635010e80b261ee", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e2862153-ffaa-49b5-8c17-344ffe23adc6", "node_type": "1", "metadata": {}, "hash": "145cd6515d0d0faaf15c1a3952739e653a7b3a43743e41697635d048ad83f414", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Recommendation rec = new Recommendation();\nrec.setMediaType(mediaType);\nrec.setItemId(itemId);\nrec.setTitle(title);\nrec.setCreator(creator);\n// Put the item into the DynamoDB table.\nmappedTable.putItem(rec); // Add the Recommendation to the list.\n}\nScenarios 1187\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\"Added all records to the \" + tableName);\n}\n}\nCreate a class that wraps Systems Manager actions.\npublic class ParameterHelper {\nString tableName = \"doc-example-resilient-architecture-table\";\nString dyntable = \"doc-example-recommendation-service\";\nString failureResponse = \"doc-example-resilient-architecture-failure-response\";\nString healthCheck = \"doc-example-resilient-architecture-health-check\";\npublic void reset() {\nput(dyntable, tableName);\nput(failureResponse, \"none\");\nput(healthCheck, \"shallow\");\n}\npublic void put(String name, String value) {\nSsmClient ssmClient = SsmClient.builder()\n.region(Region.US_EAST_1)\n.build();\nPutParameterRequest parameterRequest = PutParameterRequest.builder()\n.name(name)\n.value(value)\n.overwrite(true)\n.type(\"String\")\n.build();\nssmClient.putParameter(parameterRequest);\nSystem.out.printf(\"Setting demo parameter %s to '%s'.\", name, value);\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 AttachLoadBalancerTargetGroups\n\u2022 CreateAutoScalingGroup\n\u2022 CreateInstanceProfile\nScenarios 1188\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 CreateLaunchTemplate\n\u2022 CreateListener\n\u2022 CreateLoadBalancer\n\u2022 CreateTargetGroup\n\u2022 DeleteAutoScalingGroup\n\u2022 DeleteInstanceProfile\n\u2022 DeleteLaunchTemplate\n\u2022 DeleteLoadBalancer\n\u2022 DeleteTargetGroup\n\u2022 DescribeAutoScalingGroups\n\u2022 DescribeAvailabilityZones\n\u2022 DescribeIamInstanceProfileAssociations\n\u2022 DescribeInstances\n\u2022 DescribeLoadBalancers\n\u2022 DescribeSubnets\n\u2022 DescribeTargetGroups\n\u2022 DescribeTargetHealth\n\u2022 DescribeVpcs\n\u2022 RebootInstances\n\u2022 ReplaceIamInstanceProfileAssociation\n\u2022 TerminateInstanceInAutoScalingGroup\n\u2022 UpdateAutoScalingGroup\nMediaStore examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with MediaStore.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nMediaStore 1189\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTopics\n\u2022 Actions\nActions\nCreateContainer\nThe following code example shows how to use CreateContainer.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateContainer {\npublic static long sleepTime = 10;\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncontainerName - The name of the container to create.", "mimetype": "text/plain", "start_char_idx": 1722051, "end_char_idx": 1725705, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e2862153-ffaa-49b5-8c17-344ffe23adc6": {"__data__": {"id_": "e2862153-ffaa-49b5-8c17-344ffe23adc6", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "822d9bee-e135-445e-99f8-de521a2ffd22", "node_type": "1", "metadata": {}, "hash": "bbec4638142cce537deb2605dfb38fb1b88199dee19035e289ffda9a9c70fd96", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "52be1aa0-b2ce-49b8-86aa-e6dbf83fd121", "node_type": "1", "metadata": {}, "hash": "79cfc81b4d63814897113eb2cb64ddb78f24dc46f5bc9edcbbf6db470992c2a9", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateContainer {\npublic static long sleepTime = 10;\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncontainerName - The name of the container to create.\nActions 1190\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString containerName = args[0];\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\ncreateMediaContainer(mediaStoreClient, containerName);\nmediaStoreClient.close();\n}\npublic static void createMediaContainer(MediaStoreClient mediaStoreClient,\nString containerName) {\ntry {\nCreateContainerRequest containerRequest =\nCreateContainerRequest.builder()\n.containerName(containerName)\n.build();\nCreateContainerResponse containerResponse =\nmediaStoreClient.createContainer(containerRequest);\nString status = containerResponse.container().status().toString();\nwhile (!status.equalsIgnoreCase(\"Active\")) {\nstatus = DescribeContainer.checkContainer(mediaStoreClient,\ncontainerName);\nSystem.out.println(\"Status - \" + status);\nThread.sleep(sleepTime * 1000);\n}\nSystem.out.println(\"The container ARN value is \" +\ncontainerResponse.container().arn());\nSystem.out.println(\"Finished \");\n} catch (MediaStoreException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nActions 1191\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\n\u2022 For API details, see CreateContainer in AWS SDK for Java 2.x API Reference.\nDeleteContainer\nThe following code example shows how to use DeleteContainer.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.CreateContainerResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class CreateContainer {\npublic static long sleepTime = 10;\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncontainerName - The name of the container to create.\n\"\"\";\nActions 1192\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString containerName = args[0];\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\ncreateMediaContainer(mediaStoreClient, containerName);\nmediaStoreClient.close();\n}\npublic static void createMediaContainer(MediaStoreClient mediaStoreClient,\nString containerName) {\ntry {\nCreateContainerRequest containerRequest =\nCreateContainerRequest.builder()\n.containerName(containerName)\n.build();\nCreateContainerResponse containerResponse =\nmediaStoreClient.createContainer(containerRequest);\nString status = containerResponse.container().status().toString();\nwhile (!status.equalsIgnoreCase(\"Active\")) {\nstatus = DescribeContainer.checkContainer(mediaStoreClient,\ncontainerName);\nSystem.out.println(\"Status - \" + status);\nThread.sleep(sleepTime * 1000);\n}\nSystem.out.println(\"The container ARN value is \" +\ncontainerResponse.container().arn());\nSystem.out.println(\"Finished \");\n} catch (MediaStoreException | InterruptedException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\n}\nActions 1193\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see DeleteContainer in AWS SDK for Java 2.x API Reference.\nDeleteObject\nThe following code example shows how to use DeleteObject.", "mimetype": "text/plain", "start_char_idx": 1724776, "end_char_idx": 1729507, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "52be1aa0-b2ce-49b8-86aa-e6dbf83fd121": {"__data__": {"id_": "52be1aa0-b2ce-49b8-86aa-e6dbf83fd121", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e2862153-ffaa-49b5-8c17-344ffe23adc6", "node_type": "1", "metadata": {}, "hash": "145cd6515d0d0faaf15c1a3952739e653a7b3a43743e41697635d048ad83f414", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7c566499-a1be-4b6a-afb9-284f0d89c899", "node_type": "1", "metadata": {}, "hash": "1eae5dbf7c49ec785ef3cecb2ab512a7d30d95e3ae4b359fc1f3e4718fd40171", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteObject\nThe following code example shows how to use DeleteObject.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;\nimport software.amazon.awssdk.services.mediastoredata.model.DeleteObjectRequest;\nimport software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class DeleteObject {\npublic static void main(String[] args) throws URISyntaxException {\nfinal String usage = \"\"\"\nUsage: \nWhere:\nActions 1194\nAWS SDK for Java 2.x Developer Guide for version 2.x\ncompletePath - The path (including the container) of the item to\ndelete.\ncontainerName - The name of the container.\n\"\"\";\nif (args.length != 2) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString completePath = args[0];\nString containerName = args[1];\nRegion region = Region.US_EAST_1;\nURI uri = new URI(getEndpoint(containerName));\nMediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()\n.endpointOverride(uri)\n.region(region)\n.build();\ndeleteMediaObject(mediaStoreData, completePath);\nmediaStoreData.close();\n}\npublic static void deleteMediaObject(MediaStoreDataClient mediaStoreData, String\ncompletePath) {\ntry {\nDeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()\n.path(completePath)\n.build();\nmediaStoreData.deleteObject(deleteObjectRequest);\n} catch (MediaStoreDataException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nprivate static String getEndpoint(String containerName) {\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\nActions 1195\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeContainerRequest containerRequest =\nDescribeContainerRequest.builder()\n.containerName(containerName)\n.build();\nDescribeContainerResponse response =\nmediaStoreClient.describeContainer(containerRequest);\nmediaStoreClient.close();\nreturn response.container().endpoint();\n}\n}\n\u2022 For API details, see DeleteObject in AWS SDK for Java 2.x API Reference.\nDescribeContainer\nThe following code example shows how to use DescribeContainer.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\nActions 1196\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class DescribeContainer {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncontainerName - The name of the container to describe.", "mimetype": "text/plain", "start_char_idx": 1729437, "end_char_idx": 1733319, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7c566499-a1be-4b6a-afb9-284f0d89c899": {"__data__": {"id_": "7c566499-a1be-4b6a-afb9-284f0d89c899", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "52be1aa0-b2ce-49b8-86aa-e6dbf83fd121", "node_type": "1", "metadata": {}, "hash": "79cfc81b4d63814897113eb2cb64ddb78f24dc46f5bc9edcbbf6db470992c2a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f1bedcc7-ba9e-49f7-a26d-ade796b45a2b", "node_type": "1", "metadata": {}, "hash": "849b55567a3ce31a878e97a3aeaf9fcbde9f0360aed82eed46449c5e0c2efe7a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "import software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\nActions 1196\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic class DescribeContainer {\npublic static void main(String[] args) {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncontainerName - The name of the container to describe.\n\"\"\";\nif (args.length != 1) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString containerName = args[0];\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\nSystem.out.println(\"Status is \" + checkContainer(mediaStoreClient,\ncontainerName));\nmediaStoreClient.close();\n}\npublic static String checkContainer(MediaStoreClient mediaStoreClient, String\ncontainerName) {\ntry {\nDescribeContainerRequest describeContainerRequest =\nDescribeContainerRequest.builder()\n.containerName(containerName)\n.build();\nDescribeContainerResponse containerResponse =\nmediaStoreClient.describeContainer(describeContainerRequest);\nSystem.out.println(\"The container name is \" +\ncontainerResponse.container().name());\nSystem.out.println(\"The container ARN is \" +\ncontainerResponse.container().arn());\nreturn containerResponse.container().status().toString();\n} catch (MediaStoreException e) {\nActions 1197\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\nreturn \"\";\n}\n}\n\u2022 For API details, see DescribeContainer in AWS SDK for Java 2.x API Reference.\nGetObject\nThe following code example shows how to use GetObject.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.core.ResponseInputStream;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;\nimport software.amazon.awssdk.services.mediastoredata.model.GetObjectRequest;\nimport software.amazon.awssdk.services.mediastoredata.model.GetObjectResponse;\nimport software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\nActions 1198\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class GetObject {\npublic static void main(String[] args) throws URISyntaxException {\nfinal String usage = \"\"\"\nUsage: \nWhere:\ncompletePath - The path of the object in the container (for\nexample, Videos5/sampleVideo.mp4).\ncontainerName - The name of the container.\nsavePath - The path on the local drive where the file is saved,\nincluding the file name (for example, C:/AWS/myvid.mp4).\n\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString completePath = args[0];\nString containerName = args[1];\nString savePath = args[2];\nRegion region = Region.US_EAST_1;\nURI uri = new URI(getEndpoint(containerName));\nMediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()\n.endpointOverride(uri)\n.region(region)\n.build();\ngetMediaObject(mediaStoreData, completePath, savePath);\nmediaStoreData.close();\n}\npublic static void getMediaObject(MediaStoreDataClient mediaStoreData, String\ncompletePath, String savePath) {\ntry {\nGetObjectRequest objectRequest = GetObjectRequest.builder()\n.path(completePath)\nActions 1199\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n// Write out the data to a file.", "mimetype": "text/plain", "start_char_idx": 1732446, "end_char_idx": 1737035, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f1bedcc7-ba9e-49f7-a26d-ade796b45a2b": {"__data__": {"id_": "f1bedcc7-ba9e-49f7-a26d-ade796b45a2b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7c566499-a1be-4b6a-afb9-284f0d89c899", "node_type": "1", "metadata": {}, "hash": "1eae5dbf7c49ec785ef3cecb2ab512a7d30d95e3ae4b359fc1f3e4718fd40171", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "af2dabb8-57a6-4d71-b2e1-0301cba5d850", "node_type": "1", "metadata": {}, "hash": "486b833cffbe580bdbf2686a6e1b75d0cb5054f1e9e7d30ba2e1c6f1fa17f8f6", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\";\nif (args.length != 3) {\nSystem.out.println(usage);\nSystem.exit(1);\n}\nString completePath = args[0];\nString containerName = args[1];\nString savePath = args[2];\nRegion region = Region.US_EAST_1;\nURI uri = new URI(getEndpoint(containerName));\nMediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()\n.endpointOverride(uri)\n.region(region)\n.build();\ngetMediaObject(mediaStoreData, completePath, savePath);\nmediaStoreData.close();\n}\npublic static void getMediaObject(MediaStoreDataClient mediaStoreData, String\ncompletePath, String savePath) {\ntry {\nGetObjectRequest objectRequest = GetObjectRequest.builder()\n.path(completePath)\nActions 1199\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\n// Write out the data to a file.\nResponseInputStream data =\nmediaStoreData.getObject(objectRequest);\nbyte[] buffer = new byte[data.available()];\ndata.read(buffer);\nFile targetFile = new File(savePath);\nOutputStream outStream = new FileOutputStream(targetFile);\noutStream.write(buffer);\nSystem.out.println(\"The data was written to \" + savePath);\n} catch (MediaStoreDataException | IOException e) {\nSystem.err.println(e.getMessage());\nSystem.exit(1);\n}\n}\nprivate static String getEndpoint(String containerName) {\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\nDescribeContainerRequest containerRequest =\nDescribeContainerRequest.builder()\n.containerName(containerName)\n.build();\nDescribeContainerResponse response =\nmediaStoreClient.describeContainer(containerRequest);\nreturn response.container().endpoint();\n}\n}\n\u2022 For API details, see GetObject in AWS SDK for Java 2.x API Reference.\nListContainers\nThe following code example shows how to use ListContainers.\nActions 1200\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastore.model.Container;\nimport software.amazon.awssdk.services.mediastore.model.ListContainersResponse;\nimport software.amazon.awssdk.services.mediastore.model.MediaStoreException;\nimport java.util.List;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class ListContainers {\npublic static void main(String[] args) {\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\nlistAllContainers(mediaStoreClient);\nmediaStoreClient.close();\n}\npublic static void listAllContainers(MediaStoreClient mediaStoreClient) {\ntry {\nListContainersResponse containersResponse =\nmediaStoreClient.listContainers();\nList containers = containersResponse.containers();\nActions 1201\nAWS SDK for Java 2.x Developer Guide for version 2.x\nfor (Container container : containers) {\nSystem.out.println(\"Container name is \" + container.name());\n}\n} catch (MediaStoreException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListContainers in AWS SDK for Java 2.x API Reference.\nPutObject\nThe following code example shows how to use PutObject.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest;\nimport software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;\nimport software.amazon.awssdk.services.mediastoredata.model.PutObjectResponse;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport java.io.File;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1736285, "end_char_idx": 1740855, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "af2dabb8-57a6-4d71-b2e1-0301cba5d850": {"__data__": {"id_": "af2dabb8-57a6-4d71-b2e1-0301cba5d850", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f1bedcc7-ba9e-49f7-a26d-ade796b45a2b", "node_type": "1", "metadata": {}, "hash": "849b55567a3ce31a878e97a3aeaf9fcbde9f0360aed82eed46449c5e0c2efe7a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55a0369e-b6df-47b6-a9a3-afebb27cfbf4", "node_type": "1", "metadata": {}, "hash": "098044685841a498f5858174d18d259e28c35fcf031a3a0120a0ce673410a280", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.mediastore.MediaStoreClient;\nimport software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;\nimport software.amazon.awssdk.core.sync.RequestBody;\nimport software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest;\nimport software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;\nimport software.amazon.awssdk.services.mediastoredata.model.PutObjectResponse;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;\nimport software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;\nimport java.io.File;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\nActions 1202\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class PutObject {\npublic static void main(String[] args) throws URISyntaxException {\nfinal String USAGE = \"\"\"\nTo run this example, supply the name of a container, a file location\nto use, and path in the container\\s\nEx: \n\"\"\";\nif (args.length < 3) {\nSystem.out.println(USAGE);\nSystem.exit(1);\n}\nString containerName = args[0];\nString filePath = args[1];\nString completePath = args[2];\nRegion region = Region.US_EAST_1;\nURI uri = new URI(getEndpoint(containerName));\nMediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()\n.endpointOverride(uri)\n.region(region)\n.build();\nputMediaObject(mediaStoreData, filePath, completePath);\nmediaStoreData.close();\n}\npublic static void putMediaObject(MediaStoreDataClient mediaStoreData, String\nfilePath, String completePath) {\ntry {\nFile myFile = new File(filePath);\nRequestBody requestBody = RequestBody.fromFile(myFile);\nPutObjectRequest objectRequest = PutObjectRequest.builder()\n.path(completePath)\n.contentType(\"video/mp4\")\nActions 1203\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.build();\nPutObjectResponse response = mediaStoreData.putObject(objectRequest,\nrequestBody);\nSystem.out.println(\"The saved object is \" +\nresponse.storageClass().toString());\n} catch (MediaStoreDataException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static String getEndpoint(String containerName) {\nRegion region = Region.US_EAST_1;\nMediaStoreClient mediaStoreClient = MediaStoreClient.builder()\n.region(region)\n.build();\nDescribeContainerRequest containerRequest =\nDescribeContainerRequest.builder()\n.containerName(containerName)\n.build();\nDescribeContainerResponse response =\nmediaStoreClient.describeContainer(containerRequest);\nreturn response.container().endpoint();\n}\n}\n\u2022 For API details, see PutObject in AWS SDK for Java 2.x API Reference.\nOpenSearch Service examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with OpenSearch Service.\nBasics are code examples that show you how to perform the essential operations within a service.\nOpenSearch Service 1204\nAWS SDK for Java 2.x Developer Guide for version 2.x\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello OpenSearch Service\nThe following code example shows how to get started using OpenSearch Service.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;\nimport software.amazon.awssdk.services.opensearch.model.ListVersionsRequest;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class HelloOpenSearch {\npublic static void main(String[] args) {\ntry {\nCompletableFuture future = listVersionsAsync();\nfuture.join();\nSystem.out.println(\"Versions listed successfully.", "mimetype": "text/plain", "start_char_idx": 1739918, "end_char_idx": 1744610, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "55a0369e-b6df-47b6-a9a3-afebb27cfbf4": {"__data__": {"id_": "55a0369e-b6df-47b6-a9a3-afebb27cfbf4", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "af2dabb8-57a6-4d71-b2e1-0301cba5d850", "node_type": "1", "metadata": {}, "hash": "486b833cffbe580bdbf2686a6e1b75d0cb5054f1e9e7d30ba2e1c6f1fa17f8f6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "93a4917d-4040-4cb7-8043-07e60c40d4e1", "node_type": "1", "metadata": {}, "hash": "cccab51825faf92c7ed176ffa19029a32367896ca39636046abbc5da9c53ab27", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Get started\nHello OpenSearch Service\nThe following code example shows how to get started using OpenSearch Service.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nimport software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;\nimport software.amazon.awssdk.services.opensearch.model.ListVersionsRequest;\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*/\npublic class HelloOpenSearch {\npublic static void main(String[] args) {\ntry {\nCompletableFuture future = listVersionsAsync();\nfuture.join();\nSystem.out.println(\"Versions listed successfully.\");\n} catch (RuntimeException e) {\nSystem.err.println(\"Error occurred while listing versions: \" +\ne.getMessage());\n}\nOpenSearch Service 1205\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nprivate static OpenSearchAsyncClient getAsyncClient() {\nreturn OpenSearchAsyncClient.builder().build();\n}\npublic static CompletableFuture listVersionsAsync() {\nListVersionsRequest request = ListVersionsRequest.builder()\n.maxResults(10)\n.build();\nreturn getAsyncClient().listVersions(request).thenAccept(response -> {\nList versionList = response.versions();\nfor (String version : versionList) {\nSystem.out.println(\"Version info: \" + version);\n}\n}).exceptionally(ex -> {\n// Handle the exception, or propagate it as a RuntimeException\nthrow new RuntimeException(\"Failed to list versions\", ex);\n});\n}\n}\n\u2022 For API details, see ListVersions in AWS SDK for Java 2.x API Reference.\nTopics\n\u2022 Basics\n\u2022 Actions\nBasics\nLearn OpenSearch Service core operations\nThe following code example shows how to:\n\u2022 Create an OpenSearch Service domain.\n\u2022 Provides detailed information about a specific OpenSearch Service domain.\n\u2022 Lists all the OpenSearch Service domains owned by the account.\n\u2022 Waits until the OpenSearch Service domain's change status reaches a completed state.\nBasics 1206\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 Modifies the configuration of an existing OpenSearch Service domain.\n\u2022 Add a tag to the OpenSearch Service domain.\n\u2022 Lists the tags associated with an OpenSearch Service domain.\n\u2022 Removes tags from an OpenSearch Service domain.\n\u2022 Deletes the OpenSearch Service domain.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nRun an interactive scenario demonstrating OpenSearch Service features.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.services.opensearch.model.*;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.concurrent.CompletableFuture;\npublic class OpenSearchScenario {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\nprivate static final Logger logger =\nLoggerFactory.getLogger(OpenSearchScenario.class);\nstatic Scanner scanner = new Scanner(System.in);\nstatic OpenSearchActions openSearchActions = new OpenSearchActions();\npublic static void main(String[] args) throws Throwable {\nlogger.info(\"\"\"\nWelcome to the Amazon OpenSearch Service Basics Scenario.\nUse the Amazon OpenSearch Service API to create, configure, and manage\nOpenSearch Service domains.\nBasics 1207\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThe operations exposed by the AWS OpenSearch Service client are focused\non managing the OpenSearch Service domains\nand their configurations, not the data within the domains (such as\nindexing or querying documents).\nFor document management, you typically interact directly with the\nOpenSearch REST API or use other libraries,\nsuch as the OpenSearch Java client (https://opensearch.org/docs/latest/\nclients/java/).\nLet's get started...\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nrunScenario();\n} catch (RuntimeException e) {\ne.printStackTrace();\n}\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\nprivate static void runScenario() throws Throwable {\nString currentTimestamp = String.valueOf(System.currentTimeMillis());\nString domainName = \"test-domain-\" + currentTimestamp;\nlogger.info(DASHES);\nlogger.info(\"1.", "mimetype": "text/plain", "start_char_idx": 1743670, "end_char_idx": 1748383, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "93a4917d-4040-4cb7-8043-07e60c40d4e1": {"__data__": {"id_": "93a4917d-4040-4cb7-8043-07e60c40d4e1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "55a0369e-b6df-47b6-a9a3-afebb27cfbf4", "node_type": "1", "metadata": {}, "hash": "098044685841a498f5858174d18d259e28c35fcf031a3a0120a0ce673410a280", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a5f539d1-4bc0-424d-afd6-587ae8be4221", "node_type": "1", "metadata": {}, "hash": "64a17dfff494b47b6bdff9bcbed9dba1756a4ceaf17517312f9bccce8d99ba4b", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "For document management, you typically interact directly with the\nOpenSearch REST API or use other libraries,\nsuch as the OpenSearch Java client (https://opensearch.org/docs/latest/\nclients/java/).\nLet's get started...\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nrunScenario();\n} catch (RuntimeException e) {\ne.printStackTrace();\n}\n}\nprivate static void waitForInputToContinue(Scanner scanner) {\nwhile (true) {\nlogger.info(\"\");\nlogger.info(\"Enter 'c' followed by to continue:\");\nString input = scanner.nextLine();\nif (input.trim().equalsIgnoreCase(\"c\")) {\nlogger.info(\"Continuing with the program...\");\nlogger.info(\"\");\nbreak;\n} else {\nlogger.info(\"Invalid input. Please try again.\");\n}\n}\n}\nprivate static void runScenario() throws Throwable {\nString currentTimestamp = String.valueOf(System.currentTimeMillis());\nString domainName = \"test-domain-\" + currentTimestamp;\nlogger.info(DASHES);\nlogger.info(\"1. Create an Amazon OpenSearch domain\");\nlogger.info(\"\"\"\nAn Amazon OpenSearch domain is a managed instance of the OpenSearch\nengine,\nBasics 1208\nAWS SDK for Java 2.x Developer Guide for version 2.x\nwhich is an open-source search and analytics engine derived from\nElasticsearch.\nAn OpenSearch domain is essentially a cluster of compute resources and\nstorage that hosts\none or more OpenSearch indexes, enabling you to perform full-text\nsearches, data analysis, and\nvisualizations.\nIn this step, we'll initiate the creation of the domain. We'll check on\nthe progress in a later step.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.createNewDomainAsync(domainName);\nString domainId = future.join();\nlogger.info(\"Domain successfully created with ID: {}\", domainId);\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause != null) {\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.error(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.error(\"An unexpected error occurred: \" +\ncause.getMessage(), cause);\n}\n} else {\nlogger.error(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"2. Describe the Amazon OpenSearch domain\");\nlogger.info(\"In this step, we get back the Domain ARN which is used in an\nupcoming step.\");\nwaitForInputToContinue(scanner);\nString arn = \"\";\ntry {\nBasics 1209\nAWS SDK for Java 2.x Developer Guide for version 2.x\nCompletableFuture future =\nopenSearchActions.describeDomainAsync(domainName);\narn = future.join();\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"3. List the domains in your account\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture> future =\nopenSearchActions.listAllDomainsAsync();\nList domainInfoList = future.join();\nfor (DomainInfo domain : domainInfoList) {\nlogger.info(\"Domain name is: \" + domain.domainName());\n}\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nOpenSearchException)) {\ncause = cause.getCause();\n}\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nBasics 1210\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(DASHES);\nlogger.info(\"4. Wait until the domain's change status reaches a completed\nstate\");\nlogger.info(\"\"\"\nIn this step, we check on the change status of the domain that we\ninitiated in Step 1.\nUntil we reach a COMPLETED state, we stay in a loop by sending a\nDescribeDomainChangeProgressRequest.\nThe time it takes for a change to an OpenSearch domain to reach a\ncompleted state can range\nfrom a few minutes to several hours. In this case the change is creating\na new domain that we initiated in Step 1.", "mimetype": "text/plain", "start_char_idx": 1747469, "end_char_idx": 1751973, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "a5f539d1-4bc0-424d-afd6-587ae8be4221": {"__data__": {"id_": "a5f539d1-4bc0-424d-afd6-587ae8be4221", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "93a4917d-4040-4cb7-8043-07e60c40d4e1", "node_type": "1", "metadata": {}, "hash": "cccab51825faf92c7ed176ffa19029a32367896ca39636046abbc5da9c53ab27", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f3b066b6-6c1b-4123-87f5-1af0094bbfd7", "node_type": "1", "metadata": {}, "hash": "7f31e9f074206071d6b47741f4f1b30086ff8ca182f159e32a7bfa72e2e4ee5e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Wait until the domain's change status reaches a completed\nstate\");\nlogger.info(\"\"\"\nIn this step, we check on the change status of the domain that we\ninitiated in Step 1.\nUntil we reach a COMPLETED state, we stay in a loop by sending a\nDescribeDomainChangeProgressRequest.\nThe time it takes for a change to an OpenSearch domain to reach a\ncompleted state can range\nfrom a few minutes to several hours. In this case the change is creating\na new domain that we initiated in Step 1.\nThe time varies depending on the complexity of the change and the\ncurrent load on\nthe OpenSearch service. In general, simple changes, such as scaling the\nnumber of data nodes or\nupdating the OpenSearch version, may take 10-30 minutes.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.domainChangeProgressAsync(domainName);\nfuture.join();\nlogger.info(\"Domain change progress completed successfully.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nResourceNotFoundException)) {\ncause = cause.getCause();\n}\nif (cause instanceof ResourceNotFoundException\nresourceNotFoundException) {\nlogger.info(\"The specific AWS resource was not found: Error message:\n{}, Error code {}\", resourceNotFoundException.awsErrorDetails().errorMessage(),\nresourceNotFoundException.awsErrorDetails().errorCode());\nif (cause instanceof OpenSearchException ex) {\nlogger.info(\"An OpenSearch error occurred: Error message: \" +\nex.getMessage());\n} else {\nBasics 1211\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"5. Modify the domain\");\nlogger.info(\"\"\"\nYou can change your OpenSearch domain's settings, like the number of\ninstances, without starting over from scratch.\nThis makes it easy to adjust your domain as your needs change, allowing\nyou to scale up or\ndown quickly without recreating everything.\nWe modify the domain in this step by changing the number of instances.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.updateSpecificDomainAsync(domainName);\nUpdateDomainConfigResponse updateResponse = future.join();\nlogger.info(\"Domain update status: \" +\nupdateResponse.domainConfig().changeProgressDetails().configChangeStatusAsString());\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"6. Wait until the domain's change status reaches a completed\nstate\");\nlogger.info(\"\"\"\nBasics 1212\nAWS SDK for Java 2.x Developer Guide for version 2.x\nIn this step, we poll the status until the domain's change status\nreaches a completed state.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.domainChangeProgressAsync(domainName);\nfuture.join();\nlogger.info(\"Domain change progress completed successfully.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nif (cause instanceof OpenSearchException ex) {\nlogger.info(\"EC2 error occurred: Error message: \" +ex.getMessage());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"7. Tag the Domain\");\nlogger.info(\"\"\"\nTags let you assign arbitrary information to an Amazon OpenSearch\nService domain so you can\ncategorize and filter on that information. A tag is a key-value pair\nthat you define and\nassociate with an OpenSearch Service domain. You can use these tags to\ntrack costs by grouping\nexpenses for similarly tagged resources.\nIn this scenario, we create tags with keys \"service\" and \"instances\".\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.addDomainTagsAsync(arn);\nfuture.join();\nlogger.info(\"Domain tags added successfully.\");\n} catch (RuntimeException rt) {\nBasics 1213\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !", "mimetype": "text/plain", "start_char_idx": 1751495, "end_char_idx": 1755964, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "f3b066b6-6c1b-4123-87f5-1af0094bbfd7": {"__data__": {"id_": "f3b066b6-6c1b-4123-87f5-1af0094bbfd7", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a5f539d1-4bc0-424d-afd6-587ae8be4221", "node_type": "1", "metadata": {}, "hash": "64a17dfff494b47b6bdff9bcbed9dba1756a4ceaf17517312f9bccce8d99ba4b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "57df78c6-1644-4efa-b48e-83b8f3b6341b", "node_type": "1", "metadata": {}, "hash": "afa2dbfba0a702d2016f54df32785de3a3de812e18477e6442d0939ef1dcca90", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Tag the Domain\");\nlogger.info(\"\"\"\nTags let you assign arbitrary information to an Amazon OpenSearch\nService domain so you can\ncategorize and filter on that information. A tag is a key-value pair\nthat you define and\nassociate with an OpenSearch Service domain. You can use these tags to\ntrack costs by grouping\nexpenses for similarly tagged resources.\nIn this scenario, we create tags with keys \"service\" and \"instances\".\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.addDomainTagsAsync(arn);\nfuture.join();\nlogger.info(\"Domain tags added successfully.\");\n} catch (RuntimeException rt) {\nBasics 1213\nAWS SDK for Java 2.x Developer Guide for version 2.x\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nOpenSearchException)) {\ncause = cause.getCause();\n}\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\nif (cause != null) {\nif (cause instanceof OpenSearchException) {\nlogger.error(\"OpenSearch error occurred: Error message: \" +\ncause.getMessage(), cause);\n} else {\nlogger.error(\"An unexpected error occurred: \" +\ncause.getMessage(), cause);\n}\n} else {\nlogger.error(\"An unexpected error occurred: \" + rt.getMessage(),\nrt);\n}\nthrow cause;\n}\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"8. List Domain tags\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.listDomainTagsAsync(arn);\nListTagsResponse listTagsResponse = future.join();\nlistTagsResponse.tagList().forEach(tag -> logger.info(\"Tag Key: \" +\ntag.key() + \", Tag Value: \" + tag.value()));\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nOpenSearchException)) {\ncause = cause.getCause();\n}\nBasics 1214\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"9. Delete the domain\");\nlogger.info(\"\"\"\nIn this step, we'll delete the Amazon OpenSearch domain that we created\nin Step 1.\nDeleting a domain will remove all data and configuration for that\ndomain.\n\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.deleteSpecificDomainAsync(domainName);\nfuture.join();\nlogger.info(\"Domain successfully deleted.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nOpenSearchException)) {\ncause = cause.getCause();\n}\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\nBasics 1215\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"Scenario complete!\");\n}\n}\nA wrapper class for OpenSearch Service SDK methods.", "mimetype": "text/plain", "start_char_idx": 1755182, "end_char_idx": 1758773, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "57df78c6-1644-4efa-b48e-83b8f3b6341b": {"__data__": {"id_": "57df78c6-1644-4efa-b48e-83b8f3b6341b", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f3b066b6-6c1b-4123-87f5-1af0094bbfd7", "node_type": "1", "metadata": {}, "hash": "7f31e9f074206071d6b47741f4f1b30086ff8ca182f159e32a7bfa72e2e4ee5e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3adbef6b-7783-475f-bbdc-db716b238479", "node_type": "1", "metadata": {}, "hash": "21f6d8e816dd8733764028133ae33d278f7462ca32d9ea5e35633b16a0069fde", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\"\"\");\nwaitForInputToContinue(scanner);\ntry {\nCompletableFuture future =\nopenSearchActions.deleteSpecificDomainAsync(domainName);\nfuture.join();\nlogger.info(\"Domain successfully deleted.\");\n} catch (RuntimeException rt) {\nThrowable cause = rt.getCause();\nwhile (cause.getCause() != null && !(cause instanceof\nOpenSearchException)) {\ncause = cause.getCause();\n}\nif (cause instanceof OpenSearchException openSearchEx) {\nlogger.info(\"OpenSearch error occurred: Error message:\n{}, Error code {}\", openSearchEx.awsErrorDetails().errorMessage(),\nopenSearchEx.awsErrorDetails().errorCode());\n} else {\nlogger.info(\"An unexpected error occurred: \" + rt.getMessage());\n}\nthrow cause;\nBasics 1215\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nwaitForInputToContinue(scanner);\nlogger.info(DASHES);\nlogger.info(\"Scenario complete!\");\n}\n}\nA wrapper class for OpenSearch Service SDK methods.\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;\nimport software.amazon.awssdk.core.retry.RetryPolicy;\nimport software.amazon.awssdk.http.async.SdkAsyncHttpClient;\nimport software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;\nimport software.amazon.awssdk.services.opensearch.model.AddTagsRequest;\nimport software.amazon.awssdk.services.opensearch.model.AddTagsResponse;\nimport software.amazon.awssdk.services.opensearch.model.ClusterConfig;\nimport software.amazon.awssdk.services.opensearch.model.CreateDomainRequest;\nimport software.amazon.awssdk.services.opensearch.model.DeleteDomainRequest;\nimport software.amazon.awssdk.services.opensearch.model.DeleteDomainResponse;\nimport\nsoftware.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressRequest;\nimport\nsoftware.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressResponse;\nimport software.amazon.awssdk.services.opensearch.model.DescribeDomainRequest;\nimport software.amazon.awssdk.services.opensearch.model.DomainInfo;\nimport software.amazon.awssdk.services.opensearch.model.DomainStatus;\nimport software.amazon.awssdk.services.opensearch.model.EBSOptions;\nimport software.amazon.awssdk.services.opensearch.model.ListDomainNamesRequest;\nimport software.amazon.awssdk.services.opensearch.model.ListTagsRequest;\nimport software.amazon.awssdk.services.opensearch.model.ListTagsResponse;\nimport software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions;\nimport software.amazon.awssdk.services.opensearch.model.Tag;\nimport software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigRequest;\nimport software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigResponse;\nimport software.amazon.awssdk.services.opensearch.model.VolumeType;\nimport java.time.Duration;\nimport java.util.ArrayList;\nBasics 1216\nAWS SDK for Java 2.x Developer Guide for version 2.x\nimport java.util.List;\nimport java.util.concurrent.CompletableFuture;\npublic class OpenSearchActions {\nprivate static final Logger logger =\nLoggerFactory.getLogger(OpenSearchActions.class);\nprivate static OpenSearchAsyncClient openSearchClientAsyncClient;\nprivate static OpenSearchAsyncClient getAsyncClient() {\nif (openSearchClientAsyncClient == null) {\nSdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()\n.maxConcurrency(100)\n.connectionTimeout(Duration.ofSeconds(60))\n.readTimeout(Duration.ofSeconds(60))\n.writeTimeout(Duration.ofSeconds(60))\n.build();\nClientOverrideConfiguration overrideConfig =\nClientOverrideConfiguration.builder()\n.apiCallTimeout(Duration.ofMinutes(2))\n.apiCallAttemptTimeout(Duration.ofSeconds(90))\n.retryPolicy(RetryPolicy.builder()\n.numRetries(3)\n.build())\n.build();\nopenSearchClientAsyncClient = OpenSearchAsyncClient.builder()\n.region(Region.US_EAST_1)\n.httpClient(httpClient)\n.overrideConfiguration(overrideConfig)\n.build();\n}\nreturn openSearchClientAsyncClient;\n}\n/**\n* Creates a new OpenSearch domain asynchronously.", "mimetype": "text/plain", "start_char_idx": 1757867, "end_char_idx": 1761924, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3adbef6b-7783-475f-bbdc-db716b238479": {"__data__": {"id_": "3adbef6b-7783-475f-bbdc-db716b238479", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "57df78c6-1644-4efa-b48e-83b8f3b6341b", "node_type": "1", "metadata": {}, "hash": "afa2dbfba0a702d2016f54df32785de3a3de812e18477e6442d0939ef1dcca90", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ee199967-e3a5-4fda-972e-a8738e8ab1b1", "node_type": "1", "metadata": {}, "hash": "1c096cc4885d4a060a76eba592419ad7932e3b3afd7af69c63d64d664c011bf7", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* @param domainName the name of the new OpenSearch domain to create\n* @return a {@link CompletableFuture} containing the domain ID of the newly\ncreated domain\n*/\npublic CompletableFuture createNewDomainAsync(String domainName) {\nClusterConfig clusterConfig = ClusterConfig.builder()\n.dedicatedMasterEnabled(true)\n.dedicatedMasterCount(3)\nBasics 1217\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.dedicatedMasterType(\"t2.small.search\")\n.instanceType(\"t2.small.search\")\n.instanceCount(5)\n.build();\nEBSOptions ebsOptions = EBSOptions.builder()\n.ebsEnabled(true)\n.volumeSize(10)\n.volumeType(VolumeType.GP2)\n.build();\nNodeToNodeEncryptionOptions encryptionOptions =\nNodeToNodeEncryptionOptions.builder()\n.enabled(true)\n.build();\nCreateDomainRequest domainRequest = CreateDomainRequest.builder()\n.domainName(domainName)\n.engineVersion(\"OpenSearch_1.0\")\n.clusterConfig(clusterConfig)\n.ebsOptions(ebsOptions)\n.nodeToNodeEncryptionOptions(encryptionOptions)\n.build();\nlogger.info(\"Sending domain creation request...\");\nreturn getAsyncClient().createDomain(domainRequest)\n.handle( (createResponse, throwable) -> {\nif (createResponse != null) {\nlogger.info(\"Domain status is {}\",\ncreateResponse.domainStatus().changeProgressDetails().configChangeStatusAsString());\nlogger.info(\"Domain Id is {}\",\ncreateResponse.domainStatus().domainId());\nreturn createResponse.domainStatus().domainId();\n}\nthrow new RuntimeException(\"Failed to create domain\",\nthrowable);\n});\n}\n/**\n* Deletes a specific domain asynchronously.\n* @param domainName the name of the domain to be deleted\n* @return a {@link CompletableFuture} that completes when the domain has been\ndeleted\n* or throws a {@link RuntimeException} if the deletion fails\nBasics 1218\nAWS SDK for Java 2.x Developer Guide for version 2.x\n*/\npublic CompletableFuture deleteSpecificDomainAsync(String\ndomainName) {\nDeleteDomainRequest domainRequest = DeleteDomainRequest.builder()\n.domainName(domainName)\n.build();\n// Delete domain asynchronously\nreturn getAsyncClient().deleteDomain(domainRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the domain: \" +\ndomainName, exception);\n}\n});\n}\n/**\n* Describes the specified domain asynchronously.\n*\n* @param domainName the name of the domain to describe\n* @return a {@link CompletableFuture} that completes with the ARN of the domain\n* @throws RuntimeException if the domain description fails\n*/\npublic CompletableFuture describeDomainAsync(String domainName) {\nDescribeDomainRequest request = DescribeDomainRequest.builder()\n.domainName(domainName)\n.build();\nreturn getAsyncClient().describeDomain(request)\n.handle((response, exception) -> { // Handle both response and\nexception\nif (exception != null) {\nthrow new RuntimeException(\"Failed to describe domain\",\nexception);\n}\nDomainStatus domainStatus = response.domainStatus();\nString endpoint = domainStatus.endpoint();\nString arn = domainStatus.arn();\nString engineVersion = domainStatus.engineVersion();\nlogger.info(\"Domain endpoint is: \" + endpoint);\nlogger.info(\"ARN: \" + arn);\nSystem.out.println(\"Engine version: \" + engineVersion);\nBasics 1219\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn arn; // Return ARN when successful\n});\n}\n/**\n* Asynchronously lists all the domains in the current AWS account.\n* @return a {@link CompletableFuture} that, when completed, contains a list of\n{@link DomainInfo} objects representing\n* the domains in the account.\n* @throws RuntimeException if there was a failure while listing the domains.\n*/\npublic CompletableFuture> listAllDomainsAsync() {\nListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()\n.engineType(\"OpenSearch\")\n.build();\nreturn getAsyncClient().listDomainNames(namesRequest)\n.handle((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to list all domains\",\nexception);\n}\nreturn response.domainNames(); // Return the list of domain names\non success\n});\n}\n/**\n* Updates the configuration of a specific domain asynchronously.", "mimetype": "text/plain", "start_char_idx": 1761925, "end_char_idx": 1766026, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "ee199967-e3a5-4fda-972e-a8738e8ab1b1": {"__data__": {"id_": "ee199967-e3a5-4fda-972e-a8738e8ab1b1", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3adbef6b-7783-475f-bbdc-db716b238479", "node_type": "1", "metadata": {}, "hash": "21f6d8e816dd8733764028133ae33d278f7462ca32d9ea5e35633b16a0069fde", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6033585c-0bf3-4c50-94b3-972971fd3289", "node_type": "1", "metadata": {}, "hash": "82f17fb3abc48d641cd217918a041c7363a931dbd4a107fb4a68960ed8f7222a", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* @return a {@link CompletableFuture} that, when completed, contains a list of\n{@link DomainInfo} objects representing\n* the domains in the account.\n* @throws RuntimeException if there was a failure while listing the domains.\n*/\npublic CompletableFuture> listAllDomainsAsync() {\nListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()\n.engineType(\"OpenSearch\")\n.build();\nreturn getAsyncClient().listDomainNames(namesRequest)\n.handle((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to list all domains\",\nexception);\n}\nreturn response.domainNames(); // Return the list of domain names\non success\n});\n}\n/**\n* Updates the configuration of a specific domain asynchronously.\n* @param domainName the name of the domain to update\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation of updating the domain configuration\n*/\npublic CompletableFuture\nupdateSpecificDomainAsync(String domainName) {\nClusterConfig clusterConfig = ClusterConfig.builder()\n.instanceCount(3)\n.build();\nUpdateDomainConfigRequest updateDomainConfigRequest =\nUpdateDomainConfigRequest.builder()\n.domainName(domainName)\n.clusterConfig(clusterConfig)\n.build();\nBasics 1220\nAWS SDK for Java 2.x Developer Guide for version 2.x\nreturn getAsyncClient().updateDomainConfig(updateDomainConfigRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to update the domain\nconfiguration\", exception);\n}\n// Handle success if needed (e.g., logging or additional actions)\n});\n}\n/**\n* Asynchronously checks the progress of a domain change operation in Amazon\nOpenSearch Service.\n* @param domainName the name of the OpenSearch domain to check the progress for\n* @return a {@link CompletableFuture} that completes when the domain change\noperation is completed\n*/\npublic CompletableFuture domainChangeProgressAsync(String domainName) {\nDescribeDomainChangeProgressRequest request =\nDescribeDomainChangeProgressRequest.builder()\n.domainName(domainName)\n.build();\nreturn CompletableFuture.runAsync(() -> {\nboolean isCompleted = false;\nlong startTime = System.currentTimeMillis();\nwhile (!isCompleted) {\ntry {\n// Handle the async client call using `join` to block\nsynchronously for the result\nDescribeDomainChangeProgressResponse response = getAsyncClient()\n.describeDomainChangeProgress(request)\n.handle((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to check domain\nprogress\", ex);\n}\nreturn resp;\n}).join();\nString state = response.changeProgressStatus().statusAsString();\n// Get the status as string\nBasics 1221\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (\"COMPLETED\".equals(state)) {\nlogger.info(\"\\nOpenSearch domain status: Completed\");\nisCompleted = true;\n} else {\nfor (int i = 0; i < 5; i++) {\nlong elapsedTimeInSeconds = (System.currentTimeMillis()\n- startTime) / 1000;\nString formattedTime = String.format(\"%02d:%02d\",\nelapsedTimeInSeconds / 60, elapsedTimeInSeconds % 60);\nSystem.out.print(\"\\rOpenSearch domain state: \" + state +\n\" | Time Elapsed: \" + formattedTime + \" \");\nSystem.out.flush();\nThread.sleep(1_000);\n}\n}\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\nthrow new RuntimeException(\"Thread was interrupted\", e);\n}\n}\n});\n}\n/**\n* Asynchronously adds tags to an Amazon OpenSearch Service domain.\n* @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch\nService domain to add tags to\n* @return a {@link CompletableFuture} that completes when the tags have been\nsuccessfully added to the domain,\n* or throws a {@link RuntimeException} if the operation fails\n*/\npublic CompletableFuture addDomainTagsAsync(String domainARN) {\nTag tag1 = Tag.builder()\n.key(\"service\")\n.value(\"OpenSearch\")\n.build();\nTag tag2 = Tag.builder()\n.key(\"instances\")\n.value(\"m3.2xlarge\")\n.build();\nList tagList = new ArrayList<>();\nBasics 1222\nAWS SDK for Java 2.x Developer Guide for version 2.x\ntagList.add(tag1);\ntagList.add(tag2);\nAddTagsRequest addTagsRequest = AddTagsRequest.builder()\n.arn(domainARN)\n.tagList(tagList)\n.build();\nreturn getAsyncClient().addTags(addTagsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to add tags to the domain: \"\n+ domainARN, exception);\n} else {\nlogger.info(\"Added Tags\");\n}\n});\n}\n/**\n* Asynchronously lists the tags associated with the specified Amazon Resource\nName (ARN).", "mimetype": "text/plain", "start_char_idx": 1765287, "end_char_idx": 1769781, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "6033585c-0bf3-4c50-94b3-972971fd3289": {"__data__": {"id_": "6033585c-0bf3-4c50-94b3-972971fd3289", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ee199967-e3a5-4fda-972e-a8738e8ab1b1", "node_type": "1", "metadata": {}, "hash": "1c096cc4885d4a060a76eba592419ad7932e3b3afd7af69c63d64d664c011bf7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b7399dcc-8ad3-4efb-8ba7-6b8c1c6fe1c9", "node_type": "1", "metadata": {}, "hash": "d730b4cfa5ed35908df7cc321f0eadc41b7bc175545959d6cc0f25a9dbec0c32", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* @param arn the Amazon Resource Name (ARN) of the resource for which to list\nthe tags\n* @return a {@link CompletableFuture} that, when completed, will contain a list\nof the tags associated with the\n* specified ARN\n* @throws RuntimeException if there is an error listing the tags\n*/\npublic CompletableFuture listDomainTagsAsync(String arn) {\nListTagsRequest tagsRequest = ListTagsRequest.builder()\n.arn(arn)\n.build();\nreturn getAsyncClient().listTags(tagsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to list domain tags\",\nexception);\n}\nList tagList = response.tagList();\nfor (Tag tag : tagList) {\nBasics 1223\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Tag key is \" + tag.key());\nlogger.info(\"Tag value is \" + tag.value());\n}\n});\n}\n}\n\u2022 For API details, see the following topics in AWS SDK for Java 2.x API Reference.\n\u2022 AddTags\n\u2022 CreateDomain\n\u2022 DeleteDomain\n\u2022 DescribeDomain\n\u2022 DescribeDomainChangeProgress\n\u2022 ListDomainNames\n\u2022 ListTags\n\u2022 UpdateDomainConfig\nActions\nAddTags\nThe following code example shows how to use AddTags.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously adds tags to an Amazon OpenSearch Service domain.\n* @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch\nService domain to add tags to\n* @return a {@link CompletableFuture} that completes when the tags have been\nsuccessfully added to the domain,\nActions 1224\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* or throws a {@link RuntimeException} if the operation fails\n*/\npublic CompletableFuture addDomainTagsAsync(String domainARN) {\nTag tag1 = Tag.builder()\n.key(\"service\")\n.value(\"OpenSearch\")\n.build();\nTag tag2 = Tag.builder()\n.key(\"instances\")\n.value(\"m3.2xlarge\")\n.build();\nList tagList = new ArrayList<>();\ntagList.add(tag1);\ntagList.add(tag2);\nAddTagsRequest addTagsRequest = AddTagsRequest.builder()\n.arn(domainARN)\n.tagList(tagList)\n.build();\nreturn getAsyncClient().addTags(addTagsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to add tags to the domain: \"\n+ domainARN, exception);\n} else {\nlogger.info(\"Added Tags\");\n}\n});\n}\n\u2022 For API details, see AddTags in AWS SDK for Java 2.x API Reference.\nChangeProgress\nThe following code example shows how to use ChangeProgress.\nActions 1225\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously checks the progress of a domain change operation in Amazon\nOpenSearch Service.", "mimetype": "text/plain", "start_char_idx": 1769782, "end_char_idx": 1772578, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "b7399dcc-8ad3-4efb-8ba7-6b8c1c6fe1c9": {"__data__": {"id_": "b7399dcc-8ad3-4efb-8ba7-6b8c1c6fe1c9", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6033585c-0bf3-4c50-94b3-972971fd3289", "node_type": "1", "metadata": {}, "hash": "82f17fb3abc48d641cd217918a041c7363a931dbd4a107fb4a68960ed8f7222a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "affadf83-bacb-4642-b826-30f62fb1909e", "node_type": "1", "metadata": {}, "hash": "6d3391707ccec569f679c8a5ba0ad99e4fed1fdb275dab0bedfc9fe2aa9a7e7f", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ChangeProgress\nThe following code example shows how to use ChangeProgress.\nActions 1225\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously checks the progress of a domain change operation in Amazon\nOpenSearch Service.\n* @param domainName the name of the OpenSearch domain to check the progress for\n* @return a {@link CompletableFuture} that completes when the domain change\noperation is completed\n*/\npublic CompletableFuture domainChangeProgressAsync(String domainName) {\nDescribeDomainChangeProgressRequest request =\nDescribeDomainChangeProgressRequest.builder()\n.domainName(domainName)\n.build();\nreturn CompletableFuture.runAsync(() -> {\nboolean isCompleted = false;\nlong startTime = System.currentTimeMillis();\nwhile (!isCompleted) {\ntry {\n// Handle the async client call using `join` to block\nsynchronously for the result\nDescribeDomainChangeProgressResponse response = getAsyncClient()\n.describeDomainChangeProgress(request)\n.handle((resp, ex) -> {\nif (ex != null) {\nthrow new RuntimeException(\"Failed to check domain\nprogress\", ex);\n}\nreturn resp;\n}).join();\nString state = response.changeProgressStatus().statusAsString();\n// Get the status as string\nActions 1226\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (\"COMPLETED\".equals(state)) {\nlogger.info(\"\\nOpenSearch domain status: Completed\");\nisCompleted = true;\n} else {\nfor (int i = 0; i < 5; i++) {\nlong elapsedTimeInSeconds = (System.currentTimeMillis()\n- startTime) / 1000;\nString formattedTime = String.format(\"%02d:%02d\",\nelapsedTimeInSeconds / 60, elapsedTimeInSeconds % 60);\nSystem.out.print(\"\\rOpenSearch domain state: \" + state +\n\" | Time Elapsed: \" + formattedTime + \" \");\nSystem.out.flush();\nThread.sleep(1_000);\n}\n}\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\nthrow new RuntimeException(\"Thread was interrupted\", e);\n}\n}\n});\n}\n\u2022 For API details, see ChangeProgress in AWS SDK for Java 2.x API Reference.\nCreateDomain\nThe following code example shows how to use CreateDomain.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Creates a new OpenSearch domain asynchronously.\n* @param domainName the name of the new OpenSearch domain to create\nActions 1227\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* @return a {@link CompletableFuture} containing the domain ID of the newly\ncreated domain\n*/\npublic CompletableFuture createNewDomainAsync(String domainName) {\nClusterConfig clusterConfig = ClusterConfig.builder()\n.dedicatedMasterEnabled(true)\n.dedicatedMasterCount(3)\n.dedicatedMasterType(\"t2.small.search\")\n.instanceType(\"t2.small.search\")\n.instanceCount(5)\n.build();\nEBSOptions ebsOptions = EBSOptions.builder()\n.ebsEnabled(true)\n.volumeSize(10)\n.volumeType(VolumeType.GP2)\n.build();\nNodeToNodeEncryptionOptions encryptionOptions =\nNodeToNodeEncryptionOptions.builder()\n.enabled(true)\n.build();\nCreateDomainRequest domainRequest = CreateDomainRequest.builder()\n.domainName(domainName)\n.engineVersion(\"OpenSearch_1.0\")\n.clusterConfig(clusterConfig)\n.ebsOptions(ebsOptions)\n.nodeToNodeEncryptionOptions(encryptionOptions)\n.build();\nlogger.info(\"Sending domain creation request...\");\nreturn getAsyncClient().createDomain(domainRequest)\n.handle( (createResponse, throwable) -> {\nif (createResponse != null) {\nlogger.info(\"Domain status is {}\",\ncreateResponse.domainStatus().changeProgressDetails().configChangeStatusAsString());\nlogger.info(\"Domain Id is {}\",\ncreateResponse.domainStatus().domainId());\nreturn createResponse.domainStatus().domainId();\n}\nthrow new RuntimeException(\"Failed to create domain\",\nthrowable);\n});\n}\nActions 1228\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\u2022 For API details, see CreateDomain in AWS SDK for Java 2.x API Reference.\nDeleteDomain\nThe following code example shows how to use DeleteDomain.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes a specific domain asynchronously.", "mimetype": "text/plain", "start_char_idx": 1772197, "end_char_idx": 1776414, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "affadf83-bacb-4642-b826-30f62fb1909e": {"__data__": {"id_": "affadf83-bacb-4642-b826-30f62fb1909e", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b7399dcc-8ad3-4efb-8ba7-6b8c1c6fe1c9", "node_type": "1", "metadata": {}, "hash": "d730b4cfa5ed35908df7cc321f0eadc41b7bc175545959d6cc0f25a9dbec0c32", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "167f65e7-6710-4af9-8951-fc037d69b3fd", "node_type": "1", "metadata": {}, "hash": "a21cd1ea77f496fe90901ae7c894b61d307beeeade394e9ab32fd889a7b0a792", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "DeleteDomain\nThe following code example shows how to use DeleteDomain.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Deletes a specific domain asynchronously.\n* @param domainName the name of the domain to be deleted\n* @return a {@link CompletableFuture} that completes when the domain has been\ndeleted\n* or throws a {@link RuntimeException} if the deletion fails\n*/\npublic CompletableFuture deleteSpecificDomainAsync(String\ndomainName) {\nDeleteDomainRequest domainRequest = DeleteDomainRequest.builder()\n.domainName(domainName)\n.build();\n// Delete domain asynchronously\nreturn getAsyncClient().deleteDomain(domainRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to delete the domain: \" +\ndomainName, exception);\n}\n});\n}\n\u2022 For API details, see DeleteDomain in AWS SDK for Java 2.x API Reference.\nActions 1229\nAWS SDK for Java 2.x Developer Guide for version 2.x\nDescribeDomain\nThe following code example shows how to use DescribeDomain.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Updates the configuration of a specific domain asynchronously.\n* @param domainName the name of the domain to update\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation of updating the domain configuration\n*/\npublic CompletableFuture\nupdateSpecificDomainAsync(String domainName) {\nClusterConfig clusterConfig = ClusterConfig.builder()\n.instanceCount(3)\n.build();\nUpdateDomainConfigRequest updateDomainConfigRequest =\nUpdateDomainConfigRequest.builder()\n.domainName(domainName)\n.clusterConfig(clusterConfig)\n.build();\nreturn getAsyncClient().updateDomainConfig(updateDomainConfigRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to update the domain\nconfiguration\", exception);\n}\n// Handle success if needed (e.g., logging or additional actions)\n});\n}\n\u2022 For API details, see DescribeDomain in AWS SDK for Java 2.x API Reference.\nActions 1230\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListDomainNames\nThe following code example shows how to use ListDomainNames.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously lists all the domains in the current AWS account.\n* @return a {@link CompletableFuture} that, when completed, contains a list of\n{@link DomainInfo} objects representing\n* the domains in the account.\n* @throws RuntimeException if there was a failure while listing the domains.\n*/\npublic CompletableFuture> listAllDomainsAsync() {\nListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()\n.engineType(\"OpenSearch\")\n.build();\nreturn getAsyncClient().listDomainNames(namesRequest)\n.handle((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to list all domains\",\nexception);\n}\nreturn response.domainNames(); // Return the list of domain names\non success\n});\n}\n\u2022 For API details, see ListDomainNames in AWS SDK for Java 2.x API Reference.\nListTags\nThe following code example shows how to use ListTags.\nActions 1231\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously adds tags to an Amazon OpenSearch Service domain.", "mimetype": "text/plain", "start_char_idx": 1776155, "end_char_idx": 1779810, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "167f65e7-6710-4af9-8951-fc037d69b3fd": {"__data__": {"id_": "167f65e7-6710-4af9-8951-fc037d69b3fd", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "affadf83-bacb-4642-b826-30f62fb1909e", "node_type": "1", "metadata": {}, "hash": "6d3391707ccec569f679c8a5ba0ad99e4fed1fdb275dab0bedfc9fe2aa9a7e7f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aa24f195-86bb-4f05-8a6c-d0c16fa48ebe", "node_type": "1", "metadata": {}, "hash": "7a6fe714b5a60eb8279d061829afe74104c62fa54cc46c30b75ce1b805a6d3ef", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "*/\npublic CompletableFuture> listAllDomainsAsync() {\nListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()\n.engineType(\"OpenSearch\")\n.build();\nreturn getAsyncClient().listDomainNames(namesRequest)\n.handle((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to list all domains\",\nexception);\n}\nreturn response.domainNames(); // Return the list of domain names\non success\n});\n}\n\u2022 For API details, see ListDomainNames in AWS SDK for Java 2.x API Reference.\nListTags\nThe following code example shows how to use ListTags.\nActions 1231\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Asynchronously adds tags to an Amazon OpenSearch Service domain.\n* @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch\nService domain to add tags to\n* @return a {@link CompletableFuture} that completes when the tags have been\nsuccessfully added to the domain,\n* or throws a {@link RuntimeException} if the operation fails\n*/\npublic CompletableFuture addDomainTagsAsync(String domainARN) {\nTag tag1 = Tag.builder()\n.key(\"service\")\n.value(\"OpenSearch\")\n.build();\nTag tag2 = Tag.builder()\n.key(\"instances\")\n.value(\"m3.2xlarge\")\n.build();\nList tagList = new ArrayList<>();\ntagList.add(tag1);\ntagList.add(tag2);\nAddTagsRequest addTagsRequest = AddTagsRequest.builder()\n.arn(domainARN)\n.tagList(tagList)\n.build();\nreturn getAsyncClient().addTags(addTagsRequest)\n.whenComplete((response, exception) -> {\nif (exception != null) {\nthrow new RuntimeException(\"Failed to add tags to the domain: \"\n+ domainARN, exception);\n} else {\nActions 1232\nAWS SDK for Java 2.x Developer Guide for version 2.x\nlogger.info(\"Added Tags\");\n}\n});\n}\n\u2022 For API details, see ListTags in AWS SDK for Java 2.x API Reference.\nUpdateDomainConfig\nThe following code example shows how to use UpdateDomainConfig.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Updates the configuration of a specific domain asynchronously.\n* @param domainName the name of the domain to update\n* @return a {@link CompletableFuture} that represents the asynchronous\noperation of updating the domain configuration\n*/\npublic CompletableFuture\nupdateSpecificDomainAsync(String domainName) {\nClusterConfig clusterConfig = ClusterConfig.builder()\n.instanceCount(3)\n.build();\nUpdateDomainConfigRequest updateDomainConfigRequest =\nUpdateDomainConfigRequest.builder()\n.domainName(domainName)\n.clusterConfig(clusterConfig)\n.build();\nreturn getAsyncClient().updateDomainConfig(updateDomainConfigRequest)\n.whenComplete((response, exception) -> {\nActions 1233\nAWS SDK for Java 2.x Developer Guide for version 2.x\nif (exception != null) {\nthrow new RuntimeException(\"Failed to update the domain\nconfiguration\", exception);\n}\n// Handle success if needed (e.g., logging or additional actions)\n});\n}\n\u2022 For API details, see UpdateDomainConfig in AWS SDK for Java 2.x API Reference.\nEventBridge examples using SDK for Java 2.x\nThe following code examples show you how to perform actions and implement common scenarios\nby using the AWS SDK for Java 2.x with EventBridge.\nBasics are code examples that show you how to perform the essential operations within a service.\nActions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello EventBridge\nThe following code examples show how to get started using EventBridge.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nEventBridge 1234\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.", "mimetype": "text/plain", "start_char_idx": 1778947, "end_char_idx": 1783329, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "aa24f195-86bb-4f05-8a6c-d0c16fa48ebe": {"__data__": {"id_": "aa24f195-86bb-4f05-8a6c-d0c16fa48ebe", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "167f65e7-6710-4af9-8951-fc037d69b3fd", "node_type": "1", "metadata": {}, "hash": "a21cd1ea77f496fe90901ae7c894b61d307beeeade394e9ab32fd889a7b0a792", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3c2084cb-d6c5-4bb8-a6a9-bf10384ccd01", "node_type": "1", "metadata": {}, "hash": "2dade3fddb250c414124d1bbc1b646606c8b44988e49d1fae3d4990d73fac6ee", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Actions are code excerpts from larger programs and must be run in context. While actions show you\nhow to call individual service functions, you can see actions in context in their related scenarios.\nScenarios are code examples that show you how to accomplish specific tasks by calling multiple\nfunctions within a service or combined with other AWS services.\nEach example includes a link to the complete source code, where you can find instructions on how\nto set up and run the code in context.\nGet started\nHello EventBridge\nThe following code examples show how to get started using EventBridge.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\nEventBridge 1234\nAWS SDK for Java 2.x Developer Guide for version 2.x\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n*/\npublic class HelloEventBridge {\npublic static void main(String[] args) {\nRegion region = Region.US_WEST_2;\nEventBridgeClient eventBrClient = EventBridgeClient.builder()\n.region(region)\n.build();\nlistBuses(eventBrClient);\neventBrClient.close();\n}\npublic static void listBuses(EventBridgeClient eventBrClient) {\ntry {\nListEventBusesRequest busesRequest = ListEventBusesRequest.builder()\n.limit(10)\n.build();\nListEventBusesResponse response =\neventBrClient.listEventBuses(busesRequest);\nList buses = response.eventBuses();\nfor (EventBus bus : buses) {\nSystem.out.println(\"The name of the event bus is: \" + bus.name());\nSystem.out.println(\"The ARN of the event bus is: \" + bus.arn());\n}\n} catch (EventBridgeException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\n}\n\u2022 For API details, see ListEventBuses in AWS SDK for Java 2.x API Reference.\nEventBridge 1235\nAWS SDK for Java 2.x Developer Guide for version 2.x\nTopics\n\u2022 Basics\n\u2022 Actions\n\u2022 Scenarios\nBasics\nLearn the basics\nThe following code example shows how to:\n\u2022 Create a rule and add a target to it.\n\u2022 Enable and disable rules.\n\u2022 List and update rules and targets.\n\u2022 Send events, then clean up resources.\nSDK for Java 2.x\nNote\nThere's more on GitHub. Find the complete example and learn how to set up and run in\nthe AWS Code Examples Repository.\n/**\n* Before running this Java V2 code example, set up your development\n* environment, including your credentials.\n*\n* For more information, see the following documentation topic:\n*\n* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html\n*\n* This Java code example performs the following tasks:\n*\n* This Java V2 example performs the following tasks with Amazon EventBridge:\n*\n* 1. Creates an AWS Identity and Access Management (IAM) role to use with\n* Amazon EventBridge.\nBasics 1236\nAWS SDK for Java 2.x Developer Guide for version 2.x\n* 2. Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events\n* enabled.\n* 3. Creates a rule that triggers when an object is uploaded to Amazon S3.\n* 4. Lists rules on the event bus.\n* 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and\n* lets the user subscribe to it.\n* 6. Adds a target to the rule that sends an email to the specified topic.\n* 7. Creates an EventBridge event that sends an email when an Amazon S3 object\n* is created.\n* 8. Lists Targets.\n* 9. Lists the rules for the same target.\n* 10. Triggers the rule by uploading a file to the Amazon S3 bucket.\n* 11. Disables a specific rule.\n* 12. Checks and print the state of the rule.\n* 13. Adds a transform to the rule to change the text of the email.\n* 14. Enables a specific rule.\n* 15. Triggers the updated rule by uploading a file to the Amazon S3 bucket.\n* 16. Updates the rule to be a custom rule pattern.\n* 17. Sending an event to trigger the rule.\n* 18. Cleans up resources.", "mimetype": "text/plain", "start_char_idx": 1782409, "end_char_idx": 1786375, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "3c2084cb-d6c5-4bb8-a6a9-bf10384ccd01": {"__data__": {"id_": "3c2084cb-d6c5-4bb8-a6a9-bf10384ccd01", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aa24f195-86bb-4f05-8a6c-d0c16fa48ebe", "node_type": "1", "metadata": {}, "hash": "7a6fe714b5a60eb8279d061829afe74104c62fa54cc46c30b75ce1b805a6d3ef", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e824c63f-ba0b-4009-83c4-63ffc5035f7a", "node_type": "1", "metadata": {}, "hash": "dadc3c7d4eeac343baf93d927ff589f9cac88224216f9f98a635d83735137c1d", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "* 6. Adds a target to the rule that sends an email to the specified topic.\n* 7. Creates an EventBridge event that sends an email when an Amazon S3 object\n* is created.\n* 8. Lists Targets.\n* 9. Lists the rules for the same target.\n* 10. Triggers the rule by uploading a file to the Amazon S3 bucket.\n* 11. Disables a specific rule.\n* 12. Checks and print the state of the rule.\n* 13. Adds a transform to the rule to change the text of the email.\n* 14. Enables a specific rule.\n* 15. Triggers the updated rule by uploading a file to the Amazon S3 bucket.\n* 16. Updates the rule to be a custom rule pattern.\n* 17. Sending an event to trigger the rule.\n* 18. Cleans up resources.\n*\n*/\npublic class EventbridgeMVP {\npublic static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\npublic static void main(String[] args) throws InterruptedException, IOException\n{\nfinal String usage = \"\"\"\nUsage:\n \nWhere:\nroleName - The name of the role to create.\nbucketName - The Amazon Simple Storage Service (Amazon S3)\nbucket name to create.\ntopicName - The name of the Amazon Simple Notification Service\n(Amazon SNS) topic to create.\neventRuleName - The Amazon EventBridge rule name to create.\n\"\"\";\nif (args.length != 5) {\nSystem.out.println(usage);\nSystem.exit(1);\nBasics 1237\nAWS SDK for Java 2.x Developer Guide for version 2.x\n}\nString polJSON = \"{\" +\n\"\\\"Version\\\": \\\"2012-10-17\\\",\" +\n\"\\\"Statement\\\": [{\" +\n\"\\\"Effect\\\": \\\"Allow\\\",\" +\n\"\\\"Principal\\\": {\" +\n\"\\\"Service\\\": \\\"events.amazonaws.com\\\"\" +\n\"},\" +\n\"\\\"Action\\\": \\\"sts:AssumeRole\\\"\" +\n\"}]\" +\n\"}\";\nScanner sc = new Scanner(System.in);\nString roleName = args[0];\nString bucketName = args[1];\nString topicName = args[2];\nString eventRuleName = args[3];\nRegion region = Region.US_EAST_1;\nEventBridgeClient eventBrClient = EventBridgeClient.builder()\n.region(region)\n.build();\nS3Client s3Client = S3Client.builder()\n.region(region)\n.build();\nRegion regionGl = Region.AWS_GLOBAL;\nIamClient iam = IamClient.builder()\n.region(regionGl)\n.build();\nSnsClient snsClient = SnsClient.builder()\n.region(region)\n.build();\nSystem.out.println(DASHES);\nSystem.out.println(\"Welcome to the Amazon EventBridge example scenario.\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out\nBasics 1238\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.println(\"1. Create an AWS Identity and Access Management (IAM) role\nto use with Amazon EventBridge.\");\nString roleArn = createIAMRole(iam, roleName, polJSON);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"2. Create an S3 bucket with EventBridge events\nenabled.\");\nif (checkBucket(s3Client, bucketName)) {\nSystem.out.println(\"Bucket \" + bucketName + \" already exists. Ending\nthis scenario.\");\nSystem.exit(1);\n}\ncreateBucket(s3Client, bucketName);\nThread.sleep(3000);\nsetBucketNotification(s3Client, bucketName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"3. Create a rule that triggers when an object is\nuploaded to Amazon S3.\");\nThread.sleep(10000);\naddEventRule(eventBrClient, roleArn, bucketName, eventRuleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. List rules on the event bus.\");\nlistRules(eventBrClient);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"5. Create a new SNS topic for testing and let the user\nsubscribe to the topic.\");\nString topicArn = createSnsTopic(snsClient, topicName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Add a target to the rule that sends an email to the\nspecified topic.", "mimetype": "text/plain", "start_char_idx": 1785700, "end_char_idx": 1789325, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "e824c63f-ba0b-4009-83c4-63ffc5035f7a": {"__data__": {"id_": "e824c63f-ba0b-4009-83c4-63ffc5035f7a", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3c2084cb-d6c5-4bb8-a6a9-bf10384ccd01", "node_type": "1", "metadata": {}, "hash": "2dade3fddb250c414124d1bbc1b646606c8b44988e49d1fae3d4990d73fac6ee", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7c2d71fd-0109-492f-875f-ac7194a0547f", "node_type": "1", "metadata": {}, "hash": "6fcb28119af368bdd0ece4b08f208b3e47808b7e54463d635c9954f6d8c6be58", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "Create a rule that triggers when an object is\nuploaded to Amazon S3.\");\nThread.sleep(10000);\naddEventRule(eventBrClient, roleArn, bucketName, eventRuleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"4. List rules on the event bus.\");\nlistRules(eventBrClient);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"5. Create a new SNS topic for testing and let the user\nsubscribe to the topic.\");\nString topicArn = createSnsTopic(snsClient, topicName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"6. Add a target to the rule that sends an email to the\nspecified topic.\");\nSystem.out.println(\"Enter your email to subscribe to the Amazon SNS\ntopic:\");\nString email = sc.nextLine();\nsubEmail(snsClient, topicArn, email);\nBasics 1239\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(\n\"Use the link in the email you received to confirm your\nsubscription. Then, press Enter to continue.\");\nsc.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"7. Create an EventBridge event that sends an email when\nan Amazon S3 object is created.\");\naddSnsEventRule(eventBrClient, eventRuleName, topicArn, topicName,\neventRuleName, bucketName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\" 8. List Targets.\");\nlistTargets(eventBrClient, eventRuleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\" 9. List the rules for the same target.\");\nlistTargetRules(eventBrClient, topicArn);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\" 10. Trigger the rule by uploading a file to the S3\nbucket.\");\nSystem.out.println(\"Press Enter to continue.\");\nsc.nextLine();\nuploadTextFiletoS3(s3Client, bucketName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"11. Disable a specific rule.\");\nchangeRuleState(eventBrClient, eventRuleName, false);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"12. Check and print the state of the rule.\");\ncheckRule(eventBrClient, eventRuleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"13. Add a transform to the rule to change the text of\nthe email.\");\nBasics 1240\nAWS SDK for Java 2.x Developer Guide for version 2.x\nupdateSnsEventRule(eventBrClient, topicArn, eventRuleName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"14. Enable a specific rule.\");\nchangeRuleState(eventBrClient, eventRuleName, true);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\" 15. Trigger the updated rule by uploading a file to the\nS3 bucket.\");\nSystem.out.println(\"Press Enter to continue.\");\nsc.nextLine();\nuploadTextFiletoS3(s3Client, bucketName);\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\" 16. Update the rule to be a custom rule pattern.\");\nupdateToCustomRule(eventBrClient, eventRuleName);\nSystem.out.println(\"Updated event rule \" + eventRuleName + \" to use a custom\npattern.\");\nupdateCustomRuleTargetWithTransform(eventBrClient, topicArn, eventRuleName);\nSystem.out.println(\"Updated event target \" + topicArn + \".\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"17. Sending an event to trigger the rule. This will\ntrigger a subscription email.\");\ntriggerCustomRule(eventBrClient, email);\nSystem.out.println(\"Events have been sent. Press Enter to continue.\");\nsc.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"18. Clean up resources.\");\nSystem.out.println(\"Do you want to clean up resources (y/n)\");\nString ans = sc.nextLine();\nif (ans.compareTo(\"y\") == 0) {\ncleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn,\neventRuleName, bucketName, roleName);\n} else {\nSystem.out.println(\"The resources will not be cleaned up.", "mimetype": "text/plain", "start_char_idx": 1788669, "end_char_idx": 1792584, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "7c2d71fd-0109-492f-875f-ac7194a0547f": {"__data__": {"id_": "7c2d71fd-0109-492f-875f-ac7194a0547f", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e824c63f-ba0b-4009-83c4-63ffc5035f7a", "node_type": "1", "metadata": {}, "hash": "dadc3c7d4eeac343baf93d927ff589f9cac88224216f9f98a635d83735137c1d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1317cd63-2099-4a67-8eba-e48c78fbc94d", "node_type": "1", "metadata": {}, "hash": "abb8feb1a2e4534b30359ad14a90ca3c9f384a1307beea945e1d7886709d4c7e", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "\");\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"17. Sending an event to trigger the rule. This will\ntrigger a subscription email.\");\ntriggerCustomRule(eventBrClient, email);\nSystem.out.println(\"Events have been sent. Press Enter to continue.\");\nsc.nextLine();\nSystem.out.println(DASHES);\nSystem.out.println(DASHES);\nSystem.out.println(\"18. Clean up resources.\");\nSystem.out.println(\"Do you want to clean up resources (y/n)\");\nString ans = sc.nextLine();\nif (ans.compareTo(\"y\") == 0) {\ncleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn,\neventRuleName, bucketName, roleName);\n} else {\nSystem.out.println(\"The resources will not be cleaned up. \");\n}\nSystem.out.println(DASHES);\nBasics 1241\nAWS SDK for Java 2.x Developer Guide for version 2.x\nSystem.out.println(DASHES);\nSystem.out.println(\"The Amazon EventBridge example scenario has successfully\ncompleted.\");\nSystem.out.println(DASHES);\n}\npublic static void cleanupResources(EventBridgeClient eventBrClient, SnsClient\nsnsClient, S3Client s3Client,\nIamClient iam, String topicArn, String eventRuleName, String bucketName,\nString roleName) {\nSystem.out.println(\"Removing all targets from the event rule.\");\ndeleteTargetsFromRule(eventBrClient, eventRuleName);\ndeleteRuleByName(eventBrClient, eventRuleName);\ndeleteSNSTopic(snsClient, topicArn);\ndeleteS3Bucket(s3Client, bucketName);\ndeleteRole(iam, roleName);\n}\npublic static void deleteRole(IamClient iam, String roleName) {\nString policyArn = \"arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess\";\nDetachRolePolicyRequest policyRequest = DetachRolePolicyRequest.builder()\n.policyArn(policyArn)\n.roleName(roleName)\n.build();\niam.detachRolePolicy(policyRequest);\nSystem.out.println(\"Successfully detached policy \" + policyArn + \" from role\n\" + roleName);\n// Delete the role.\nDeleteRoleRequest roleRequest = DeleteRoleRequest.builder()\n.roleName(roleName)\n.build();\niam.deleteRole(roleRequest);\nSystem.out.println(\"*** Successfully deleted \" + roleName);\n}\npublic static void deleteS3Bucket(S3Client s3Client, String bucketName) {\n// Remove all the objects from the S3 bucket.\nListObjectsRequest listObjects = ListObjectsRequest.builder()\n.bucket(bucketName)\n.build();\nBasics 1242\nAWS SDK for Java 2.x Developer Guide for version 2.x\nListObjectsResponse res = s3Client.listObjects(listObjects);\nList objects = res.contents();\nArrayList toDelete = new ArrayList<>();\nfor (S3Object myValue : objects) {\ntoDelete.add(ObjectIdentifier.builder()\n.key(myValue.key())\n.build());\n}\nDeleteObjectsRequest dor = DeleteObjectsRequest.builder()\n.bucket(bucketName)\n.delete(Delete.builder()\n.objects(toDelete).build())\n.build();\ns3Client.deleteObjects(dor);\n// Delete the S3 bucket.\nDeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()\n.bucket(bucketName)\n.build();\ns3Client.deleteBucket(deleteBucketRequest);\nSystem.out.println(\"You have deleted the bucket and the objects\");\n}\n// Delete the SNS topic.\npublic static void deleteSNSTopic(SnsClient snsClient, String topicArn) {\ntry {\nDeleteTopicRequest request = DeleteTopicRequest.builder()\n.topicArn(topicArn)\n.build();\nDeleteTopicResponse result = snsClient.deleteTopic(request);\nSystem.out.println(\"\\n\\nStatus was \" +\nresult.sdkHttpResponse().statusCode());\n} catch (SnsException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\nBasics 1243\nAWS SDK for Java 2.x Developer Guide for version 2.x\npublic static void deleteRuleByName(EventBridgeClient eventBrClient, String\nruleName) {\nDeleteRuleRequest ruleRequest = DeleteRuleRequest.builder()\n.name(ruleName)\n.build();\neventBrClient.deleteRule(ruleRequest);\nSystem.out.println(\"Successfully deleted the rule\");\n}\npublic static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String\neventRuleName) {\n// First, get all targets that will be deleted.\nListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder()\n.rule(eventRuleName)\n.build();\nListTargetsByRuleResponse response =\neventBrClient.listTargetsByRule(request);\nList allTargets = response.targets();\n// Get all targets and delete them.", "mimetype": "text/plain", "start_char_idx": 1791895, "end_char_idx": 1796029, "metadata_seperator": "\n", "text_template": "{metadata_str}\n\n{content}", "class_name": "TextNode"}, "__type__": "1"}, "1317cd63-2099-4a67-8eba-e48c78fbc94d": {"__data__": {"id_": "1317cd63-2099-4a67-8eba-e48c78fbc94d", "embedding": null, "metadata": {}, "excluded_embed_metadata_keys": [], "excluded_llm_metadata_keys": [], "relationships": {"1": {"node_id": "87e184ca-9a81-4558-ae8b-60c96e312094", "node_type": "4", "metadata": {}, "hash": "69ebc58d0529d879116007b5138e22794b9105ba2d49ee60fd0f91d67410c1e7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7c2d71fd-0109-492f-875f-ac7194a0547f", "node_type": "1", "metadata": {}, "hash": "6fcb28119af368bdd0ece4b08f208b3e47808b7e54463d635c9954f6d8c6be58", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b50e9816-4e8e-4125-829e-ec813b305c66", "node_type": "1", "metadata": {}, "hash": "bac105f8cee031c467b981eaf7b688fdc2b6c4af2bf7cb8edc842148bce7f7b1", "class_name": "RelatedNodeInfo"}}, "metadata_template": "{key}: {value}", "metadata_separator": "\n", "text": "ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder()\n.rule(eventRuleName)\n.build();\nListTargetsByRuleResponse response =\neventBrClient.listTargetsByRule(request);\nList allTargets = response.targets();\n// Get all targets and delete them.\nfor (Target myTarget : allTargets) {\nRemoveTargetsRequest removeTargetsRequest =\nRemoveTargetsRequest.builder()\n.rule(eventRuleName)\n.ids(myTarget.id())\n.build();\neventBrClient.removeTargets(removeTargetsRequest);\nSystem.out.println(\"Successfully removed the target\");\n}\n}\npublic static void triggerCustomRule(EventBridgeClient eventBrClient, String\nemail) {\nString json = \"{\" +\n\"\\\"UserEmail\\\": \\\"\" + email + \"\\\",\" +\n\"\\\"Message\\\": \\\"This event was generated by example code.\\\",\" +\n\"\\\"UtcTime\\\": \\\"Now.\\\"\" +\n\"}\";\nPutEventsRequestEntry entry = PutEventsRequestEntry.builder()\nBasics 1244\nAWS SDK for Java 2.x Developer Guide for version 2.x\n.source(\"ExampleSource\")\n.detail(json)\n.detailType(\"ExampleType\")\n.build();\nPutEventsRequest eventsRequest = PutEventsRequest.builder()\n.entries(entry)\n.build();\neventBrClient.putEvents(eventsRequest);\n}\npublic static void updateCustomRuleTargetWithTransform(EventBridgeClient\neventBrClient, String topicArn,\nString ruleName) {\nString targetId = java.util.UUID.randomUUID().toString();\nInputTransformer inputTransformer = InputTransformer.builder()\n.inputTemplate(\"\\\"Notification: sample event was received.\\\"\")\n.build();\nTarget target = Target.builder()\n.id(targetId)\n.arn(topicArn)\n.inputTransformer(inputTransformer)\n.build();\ntry {\nPutTargetsRequest targetsRequest = PutTargetsRequest.builder()\n.rule(ruleName)\n.targets(target)\n.eventBusName(null)\n.build();\neventBrClient.putTargets(targetsRequest);\n} catch (EventBridgeException e) {\nSystem.err.println(e.awsErrorDetails().errorMessage());\nSystem.exit(1);\n}\n}\npublic static void updateToCustomRule(EventBridgeClient eventBrClient, String\nruleName) {\nString customEventsPattern = \"{\" +\n\"\\\"source\\\": [\\\"ExampleSource\\\"],\" +\nBasics 1245\nAWS SDK for Java 2.x Developer Guide for version 2.x\n\"\\\"detail-type\\\": [\\\"ExampleType\\\"]\" +\n\"}\";\nPutRuleRequest request = PutRuleRequest.builder()\n.name(ruleName)\n.description(\"Custom test rule\")\n.eventPattern(customEventsPattern)\n.build();\neventBrClient.putRule(request);\n}\n// Update an Amazon S3 object created rule with a transform on the target.\npublic static void updateSnsEventRule(EventBridgeClient eventBrClient, String\ntopicArn, String ruleName) {\nString targetId = java.util.UUID.randomUUID().toString();\nMap myMap = new HashMap<>();\nmyMap.put(\"bucket\", \"$.detail.bucket.name\");\nmyMap.put(\"time\", \"$.time\");\nInputTransformer inputTransformer = InputTransformer.builder()\n.inputTemplate(\"\\\"Notification: an object was uploaded to bucket\n at