001package com.nimbusds.oauth2.sdk.util; 002 003 004import java.net.URI; 005import java.net.URISyntaxException; 006import java.util.ArrayList; 007import java.util.Collections; 008import java.util.List; 009 010import com.nimbusds.oauth2.sdk.ParseException; 011import net.minidev.json.JSONArray; 012import org.apache.commons.collections.CollectionUtils; 013 014 015/** 016 * JSON array helper methods for parsing and typed retrieval of values. 017 */ 018public class JSONArrayUtils { 019 020 021 /** 022 * Parses a JSON array. 023 * 024 * <p>Specific JSON to Java entity mapping (as per JSON Simple): 025 * 026 * <ul> 027 * <li>JSON numbers mapped to {@code java.lang.Number}. 028 * <li>JSON integer numbers mapped to {@code long}. 029 * <li>JSON fraction numbers mapped to {@code double}. 030 * </ul> 031 * 032 * @param s The JSON array string to parse. Must not be {@code null}. 033 * 034 * @return The JSON array. 035 * 036 * @throws ParseException If the string cannot be parsed to a JSON 037 * array. 038 */ 039 public static JSONArray parse(final String s) 040 throws ParseException { 041 042 Object o = JSONUtils.parseJSON(s); 043 044 if (o instanceof JSONArray) 045 return (JSONArray)o; 046 else 047 throw new ParseException("The JSON entity is not an array"); 048 } 049 050 051 /** 052 * Converts the specified JSON array to a string list. 053 * 054 * @param jsonArray The JSON array. May be {@code null}. 055 * 056 * @return The corresponding string list, empty list if the JSON array 057 * is {@code null} or empty. 058 */ 059 public static List<String> toStringList(final JSONArray jsonArray) { 060 061 if (CollectionUtils.isEmpty(jsonArray)) { 062 return Collections.emptyList(); 063 } 064 065 List<String> stringList = new ArrayList<>(jsonArray.size()); 066 067 for (Object o: jsonArray) { 068 069 if (o == null) { 070 continue; // skip 071 } 072 073 stringList.add(o.toString()); 074 } 075 076 return stringList; 077 } 078 079 080 /** 081 * Converts the specified JSON array to a URI list. 082 * 083 * @param jsonArray The JSON array. May be {@code null}. 084 * 085 * @return The corresponding URI list, empty list if the JSON array is 086 * {@code null} or empty. 087 * 088 * @throws ParseException If a JSON array item couldn't be parsed to a 089 * URI. 090 */ 091 public static List<URI> toURIList(final JSONArray jsonArray) 092 throws ParseException { 093 094 if (CollectionUtils.isEmpty(jsonArray)) { 095 return Collections.emptyList(); 096 } 097 098 List<URI> uriList = new ArrayList<>(jsonArray.size()); 099 100 for (Object o: jsonArray) { 101 102 if (o == null) { 103 continue; // skip 104 } 105 106 try { 107 uriList.add(new URI(o.toString())); 108 } catch (URISyntaxException e) { 109 throw new ParseException("Illegal URI: " + e.getMessage(), e); 110 } 111 } 112 113 return uriList; 114 } 115}