Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.factual.driver;
  
  import java.util.List;
 import java.util.Map;
 
Represents the public Factual API. Supports running queries against Factual and inspecting the response. Supports the same levels of authentication supported by Factual's API.

Author(s):
aaron
 
 public class Factual {
   private static final String DRIVER_HEADER_TAG = "factual-java-driver-v1.4.0";
   private static final String DEFAULT_HOST_HEADER = "api.v3.factual.com";
   private String factHome = "http://api.v3.factual.com/";
   private String host = ;
   private final String key;
   private final OAuthHmacSigner signer;
   private boolean debug = false;
   private StreamHandler debugHandler = null;
 
   private Queue<FullQueryfetchQueue = Lists.newLinkedList();

  
Constructor. Represents your authenticated access to Factual.

Parameters:
key your oauth key.
secret your oauth secret.
 
   public Factual(String keyString secret) {
 	this(keysecretfalse);
   }

  
Constructor. Represents your authenticated access to Factual.

Parameters:
key your oauth key.
secret your oauth secret.
debug whether or not this is in debug mode
 
   public Factual(String keyString secretboolean debug) {
 	this. = key;
 	this. = new OAuthHmacSigner();
 	this.. = secret;
 	debug(debug);
   }


  
Change the base URL at which to contact Factual's API. This may be useful if you want to talk to a test or staging server.

Example value: http://staging.api.v3.factual.com/t/

Parameters:
urlBase the base URL at which to contact Factual's API.
 
   public void setFactHome(String urlBase) {
     this. = urlBase;
   }

  
Change the host header value for a request to Factual's API.

Parameters:
host the host header value for a request to Factual's API.
 
   public void setRequestHost(String host) {
     this. = host;
   }

  
Runs a read query against the specified Factual table.

Parameters:
tableName the name of the table you wish to query (e.g., "places")
query the read query to run against table.
Returns:
the response of running query against Factual.
  public ReadResponse fetch(String tableNameQuery query) {
    return fetchCustom(urlForFetch(tableName), query);
  }

  
Runs a geopulse query against Factual.

Parameters:
geopulse the geopulse query to run.
Returns:
the response of running geopulse against Factual.
  public ReadResponse geopulse(Geopulse geopulse) {
	return new ReadResponse(request(toUrl( + "places/geopulse"geopulse.toUrlQuery())));
  }

  
Reverse geocodes by returning a response containing the address nearest to the given point.

Parameters:
point the point for which the nearest address is returned
Returns:
the response of running a reverse geocode query for point against Factual.
  public ReadResponse reverseGeocode(Point point) {
	return new ReadResponse(request(toUrl( + "places/geocode"new Geocode(point).toUrlQuery())));
  }
  
  
Runs a facet read against the specified Factual table.

Parameters:
tableName the name of the table you wish to query for facets (e.g., "places")
facet the facet query to run against table
Returns:
the response of running facet against Factual.
  public FacetResponse fetch(String tableNameFacetQuery facet) {
	return fetchCustom(urlForFacets(tableName), facet);
  }

  
Runs a submit input against the specified Factual table.

Parameters:
tableName the name of the table you wish to submit updates for (e.g., "places")
factualId the factual id on which the submit is run
submit the submit parameters to run against table
metadata the metadata to send with information on this request
Returns:
the response of running submit against Factual.
  public SubmitResponse submit(String tableNameString factualIdSubmit submitMetadata metadata) {
	return submitCustom("t/"+tableName+"/"+factualId+"/submit"submitmetadata);
  }

  
Runs a submit to add a row against the specified Factual table.

Parameters:
tableName the name of the table you wish to submit the add for (e.g., "places")
submit the submit parameters to run against table
metadata the metadata to send with information on this request
Returns:
the response of running submit against Factual.
  public SubmitResponse submit(String tableNameSubmit submitMetadata metadata) {
	return submitCustom("t/"+tableName+"/submit"submitmetadata);
  }

  
Flags a row as a duplicate in the specified Factual table.

Parameters:
tableName the name of the table you wish to flag a duplicate for (e.g., "places")
factualId the factual id that is the duplicate
metadata the metadata to send with information on this request
Returns:
the response from flagging a duplicate row.
  public FlagResponse flagDuplicate(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "duplicate"metadata);
  }

  
Flags a row as inaccurate in the specified Factual table.

Parameters:
tableName the name of the table you wish to flag an inaccurate row for (e.g., "places")
factualId the factual id that is inaccurate
metadata the metadata to send with information on this request
Returns:
the response from flagging an inaccurate row.
  public FlagResponse flagInaccurate(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "inaccurate"metadata);
  }

  
Flags a row as inappropriate in the specified Factual table.

Parameters:
tableName the name of the table you wish to flag an inappropriate row for (e.g., "places")
factualId the factual id that is inappropriate
metadata the metadata to send with information on this request
Returns:
the response from flagging an inappropriate row.
  public FlagResponse flagInappropriate(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "inappropriate"metadata);
  }

  
Flags a row as non-existent in the specified Factual table.

Parameters:
tableName the name of the table you wish to flag a non-existent row for (e.g., "places")
factualId the factual id that is non-existent
metadata the metadata to send with information on this request
Returns:
the response from flagging a non-existent row.
  public FlagResponse flagNonExistent(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "nonexistent"metadata);
  }

  
Flags a row as spam in the specified Factual table.

Parameters:
tableName the name of the table you wish to flag a row as spam (e.g., "places")
factualId the factual id that is spam
metadata the metadata to send with information on this request
Returns:
the response from flagging a row as spam.
  public FlagResponse flagSpam(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "spam"metadata);
  }

  
Flags a row as problematic in the specified Factual table.

Parameters:
tableName the name of the table for which you wish to flag as problematic (e.g., "places")
factualId the factual id that has a problem other than duplicate, inaccurate, inappropriate, non-existent, or spam.
metadata the metadata to send with information on this request
Returns:
the response from flagging a row as problematic.
  public FlagResponse flagOther(String tableNameString factualIdMetadata metadata) {
	return flagCustom(urlForFlag(tableNamefactualId), "other"metadata);
  }

  
Runs a "GET" request against the path specified using the parameters specified and your Oauth token.

Parameters:
path the path to run the request against
params the parameters to send with the request
Returns:
the response of running query against Factual.
  public String get(String pathMap<StringObjectparams) {
	return request(constructRawReadUrl(pathparams));
  }
  
  private String constructRawReadUrl(String pathMap<StringObjectparams) {
	List<ObjectparamList = Lists.newArrayList();
	for (Entry<StringObjectentry : params.entrySet()) {
		paramList.add(Parameters.urlPair(entry.getKey(), String.valueOf(entry.getValue()), true));
	}
	String paramString = Joiner.on("&").skipNulls().join(paramList);
	return toUrl( + pathparamString);
  }
  private ReadResponse fetchCustom(String rootQuery query) {
	return new ReadResponse(request(toUrl( + rootquery.toUrlQuery())));
  }
  private FacetResponse fetchCustom(String rootFacetQuery facet) {
	return new FacetResponse(request(toUrl( + rootfacet.toUrlQuery())));
  }
  private CrosswalkResponse fetchCustom(String rootCrosswalkQuery query) {
	return new CrosswalkResponse(request(toUrl( + rootquery.toUrlQuery())));
  }
  private ReadResponse fetchCustom(String rootResolveQuery query) {
	return new ReadResponse(request(toUrl( + rootquery.toUrlQuery())));
  }
  private SubmitResponse submitCustom(String rootSubmit submitMetadata metadata) {
	Map<StringStringparams = Maps.newHashMap();
	// TODO: Switch parameters to POST content when supported.
	//params.putAll(metadata.toParamMap());
	//params.putAll(submit.toParamMap());
	return new SubmitResponse(requestPost( + root+"?"+submit.toUrlQuery()+"&"+metadata.toUrlQuery(), params));
  }
  private FlagResponse flagCustom(String rootString flagTypeMetadata metadata) {
	Map<StringStringparams = Maps.newHashMap();
	// TODO: Switch parameters to POST content when supported.
	//params.putAll(metadata.toParamMap());
	//params.put("problem", flagType);
	return new FlagResponse(requestPost( + root+"?problem="+flagType+"&"+metadata.toUrlQuery(), params));
  }
  private String toUrl(String rootString parameters) {
	return root + "?" + parameters;
  }
  private class FullQuery {
	  protected Object query;
	  protected String table;
	  public FullQuery(String tableObject query) {
		  this. = table;
		  this. = query;
	  }
  }

  
Queue a raw read request for inclusion in the next multi request.

Parameters:
path the path to run the request against
params the parameters to send with the request
  public void queueFetch(String pathMap<StringObjectparams) {
	.add(new FullQuery(pathparams));
  }

  
Queue a read request for inclusion in the next multi request.

Parameters:
table the name of the table you wish to query (e.g., "places")
query the read query to run against table.
  public void queueFetch(String tableQuery query) {
	.add(new FullQuery(tablequery));
  }

  
Queue a crosswalk request for inclusion in the next multi request.

Parameters:
table the name of the table you wish to use crosswalk against (e.g., "places")
query the crosswalk query to run against table.
  public void queueFetch(String tableCrosswalkQuery query) {
	.add(new FullQuery(tablequery));
  }

  
Queue a resolve request for inclusion in the next multi request.

Parameters:
table the name of the table you wish to use resolve against (e.g., "places")
query the resolve query to run against table.
  public void queueFetch(String tableResolveQuery query) {
	.add(new FullQuery(tablequery));
  }

  
Queue a facet request for inclusion in the next multi request.

Parameters:
table the name of the table you wish to use a facet request against (e.g., "places")
query the facet query to run against table.
  public void queueFetch(String tableFacetQuery query) {
	.add(new FullQuery(tablequery));
  }
  public void queueFetch(Geocode query) {
	.add(new FullQuery(nullquery));
  }
  public void queueFetch(Geopulse query) {
	.add(new FullQuery(nullquery));
  }
  
  
Use this to send all queued reads as a multi request

Returns:
response for a multi request
  public MultiResponse sendRequests() {
	Map<StringStringmulti = Maps.newHashMap();
	int i = 0;
	Map<StringObjectrequestMapping = Maps.newLinkedHashMap();
	while (!.isEmpty()) {
		FullQuery fullQuery = .poll();
		String url = null;
		Object query = fullQuery.query;
		String table = fullQuery.table;
	    if (query instanceof Query) {
			url = toUrl("/"+urlForFetch(table), ((Query)query).toUrlQuery());
	    } else if (query instanceof CrosswalkQuery) {
			url = toUrl("/"+urlForCrosswalk(table), ((CrosswalkQuery)query).toUrlQuery());
	    } else if (query instanceof ResolveQuery) {
			url = toUrl("/"+urlForResolve(table), ((ResolveQuery)query).toUrlQuery());
	    } else if (query instanceof FacetQuery) {
			url = toUrl("/"+urlForFacets(table), ((FacetQuery)query).toUrlQuery());
	    } else if (query instanceof Map) {
	    	url = constructRawReadUrl(table, (Mapquery);
	    } else if (query instanceof Geocode) {
	    	url = toUrl( + "places/geocode", ((Geocodequery).toUrlQuery());
	    } else if (query instanceof Geopulse) {
	    	url = toUrl( + "places/geopulse", ((Geopulsequery).toUrlQuery());
	    }
		if (url != null) {
			String multiKey = "q"+Integer.toString(i);
			multi.put(multiKeyurl);
			requestMapping.put(multiKeyquery);
			i++;
		}
	}
	String json = JsonUtil.toJsonStr(multi);
	String url = "";
	try {
		String encoded = URLEncoder.encode(json"UTF-8");
		url = toUrl( + "multi""queries=" + encoded);
	}
	String jsonResponse = request(url);
	MultiResponse resp = new MultiResponse(requestMapping);
	resp.setJson(jsonResponse);
	return resp;
  }

  
Convenience method to return Crosswalks for the specific query.
  public List<Crosswalkcrosswalks(String tableCrosswalkQuery query) {
    return fetch(tablequery).getCrosswalks();
  }

  
Query's Factual for the Crosswalk data matching the specified query.

Parameters:
tableName the name of the table to crosswalk.
query the Crosswalk query.
Returns:
Factual's response to the Crosswalk query.
  public CrosswalkResponse fetch(String tableNameCrosswalkQuery query) {
    return fetchCustom(urlForCrosswalk(tableName), query);
  }

  
Asks Factual to resolve the Places entity for the attributes specified by query.

Returns the read response from a Factual Resolve request, which includes all records that are potential matches.

Parameters:
query the Resolve query to run against Factual's Places table.
Returns:
the response from Factual for the Resolve request.
  public ReadResponse resolves(ResolveQuery query) {
    return fetch("places"query);
  }

  
Asks Factual to resolve the Places entity for the attributes specified by query. Returns a record representing the resolved entity if Factual successfully identified the entity with full confidence, or null if the entity was not resolved.

Parameters:
query a Resolve query with partial attributes for an entity.
Returns:
a record representing the resolved entity if Factual successfully identified the entity with full confidence, or null if the entity was not resolved.
  public Map<StringObjectresolve(ResolveQuery query) {
    return resolves(query).first();
  }

  
Asks Factual to resolve the entity for the attributes specified by query, within the table called tableName.

Returns the read response from a Factual Resolve request, which includes all records that are potential matches.

Each result record will include a confidence score ("similarity"), and a flag indicating whether Factual decided the entity is the correct resolved match with a high degree of accuracy ("resolved").

There will be 0 or 1 entities returned with "resolved"=true. If there was a full match, it is guaranteed to be the first record in the response.

Parameters:
tableName the name of the table to resolve within.
query a Resolve query with partial attributes for an entity.
Returns:
the response from Factual for the Resolve request.
  public ReadResponse fetch(String tableNameResolveQuery query) {
    return fetchCustom(urlForResolve(tableName), query);
  }
  public SchemaResponse schema(String tableName) {
    return new SchemaResponse(request(+urlForSchema(tableName)));
  }
  private String urlForSchema(String tableName) {
    return "t/" + tableName + "/schema";
  }
  private String urlForCrosswalk(String tableName) {
    return tableName + "/crosswalk";
  }
  private String urlForResolve(String tableName) {
    return tableName + "/resolve";
  }
  private String urlForFetch(String tableName) {
    return "t/" + tableName;
  }
  private String urlForFlag(String tableNameString factualId) {
	return "t/"+tableName+"/"+factualId+"/flag";
  }
  private String urlForFacets(String tableName) {
	return "t/" + tableName+"/facets";
  }
  private String request(String urlStr) {
	  return request(urlStrtrue);
  }
  private String request(String urlStrboolean useOAuth) {
	  return request(urlStr"GET"nulluseOAuth);
  }
  private String requestPost(String urlStrMap<StringStringpostData) {
	  return requestPost(urlStrpostDatatrue);
  }
  private String requestPost(String urlStrMap<StringStringpostDataboolean useOAuth) {
	  return request(urlStr"POST"postDatauseOAuth);
  }
  private String request(String urlStrString requestMethodMap<StringStringpostDataboolean useOAuth) {
    GenericUrl url = new GenericUrl(urlStr);
    // Configure OAuth request params
    OAuthParameters params = new OAuthParameters();
    params.consumerKey = ;
    params.computeNonce();
    params.computeTimestamp();
    params.signer = ;
    BufferedReader br = null;
    try {
      // generate the signature
      params.computeSignature(requestMethodurl);
      // make the request
      HttpTransport transport = new NetHttpTransport();
      HttpRequestFactory f = null;
      if (useOAuth) {
    	  f = transport.createRequestFactory(params);
      } else {
    	  f = transport.createRequestFactory();
      }
      HttpRequest request = null;
      if ("POST".equals(requestMethod))
    	  if (postData == null)
        	  request = f.buildPostRequest(urlnull);
    	  else
    		  request = f.buildPostRequest(urlnew UrlEncodedContent(postData));
      else
    	  request = f.buildGetRequest(url);
      HttpHeaders headers = new HttpHeaders();
      headers.set("X-Factual-Lib");
      headers.set("Host");
      request.setHeaders(headers);
      if () {
          Logger logger = Logger.getLogger(HttpTransport.class.getName());
          logger.removeHandler();
          logger.setLevel(.);
          logger.addHandler();
	  }
      // get the response
      br = new BufferedReader(new InputStreamReader(request.execute().getContent()));
      String line = null;
      StringBuffer sb = new StringBuffer();
      while ((line = br.readLine())!= null) {
    	  sb.append(line);
      }
      return sb.toString();
    } catch (HttpResponseException e) {
      throw new FactualApiException(e).requestUrl(urlStr).requestMethod(requestMethod).response(e.getResponse());
    } catch (IOException e) {
      throw new FactualApiException(e).requestUrl(urlStr).requestMethod(requestMethod);
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    } finally {
      Closeables.closeQuietly(br);
    }
  }

  
Set the driver in or out of debug mode.

Parameters:
debug whether or not this is in debug mode
  public void debug(boolean debug) {
	  this. = debug;
	  if (debug &&  == null) {
           = new StreamHandler(.new SimpleFormatter());
          .setLevel(.);
	  }
  }
New to GrepCode? Check out our FAQ X