int phase = 0;
try
{
- phase = Integer.parseInt(sf.getPhase());
+ String s = sf.getPhase();
+ if (s != null)
+ {
+ phase = Integer.parseInt(s);
+ }
} catch (NumberFormatException e)
{
- // ignore
+ // SwingJS -- need to avoid these.
}
/*
* phase > 0 on first codon means 5' incomplete - skip to the start
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
// TODO: use a vararg String... for getSequenceRecords instead?
List<String> queries = new ArrayList<>();
queries.add(query);
- BufferedReader fp = getSequenceReader(queries);
- if (fp == null)
- {
- return null;
- }
-
- SequenceI seq = parseFeaturesJson(fp);
+ SequenceI seq = parseFeaturesJson(queries);
+ if (seq == null)
+ return null;
return new Alignment(new SequenceI[] { seq });
}
* @param br
* @return
*/
- private SequenceI parseFeaturesJson(BufferedReader br)
+ @SuppressWarnings("unchecked")
+private SequenceI parseFeaturesJson(List<String> queries)
{
+
+
SequenceI seq = new Sequence("Dummy", "");
- JSONParser jp = new JSONParser();
try
{
- JSONArray responses = (JSONArray) jp.parse(br);
- Iterator rvals = responses.iterator();
+
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(null, queries, -1, MODE_ITERATOR, null);
+ if (rvals == null)
+ return null;
while (rvals.hasNext())
{
try
{
- JSONObject obj = (JSONObject) rvals.next();
+ Map<String, Object> obj = (Map<String, Object>) rvals.next();
String type = obj.get("feature_type").toString();
int start = Integer.parseInt(obj.get("start").toString());
int end = Integer.parseInt(obj.get("end").toString());
String source = obj.get("source").toString();
String strand = obj.get("strand").toString();
String alleles = JSONUtils
- .arrayToList((JSONArray) obj.get("alleles"));
+ .arrayToStringList((List<Object>) obj.get("alleles"));
String clinSig = JSONUtils
- .arrayToList(
- (JSONArray) obj.get("clinical_significance"));
+ .arrayToStringList(
+ (List<Object>) obj.get("clinical_significance"));
/*
* convert 'variation' to 'sequence_variant', and 'cds' to 'CDS'
}
} catch (ParseException | IOException e)
{
+ e.printStackTrace();
// ignore
}
return seq;
}
- /**
+
+/**
* Returns the first non-null attribute found (if any) as a string
*
* @param obj
* @param keys
* @return
*/
- protected String getFirstNotNull(JSONObject obj, String... keys)
+ protected String getFirstNotNull(Map<String, Object> obj, String... keys)
{
String desc = null;
* @param obj
* @param key
*/
- protected void setFeatureAttribute(SequenceFeature sf, JSONObject obj,
+ protected void setFeatureAttribute(SequenceFeature sf, Map<String, Object> obj,
String key)
{
Object object = obj.get(key);
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefSource;
+import jalview.util.JSONUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
-import org.json.simple.JSONArray;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class EnsemblInfo extends EnsemblRestClient
* for convenience, pre-fill ensembl.org as the domain for "ENSEMBL"
*/
divisions.put(DBRefSource.ENSEMBL.toUpperCase(), ensemblDomain);
-
- BufferedReader br = null;
try
{
- URL url = getDivisionsUrl(ensemblGenomesDomain);
- if (url != null)
- {
- br = getHttpResponse(url, null);
- }
- parseResponse(br, ensemblGenomesDomain);
- } catch (IOException e)
- {
- // ignore
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
- }
- }
-
- /**
- * Parses the JSON response to /info/divisions, and add each to the lookup map
- *
- * @param br
- * @param domain
- */
- void parseResponse(BufferedReader br, String domain)
- {
- JSONParser jp = new JSONParser();
-
- try
- {
- JSONArray parsed = (JSONArray) jp.parse(br);
-
- Iterator rvals = parsed.iterator();
+ @SuppressWarnings("unchecked")
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(getDivisionsUrl(ensemblGenomesDomain), null, -1, MODE_ITERATOR, null);
+ if (rvals == null)
+ return;
while (rvals.hasNext())
{
String division = rvals.next().toString();
- divisions.put(division.toUpperCase(), domain);
+ divisions.put(division.toUpperCase(), ensemblGenomesDomain);
}
} catch (IOException | ParseException | NumberFormatException e)
{
import jalview.datamodel.GeneLociI;
import jalview.util.MapList;
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* @param br
* @return
*/
- protected String parseGeneId(JSONObject val)
+ protected String parseGeneId(Map<String, Object> val)
{
if (val == null)
{
public String getSpecies(String identifier)
{
String species = null;
- JSONObject json = getResult(identifier, null);
+ Map<String, Object> json = getResult(identifier, null);
if (json != null)
{
Object o = json.get(SPECIES);
}
/**
- * Calls the /lookup/id rest service and returns the response as a JSONObject,
+ * Calls the /lookup/id rest service and returns the response as a Map<String, Object>,
* or null if any error
*
* @param identifier
* (optional)
* @return
*/
- protected JSONObject getResult(String identifier, String objectType)
+ @SuppressWarnings("unchecked")
+ protected Map<String, Object> getResult(String identifier, String objectType)
{
List<String> ids = Arrays.asList(new String[] { identifier });
- BufferedReader br = null;
try
{
- URL url = getUrl(identifier, objectType);
-
- if (url != null)
- {
- br = getHttpResponse(url, ids);
- }
- return br == null ? null : (JSONObject) (new JSONParser().parse(br));
- } catch (IOException | ParseException e)
+ return (Map<String, Object>) getJSON(getUrl(identifier, objectType), ids, -1, MODE_MAP, null);
+ }
+ catch (IOException | ParseException e)
{
System.err.println("Error parsing " + identifier + " lookup response "
+ e.getMessage());
return null;
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
}
}
* @param json
* @return
*/
- GeneLociI parseGeneLoci(JSONObject json)
+ GeneLociI parseGeneLoci(Map<String, Object> json)
{
if (json == null)
{
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefSource;
import jalview.datamodel.GeneLociI;
+import jalview.util.JSONUtils;
import jalview.util.MapList;
import java.io.BufferedReader;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class EnsemblMap extends EnsemblRestClient
String fromRef, String toRef, int[] queryRange)
{
URL url = null;
- BufferedReader br = null;
-
try
{
url = getAssemblyMapUrl(species, chromosome, fromRef, toRef, queryRange[0],
queryRange[1]);
- br = getHttpResponse(url, null);
- return (parseAssemblyMappingResponse(br));
+ return (parseAssemblyMappingResponse(url));
} catch (Throwable t)
{
System.out.println("Error calling " + url + ": " + t.getMessage());
return null;
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
}
}
* @param br
* @return
*/
- protected int[] parseAssemblyMappingResponse(BufferedReader br)
+ @SuppressWarnings("unchecked")
+ protected int[] parseAssemblyMappingResponse(URL url)
{
int[] result = null;
- JSONParser jp = new JSONParser();
try
{
- JSONObject parsed = (JSONObject) jp.parse(br);
- JSONArray mappings = (JSONArray) parsed.get(MAPPINGS);
-
- Iterator rvals = mappings.iterator();
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
+ if (rvals == null)
+ return null;
while (rvals.hasNext())
{
// todo check for "mapped"
- JSONObject val = (JSONObject) rvals.next();
- JSONObject mapped = (JSONObject) val.get(MAPPED);
+ Map<String, Object> val = (Map<String, Object>) rvals.next();
+ Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
int start = Integer.parseInt(mapped.get("start").toString());
int end = Integer.parseInt(mapped.get("end").toString());
String strand = mapped.get("strand").toString();
int end, String cdsOrCdna)
{
URL url = null;
- BufferedReader br = null;
-
try
{
String domain = new EnsemblInfo().getDomain(division);
if (domain != null)
{
url = getIdMapUrl(domain, accession, start, end, cdsOrCdna);
- br = getHttpResponse(url, null);
- if (br != null)
- {
- return (parseIdMappingResponse(br, accession, domain));
- }
+ return (parseIdMappingResponse(url, accession, domain));
}
return null;
} catch (Throwable t)
{
System.out.println("Error calling " + url + ": " + t.getMessage());
return null;
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
}
}
* @param domain
* @return
*/
- GeneLociI parseIdMappingResponse(BufferedReader br, String accession,
+ @SuppressWarnings("unchecked")
+GeneLociI parseIdMappingResponse(URL url, String accession,
String domain)
{
- JSONParser jp = new JSONParser();
try
{
- JSONObject parsed = (JSONObject) jp.parse(br);
- JSONArray mappings = (JSONArray) parsed.get(MAPPINGS);
-
- Iterator rvals = mappings.iterator();
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
+ if (rvals == null)
+ return null;
String assembly = null;
String chromosome = null;
int fromEnd = 0;
while (rvals.hasNext())
{
- JSONObject val = (JSONObject) rvals.next();
- JSONObject original = (JSONObject) val.get("original");
+ Map<String, Object> val = (Map<String, Object>) rvals.next();
+ Map<String, Object> original = (Map<String, Object>) val.get("original");
fromEnd = Integer.parseInt(original.get("end").toString());
- JSONObject mapped = (JSONObject) val.get(MAPPED);
+ Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
int start = Integer.parseInt(mapped.get("start").toString());
int end = Integer.parseInt(mapped.get("end").toString());
String ass = mapped.get("assembly_name").toString();
package jalview.ext.ensembl;
import jalview.bin.Cache;
-import jalview.bin.Jalview;
+import jalview.javascript.json.JSON;
+import jalview.util.JSONUtils;
+import jalview.util.Platform;
import jalview.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import javax.ws.rs.HttpMethod;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
/**
* Base class for Ensembl REST service clients
* @see http://rest.ensembl.org/documentation/info/ping
* @return
*/
- boolean checkEnsembl()
+ @SuppressWarnings("unchecked")
+boolean checkEnsembl()
{
BufferedReader br = null;
String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
{
// note this format works for both ensembl and ensemblgenomes
// info/ping.json works for ensembl only (March 2016)
- URL ping = new URL(pingUrl);
-
+
+
+
+
/*
* expect {"ping":1} if ok
* if ping takes more than 2 seconds to respond, treat as if unavailable
*/
- br = getHttpResponse(ping, null, 2 * 1000);
- if (br == null)
- {
- // error reponse status
- return false;
- }
- JSONParser jp = new JSONParser();
- JSONObject val = (JSONObject) jp.parse(br);
+ Map<String, Object> val = (Map<String, Object>) getJSON(new URL(pingUrl), null, 2 * 1000, MODE_MAP, null);
+ if (val == null)
+ return false;
String pingString = val.get("ping").toString();
return pingString != null;
} catch (Throwable t)
return false;
}
- /**
- * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
- * If the request failed the return value may be null.
- *
- * @param ids
- * @return
- * @throws IOException
- */
- protected BufferedReader getSequenceReader(List<String> ids)
- throws IOException
- {
- URL url = getUrl(ids);
-
- BufferedReader reader = getHttpResponse(url, ids);
- return reader;
- }
-
- /**
- * Gets a reader to the HTTP response, using the default read timeout of 5
- * minutes
- *
- * @param url
- * @param ids
- * @return
- * @throws IOException
- */
- protected BufferedReader getHttpResponse(URL url, List<String> ids)
- throws IOException
- {
- return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
- }
+
+ protected final static int MODE_ARRAY = 0;
+ protected final static int MODE_MAP = 1;
+ protected final static int MODE_ITERATOR = 2;
+
+// /**
+// * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
+// * If the request failed the return value may be null.
+// *
+// * @param ids
+// * @return
+// * @throws IOException
+// * @throws ParseException
+// */
+// protected Object getSequenceJSON(List<String> ids, int mode)
+// throws IOException, ParseException
+// {
+// URL url = getUrl(ids);
+// return getJSON(url, ids, -1, mode);
+// }
+//
+// /**
+// * Gets a reader to the HTTP response, using the default read timeout of 5
+// * minutes
+// *
+// * @param url
+// * @param ids
+// * @return
+// * @throws IOException
+// */
+// protected BufferedReader getHttpResponse(URL url, List<String> ids)
+// throws IOException
+// {
+// return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
+// }
/**
* Sends the HTTP request and gets the response as a reader. Returns null if
* @return
* @throws IOException
*/
- protected BufferedReader getHttpResponse(URL url, List<String> ids,
+ private BufferedReader getHttpResponse(URL url, List<String> ids,
int readTimeout) throws IOException
{
+ if (readTimeout < 0)
+ readTimeout = DEFAULT_READ_TIMEOUT;
int retriesLeft = MAX_RETRIES;
HttpURLConnection connection = null;
int responseCode = 0;
-
+
+ if (Platform.isJS()) {
+ JSON.setAjax(url);
+ }
+
while (retriesLeft > 0)
{
connection = tryConnection(url, ids, readTimeout);
* note: a GET request for an invalid id returns an error code e.g. 415
* but POST request returns 200 and an empty Fasta response
*/
- System.err.println("Response code " + responseCode + " for " + url);
+ System.err.println("Response code " + responseCode);// + " for " + url);
return null;
}
+
InputStream response = connection.getInputStream();
+
+ if (Platform.isJS()) {
+ return JSON.getJSONReader(response);
+ }
// System.out.println(getClass().getName() + " took "
// + (System.currentTimeMillis() - now) + "ms to fetch");
- BufferedReader reader = null;
- reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
- return reader;
+ return new BufferedReader(new InputStreamReader(response, "UTF-8"));
}
/**
int readTimeout) throws IOException, ProtocolException
{
// System.out.println(System.currentTimeMillis() + " " + url);
+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/*
wr.close();
}
+ /**
+ * Primary access point to parsed JSON data, including the call to retrieve and
+ * parsing.
+ *
+ * @param url request url; if null, getUrl(ids) will be used
+ * @param ids optional; may be null
+ * @param msDelay -1 for default delay
+ * @param mode map, array, or array iterator
+ * @param mapKey an optional key for an outer map
+ * @return a Map, List, Iterator, or null
+ * @throws IOException
+ * @throws ParseException
+ *
+ * @author Bob Hanson 2019
+ */
+ @SuppressWarnings("unchecked")
+ protected Object getJSON(URL url, List<String> ids, int msDelay, int mode, String mapKey) throws IOException, ParseException {
+
+ if (url == null)
+ url = getUrl(ids);
+
+ Platform.timeCheck("EnsembleRestClient.getJSON0 " + url, Platform.TIME_MARK);
+
+ Reader br = null;
+ try {
+ br = (url == null ? null : getHttpResponse(url, ids, msDelay));
+
+ Platform.timeCheck("EnsembleRestClient.getJSON1 parsing... ", Platform.TIME_MARK);
+
+ Object ret = (br == null ? null : JSONUtils.parse(br));
+
+ Platform.timeCheck("EnsembleRestClient.getJSON2 ...done ", Platform.TIME_MARK);
+
+ if (ret != null && mapKey != null)
+ ret = ((Map<String, Object>) ret).get(mapKey);
+ if (ret == null)
+ {
+ return null;
+ }
+ switch (mode) {
+ case MODE_ARRAY:
+ case MODE_MAP:
+ break;
+ case MODE_ITERATOR:
+ ret = ((List<Object>) ret).iterator();
+ break;
+ }
+ return ret;
+
+ } finally
+ {
+ if (br != null)
+ {
+ try
+ {
+ br.close();
+ } catch (IOException e)
+ {
+ // ignore
+ }
+ }
+ }
+ }
+
+
+
/**
* Fetches and checks Ensembl's REST version number
*
* @return
*/
+ @SuppressWarnings("unchecked")
private void checkEnsemblRestVersion()
{
EnsemblData info = domainData.get(getDomain());
- JSONParser jp = new JSONParser();
- URL url = null;
try
{
- url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
- BufferedReader br = getHttpResponse(url, null);
- if (br == null)
- {
- return;
- }
- JSONObject val = (JSONObject) jp.parse(br);
+ Map<String, Object> val = (Map<String, Object>) getJSON(new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON), null, -1, MODE_MAP, null);
+ if (val == null)
+ return;
String version = val.get("release").toString();
String majorVersion = version.substring(0, version.indexOf("."));
String expected = info.expectedRestVersion;
*
* @return
*/
+ @SuppressWarnings("unchecked")
private void checkEnsemblDataVersion()
{
- JSONParser jp = new JSONParser();
- URL url = null;
- BufferedReader br = null;
-
- try
- {
- url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
- br = getHttpResponse(url, null);
- if (br != null)
- {
- JSONObject val = (JSONObject) jp.parse(br);
- JSONArray versions = (JSONArray) val.get("releases");
- domainData.get(getDomain()).dataVersion = versions.get(0)
- .toString();
- }
- } catch (Throwable t)
- {
- System.err.println(
- "Error checking Ensembl data version: " + t.getMessage());
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
- }
+ Map<String, Object> val;
+ try
+ {
+ val = (Map<String, Object>) getJSON(
+ new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON), null, -1, MODE_MAP, null);
+ if (val == null)
+ return;
+ List<Object> versions = (List<Object>) val.get("releases");
+ domainData.get(getDomain()).dataVersion = versions.get(0).toString();
+ } catch (Throwable e) {//could be IOException | ParseException e) {
+ System.err.println("Error checking Ensembl data version: " + e.getMessage());
+ }
}
public String getEnsemblDataVersion()
import jalview.util.DBRefUtils;
import jalview.util.IntRangeComparator;
import jalview.util.MapList;
+import jalview.util.Platform;
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
String accId = querySeq.getName();
try
{
+ System.out.println("Adding protein product for " + accId);
AlignmentI protein = new EnsemblProtein(getDomain())
.getSequenceRecords(accId);
if (protein == null || protein.getHeight() == 0)
inProgress = false;
throw new JalviewException("ENSEMBL Rest API not available.");
}
- BufferedReader br = getSequenceReader(ids);
- if (br == null)
- {
- return alignment;
- }
+ Platform.timeCheck("EnsemblSeqProx.fetchSeq ", Platform.TIME_MARK);
- List<SequenceI> seqs = parseSequenceJson(br);
+ List<SequenceI> seqs = parseSequenceJson(ids);
+ if (seqs == null)
+ return alignment;
if (seqs.isEmpty())
{
* @return a single jalview.datamodel.Sequence
* @see http://rest.ensembl.org/documentation/info/sequence_id
*/
- protected List<SequenceI> parseSequenceJson(BufferedReader br)
+ @SuppressWarnings("unchecked")
+ protected List<SequenceI> parseSequenceJson(List<String> ids)
{
- JSONParser jp = new JSONParser();
List<SequenceI> result = new ArrayList<>();
try
{
* for now, assumes only one sequence returned; refactor if needed
* in future to handle a JSONArray with more than one
*/
- final JSONObject val = (JSONObject) jp.parse(br);
+ Map<String, Object> val = (Map<String, Object>) getJSON(null, ids, -1, MODE_MAP, null);
+ if (val == null)
+ return null;
Object s = val.get("desc");
String desc = s == null ? null : s.toString();
s = val.get("id");
*/
package jalview.ext.ensembl;
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
super(domain, dbName, dbVersion);
}
- /**
- * Returns the first "id" value in gene identifier format from the JSON
- * response, or null if none found
- *
- * @param br
- * @return
- * @throws IOException
- */
- protected String parseSymbolResponse(BufferedReader br) throws IOException
- {
- JSONParser jp = new JSONParser();
- String result = null;
- try
- {
- JSONArray responses = (JSONArray) jp.parse(br);
- Iterator rvals = responses.iterator();
- while (rvals.hasNext())
- {
- JSONObject val = (JSONObject) rvals.next();
- String id = val.get(JSON_ID).toString();
- String type = val.get(TYPE).toString();
- if (id != null && GENE.equals(type))
- {
- result = id;
- break;
- }
- }
- } catch (ParseException e)
- {
- // ignore
- }
- return result;
- }
+// /**
+// * Returns the first "id" value in gene identifier format from the JSON
+// * response, or null if none found
+// *
+// * @param br
+// * @return
+// * @throws IOException
+// */
+// @SuppressWarnings("unchecked")
+//protected String parseSymbolResponse(BufferedReader br) throws IOException
+// {
+// }
/**
* Constructs the URL for the REST symbol endpoint
* @param identifier
* @return
*/
+ @SuppressWarnings("unchecked")
public List<String> getGeneIds(String identifier)
{
List<String> result = new ArrayList<String>();
ids.add(identifier);
String[] queries = identifier.split(getAccessionSeparator());
- BufferedReader br = null;
try
{
for (String query : queries)
{
for (Species taxon : Species.getModelOrganisms())
{
- URL url = getUrl(query, taxon, GENE);
- if (url != null)
+ String geneId = null;///parseSymbolResponse(br);
+ try
{
- br = getHttpResponse(url, ids);
- if (br != null)
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(getUrl(query, taxon, GENE), ids, -1, MODE_ITERATOR, null);
+ if (rvals == null)
+ continue;
+ while (rvals.hasNext())
{
- String geneId = parseSymbolResponse(br);
- if (geneId != null && !result.contains(geneId))
+ Map<String, Object> val = (Map<String, Object>) rvals.next();
+ String id = val.get(JSON_ID).toString();
+ String type = val.get(TYPE).toString();
+ if (id != null && GENE.equals(type))
{
- result.add(geneId);
+ geneId = id;
+ break;
}
}
+ } catch (ParseException e)
+ {
+ // ignore
+ }
+
+ if (geneId != null && !result.contains(geneId))
+ {
+ result.add(geneId);
}
}
}
} catch (IOException e)
{
// ignore
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
}
return result;
}
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
import jalview.util.DBRefUtils;
+import jalview.util.JSONUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* an Ensembl stable identifier
* @return
*/
+ @SuppressWarnings("unchecked")
public List<DBRefEntry> getCrossReferences(String identifier)
{
List<DBRefEntry> result = new ArrayList<>();
List<String> ids = new ArrayList<>();
ids.add(identifier);
- BufferedReader br = null;
try
{
- URL url = getUrl(identifier);
- if (url != null)
- {
- br = getHttpResponse(url, ids);
- if (br != null)
- {
- result = parseResponse(br);
- }
- }
- } catch (IOException e)
- {
- // ignore
- } finally
- {
- if (br != null)
- {
- try
- {
- br.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
- }
-
- return result;
- }
-
- /**
- * Parses "primary_id" and "dbname" values from the JSON response and
- * constructs a DBRefEntry. Returns a list of the DBRefEntry created. Note we
- * don't parse "synonyms" as they appear to be either redirected or obsolete
- * in Uniprot.
- *
- * @param br
- * @return
- * @throws IOException
- */
- protected List<DBRefEntry> parseResponse(BufferedReader br)
- throws IOException
- {
- JSONParser jp = new JSONParser();
- List<DBRefEntry> result = new ArrayList<>();
- try
- {
- JSONArray responses = (JSONArray) jp.parse(br);
- Iterator rvals = responses.iterator();
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(getUrl(identifier), ids, -1, MODE_ITERATOR, null);
while (rvals.hasNext())
{
- JSONObject val = (JSONObject) rvals.next();
+ Map<String, Object> val = (Map<String, Object>) rvals.next();
String db = val.get("dbname").toString();
String id = val.get("primary_id").toString();
if (db != null && id != null
result.add(dbref);
}
}
- } catch (ParseException e)
+ } catch (ParseException | IOException e)
{
// ignore
}
return result;
}
+// /**
+// * Parses "primary_id" and "dbname" values from the JSON response and
+// * constructs a DBRefEntry. Returns a list of the DBRefEntry created. Note we
+// * don't parse "synonyms" as they appear to be either redirected or obsolete
+// * in Uniprot.
+// *
+// * @param br
+// * @return
+// * @throws IOException
+// */
+// @SuppressWarnings("unchecked")
+//protected List<DBRefEntry> parseResponse(BufferedReader br)
+// throws IOException
+// {
+// return result;
+// }
+//
private String xrefVersion = "ENSEMBL:0";
/**
*/
package jalview.ext.paradise;
+import jalview.util.JSONUtils;
import jalview.util.MessageManager;
import jalview.ws.HttpClientUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
import org.json.simple.parser.ContentHandler;
import org.json.simple.parser.ParseException;
}
+ /**
+ * @param respons
+ * @return
+ * @throws Exception
+ */
public static Iterator<Reader> processJsonResponseFor(Reader respons)
throws Exception
{
- org.json.simple.parser.JSONParser jp = new org.json.simple.parser.JSONParser();
+ // BH 2019 never called?
try
{
- final JSONArray responses = (JSONArray) jp.parse(respons);
- final Iterator rvals = responses.iterator();
+ @SuppressWarnings("unchecked")
+ final Iterator<Object> rvals = ((List<Object>) JSONUtils.parse(respons)).iterator();
return new Iterator<Reader>()
{
@Override
return rvals.hasNext();
}
- @Override
+ @SuppressWarnings("unchecked")
+ @Override
public Reader next()
{
- JSONObject val = (JSONObject) rvals.next();
+ Map<String, Object> val = (Map<String, Object>) rvals.next();
Object sval = null;
try
sval = "";
}
- return new StringReader((sval instanceof JSONObject)
- ? ((JSONObject) sval).toString()
- : sval.toString());
+ return new StringReader(sval.toString());
}
import jalview.fts.core.FTSRestClient;
import jalview.fts.core.FTSRestRequest;
import jalview.fts.core.FTSRestResponse;
+import jalview.util.JSONUtils;
import jalview.util.MessageManager;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import javax.ws.rs.core.MediaType;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sun.jersey.api.client.Client;
* the JSON string containing error message from the server
* @return the processed error message from the JSON string
*/
- public static String parseJsonExceptionString(String jsonErrorResponse)
+ @SuppressWarnings("unchecked")
+public static String parseJsonExceptionString(String jsonErrorResponse)
{
StringBuilder errorMessage = new StringBuilder(
"\n============= PDB Rest Client RunTime error =============\n");
//
try
{
- JSONParser jsonParser = new JSONParser();
- JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
- JSONObject errorResponse = (JSONObject) jsonObj.get("error");
+ Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
+ Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
- JSONObject responseHeader = (JSONObject) jsonObj
+ Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
.get("responseHeader");
- JSONObject paramsObj = (JSONObject) responseHeader.get("params");
+ Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
String status = responseHeader.get("status").toString();
String message = errorResponse.get("msg").toString();
String query = paramsObj.get("q").toString();
List<FTSData> result = null;
try
{
- JSONParser jsonParser = new JSONParser();
- JSONObject jsonObj = (JSONObject) jsonParser
- .parse(pdbJsonResponseString);
-
- JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
- String queryTime = ((JSONObject) jsonObj.get("responseHeader"))
+ Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
+ Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
+ String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
.get("QTime").toString();
int numFound = Integer
.valueOf(pdbResponse.get("numFound").toString());
if (numFound > 0)
{
result = new ArrayList<FTSData>();
- JSONArray docs = (JSONArray) pdbResponse.get("docs");
- for (Iterator<JSONObject> docIter = docs.iterator(); docIter
+ List<Object> docs = (List<Object>) pdbResponse.get("docs");
+ for (Iterator<Object> docIter = docs.iterator(); docIter
.hasNext();)
{
- JSONObject doc = docIter.next();
+ Map<String, Object> doc = (Map<String, Object>) docIter.next();
result.add(getFTSData(doc, pdbRestRequest));
}
searchResult.setNumberOfItemsFound(numFound);
return searchResult;
}
- public static FTSData getFTSData(JSONObject pdbJsonDoc,
+ public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
FTSRestRequest request)
{
return allDefaultDisplayedStructureDataColumns;
}
- public static void main(String[] args) {
+ @SuppressWarnings("unchecked")
+public static void main(String[] args) {
// check for transpiler fix associated with JSONParser yylex.java use of charAt()
int z = c ^ 5;
String result = s +x + y + z;
assert (result == "e103982102");
- JSONParser jsonParser = new JSONParser();
try
{
- JSONObject jsonObj = (JSONObject) jsonParser.parse("{\"a\":3}");
+ Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse("{\"a\":3}");
System.out.println(jsonObj);
} catch (ParseException e)
{
import jalview.schemes.ResidueColourScheme;
import jalview.util.ColorUtils;
import jalview.util.Format;
+import jalview.util.JSONUtils;
import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
import java.awt.Color;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Vector;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-
public class JSONFile extends AlignFile implements ComplexAlignFile
{
private static String version = new BuildDetails().getVersion();
jsonAlignmentPojo.getSeqGroups().add(seqGrpPojo);
}
}
- org.json.JSONObject generatedJSon = new org.json.JSONObject(
- jsonAlignmentPojo);
+ org.json.JSONObject generatedJSon = new org.json.JSONObject(jsonAlignmentPojo);
jsonOutput = generatedJSon.toString();
return jsonOutput.replaceAll("xstart", "xStart").replaceAll("xend",
"xEnd");
{
try
{
- JSONParser jsonParser = new JSONParser();
- JSONObject alignmentJsonObj = (JSONObject) jsonParser
- .parse(jsonAlignmentString);
- JSONArray seqJsonArray = (JSONArray) alignmentJsonObj.get("seqs");
- JSONArray alAnnotJsonArray = (JSONArray) alignmentJsonObj
+ Map<String, Object> alignmentJsonObj = (Map<String, Object>) JSONUtils.parse(jsonAlignmentString);
+ List<Object> seqJsonArray = (List<Object>) alignmentJsonObj.get("seqs");
+ List<Object> alAnnotJsonArray = (List<Object>) alignmentJsonObj
.get("alignAnnotation");
- JSONArray jsonSeqArray = (JSONArray) alignmentJsonObj
+ List<Object> jsonSeqArray = (List<Object>) alignmentJsonObj
.get("seqFeatures");
- JSONArray seqGrpJsonArray = (JSONArray) alignmentJsonObj
+ List<Object> seqGrpJsonArray = (List<Object>) alignmentJsonObj
.get("seqGroups");
- JSONObject jvSettingsJsonObj = (JSONObject) alignmentJsonObj
+ Map<String, Object> jvSettingsJsonObj = (Map<String, Object>) alignmentJsonObj
.get("appSettings");
if (jvSettingsJsonObj != null)
hiddenSequences = new ArrayList<>();
seqMap = new Hashtable<>();
- for (Iterator<JSONObject> sequenceIter = seqJsonArray
- .iterator(); sequenceIter.hasNext();)
+ for (Iterator<Object> sequenceIter = seqJsonArray.iterator(); sequenceIter.hasNext();)
{
- JSONObject sequence = sequenceIter.next();
+ Map<String, Object> sequence = (Map<String, Object>) sequenceIter.next();
String sequcenceString = sequence.get("seq").toString();
String sequenceName = sequence.get("name").toString();
String seqUniqueId = sequence.get("id").toString();
parseFeatures(jsonSeqArray);
- for (Iterator<JSONObject> seqGrpIter = seqGrpJsonArray
- .iterator(); seqGrpIter.hasNext();)
+ for (Iterator<Object> seqGrpIter = seqGrpJsonArray.iterator(); seqGrpIter.hasNext();)
{
- JSONObject seqGrpObj = seqGrpIter.next();
+ Map<String, Object> seqGrpObj = (Map<String, Object>)seqGrpIter.next();
String grpName = seqGrpObj.get("groupName").toString();
String colourScheme = seqGrpObj.get("colourScheme").toString();
String description = (seqGrpObj.get("description") == null) ? null
int startRes = Integer
.valueOf(seqGrpObj.get("startRes").toString());
int endRes = Integer.valueOf(seqGrpObj.get("endRes").toString());
- JSONArray sequenceRefs = (JSONArray) seqGrpObj.get("sequenceRefs");
+ List<Object> sequenceRefs = (List<Object>) seqGrpObj.get("sequenceRefs");
ArrayList<SequenceI> grpSeqs = new ArrayList<>();
if (sequenceRefs.size() > 0)
{
- Iterator<String> seqHashIter = sequenceRefs.iterator();
+ Iterator<Object> seqHashIter = sequenceRefs.iterator();
while (seqHashIter.hasNext())
{
- String seqHash = seqHashIter.next();
- Sequence sequence = seqMap.get(seqHash);
+ Sequence sequence = seqMap.get(seqHashIter.next());
if (sequence != null)
{
grpSeqs.add(sequence);
}
- for (Iterator<JSONObject> alAnnotIter = alAnnotJsonArray
- .iterator(); alAnnotIter.hasNext();)
+ for (Iterator<Object> alAnnotIter = alAnnotJsonArray.iterator(); alAnnotIter.hasNext();)
{
- JSONObject alAnnot = alAnnotIter.next();
- JSONArray annotJsonArray = (JSONArray) alAnnot.get("annotations");
+ Map<String, Object> alAnnot = (Map<String, Object>) alAnnotIter.next();
+ List<Object> annotJsonArray = (List<Object>) alAnnot.get("annotations");
Annotation[] annotations = new Annotation[annotJsonArray.size()];
int count = 0;
- for (Iterator<JSONObject> annotIter = annotJsonArray
- .iterator(); annotIter.hasNext();)
+ for (Iterator<Object> annotIter = annotJsonArray.iterator(); annotIter.hasNext();)
{
- JSONObject annot = annotIter.next();
+ Map<String, Object> annot = (Map<String, Object>) annotIter.next();
if (annot == null)
{
annotations[count] = null;
alignAnnot.graph = (alAnnot.get("graphType") == null) ? 0
: Integer.valueOf(alAnnot.get("graphType").toString());
- JSONObject diplaySettings = (JSONObject) alAnnot
+ Map<String, Object> diplaySettings = (Map<String, Object>) alAnnot
.get("annotationSettings");
if (diplaySettings != null)
{
return this;
}
- public void parseHiddenSeqRefsAsList(JSONObject jvSettingsJson)
+ public void parseHiddenSeqRefsAsList(Map<String, Object> jvSettingsJson)
{
hiddenSeqRefs = new ArrayList<>();
String hiddenSeqs = (String) jvSettingsJson.get("hiddenSeqs");
}
}
- public void parseHiddenCols(JSONObject jvSettingsJson)
+ public void parseHiddenCols(Map<String, Object> jvSettingsJson)
{
String hiddenCols = (String) jvSettingsJson.get("hiddenCols");
if (hiddenCols != null && !hiddenCols.isEmpty())
}
@SuppressWarnings("unchecked")
- private void parseFeatures(JSONArray jsonSeqFeatures)
+ private void parseFeatures(List<Object> jsonSeqFeatures)
{
if (jsonSeqFeatures != null)
{
displayedFeatures = new FeaturesDisplayed();
- for (Iterator<JSONObject> seqFeatureItr = jsonSeqFeatures
+ for (Iterator<Object> seqFeatureItr = jsonSeqFeatures
.iterator(); seqFeatureItr.hasNext();)
{
- JSONObject jsonFeature = seqFeatureItr.next();
+ Map<String, Object> jsonFeature = (Map<String, Object>) seqFeatureItr.next();
Long begin = (Long) jsonFeature.get("xStart");
Long end = (Long) jsonFeature.get("xEnd");
String type = (String) jsonFeature.get("type");
SequenceFeature sequenceFeature = new SequenceFeature(type,
description, featureBegin, featureEnd, score, featureGrp);
- JSONArray linksJsonArray = (JSONArray) jsonFeature.get("links");
+ List<Object> linksJsonArray = (List<Object>) jsonFeature.get("links");
if (linksJsonArray != null && linksJsonArray.size() > 0)
{
- Iterator<String> linkList = linksJsonArray.iterator();
+ Iterator<Object> linkList = linksJsonArray.iterator();
while (linkList.hasNext())
{
- String link = linkList.next();
- sequenceFeature.addLink(link);
+ sequenceFeature.addLink((String) linkList.next());
}
}
*/
package jalview.json.binding.biojs;
+import jalview.util.JSONUtils;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
import java.util.Objects;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class BioJSRepositoryPojo
{
Objects.requireNonNull(jsonString,
"Supplied jsonString must not be null");
- JSONParser jsonParser = new JSONParser();
- JSONObject JsonObj = (JSONObject) jsonParser.parse(jsonString);
+ Map<String, Object> JsonObj = (Map<String, Object>) JSONUtils.parse(jsonString);
this.description = (String) JsonObj.get("description");
this.latestReleaseVersion = (String) JsonObj
.get("latestReleaseVersion");
- JSONArray repositoriesJsonArray = (JSONArray) JsonObj.get("releases");
- for (Iterator<JSONObject> repoIter = repositoriesJsonArray
+ List<Object> repositoriesJsonArray = (List<Object>) JsonObj.get("releases");
+ for (Iterator<Object> repoIter = repositoriesJsonArray
.iterator(); repoIter.hasNext();)
{
- JSONObject repoObj = repoIter.next();
+ Map<String, Object> repoObj = (Map<String, Object>) repoIter.next();
BioJSReleasePojo repo = new BioJSReleasePojo();
repo.setType((String) repoObj.get("type"));
repo.setUrl((String) repoObj.get("url"));
import static jalview.util.UrlConstants.DELIM;
import static jalview.util.UrlConstants.SEP;
+import jalview.util.JSONUtils;
import jalview.util.UrlLink;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.StringTokenizer;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* name of identifiers.org download file
* @return hashmap of identifiers.org data, keyed by MIRIAM id
*/
- private HashMap<String, UrlLink> readIdentifiers(String idFileName)
+ @SuppressWarnings("unchecked")
+private HashMap<String, UrlLink> readIdentifiers(String idFileName)
{
- JSONParser parser = new JSONParser();
-
// identifiers.org data
HashMap<String, UrlLink> idData = new HashMap<String, UrlLink>();
String errorMessage = null;
try
{
+ // NOTE: THIS WILL FAIL IN SWINGJS BECAUSE IT INVOLVES A FILE READER
+
FileReader reader = new FileReader(idFileName);
String key = "";
- JSONObject obj = (JSONObject) parser.parse(reader);
+ Map<String, Object> obj = (Map<String, Object>) JSONUtils.parse(reader);
if (obj.containsKey(ID_ORG_KEY))
{
key = ID_ORG_KEY;
return idData;
}
- JSONArray jsonarray = (JSONArray) obj.get(key);
+ List<Object> jsonarray = (List<Object>) obj.get(key);
// loop over each entry in JSON array and build HashMap entry
for (int i = 0; i < jsonarray.size(); i++)
{
- JSONObject item = (JSONObject) jsonarray.get(i);
+ Map<String, Object> item = (Map<String, Object>) jsonarray.get(i);
String url = (String) item.get("url") + "/" + DELIM + DB_ACCESSION
+ DELIM;
package jalview.util;
-import org.json.simple.JSONArray;
+import jalview.javascript.json.JSON;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.List;
+
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
public class JSONUtils
{
* @param jsonArray
* @return
*/
- public static String arrayToList(JSONArray jsonArray)
+ public static String arrayToStringList(List<Object> jsonArray)
{
- if (jsonArray == null)
+ int n;
+
+ if (jsonArray == null || (n = jsonArray.size()) == 0)
{
return null;
}
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < jsonArray.size(); i++)
+ /**
+ * @j2sNative
+ *
+ * return jsonArray.elementData.slice(0, n).join(",");
+ */
{
- if (i > 0)
- {
- sb.append(",");
- }
- sb.append(jsonArray.get(i).toString());
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < n; i++)
+ {
+ if (i > 0)
+ {
+ sb.append(",");
+ }
+ sb.append(jsonArray.get(i).toString());
+ }
+ return sb.toString();
}
- return sb.length() == 0 ? null : sb.toString();
+ }
+
+ /**
+ * The method all JSON parsing must go through for JavaScript.
+ * @param r a BufferedReader or a javascript.json.JSON.JSONReader
+ * @return
+ * @throws IOException
+ * @throws ParseException
+ */
+ public static Object parse(Reader r) throws IOException, ParseException
+ {
+ // Using a file reader is not currently supported in SwingJS JavaScript
+
+ if (r == null)
+ return null;
+//
+// Platform.timeCheck("JSONUtils.parse0 ", Platform.TIME_MARK);
+
+ Object ret;
+ if (Platform.isJS())
+ {
+ if (r instanceof FileReader)
+ {
+ throw new IOException("StringJS does not support FileReader parsing for JSON -- but it could...");
+ }
+ return JSON.parse(r);
+ } else {
+ ret = new JSONParser().parse(r);
+ }
+// Platform.timeCheck("JSONUtils.parse1 ", Platform.TIME_MARK);
+ return ret;
+ }
+
+ public static Object parse(String json) throws ParseException
+ {
+ return (Platform.isJS() ? JSON.parse(json) : new JSONParser().parse(json));
}
}