I getting confused with how to get duration, time and distance traveled using google distancematrix.api I can't understand whats not working with my code, all that I'm getting are null values. why ?? Below is my javacode
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(context,
new String[] {"rose hill"}, new String[] {"port louis"}).units(Unit.METRIC).await();
System.out.println(results1.rows[0].elements[0].duration);
System.out.println(results1.rows[0].elements[0].distance);
System.out.println(results1.rows[0].elements[0].distance);
context as requested
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("AIzaSyC..")
.build();
It worked for me just by creating (and enabling) an API key on the google maps
Here is my code
public class GoogleDistance {
public static void main(String[] args) throws InterruptedException, ApiException, IOException {
new GoogleDistance().go();
}
void go() throws InterruptedException, ApiException, IOException {
String API_KEY = "AIzy....";
GeoApiContext.Builder builder = new GeoApiContext.Builder();
builder.apiKey(API_KEY);
GeoApiContext geoApiContext = builder.build();
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
new String[]{"rose hill"}, new String[]{"port louis"}).units(Unit.METRIC).await();
System.out.println(Arrays.toString(results1.destinationAddresses));
}
}
I believe the issue may be with your prints: I don't think you should be doing rows[0].elements[0] just use Arrays.toString().
When I run my code it outputs [Port Louis, Mauritius]
EDIT
I think I now see what you were trying to do. Please take a look at the following
public class GoogleDistance {
public static void main(String[] args) throws InterruptedException, ApiException, IOException {
new GoogleDistance().go();
}
void go() throws InterruptedException, ApiException, IOException {
String API_KEY = "AIzy...";
GeoApiContext.Builder builder = new GeoApiContext.Builder();
builder.apiKey(API_KEY);
GeoApiContext geoApiContext = builder.build();
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
new String[]{"los angeles"}, new String[]{"san francisco"}).units(Unit.METRIC).await();
DistanceMatrixRow[] rows = results1.rows;
for (DistanceMatrixRow row : rows) {
DistanceMatrixElement[] elements = row.elements;
for (DistanceMatrixElement element : elements) {
Distance distance = element.distance;
if(distance == null){
System.out.println("distance is null");
continue;
}
String dist = distance.humanReadable;
String dur = element.duration.humanReadable;
System.out.println(dist);
System.out.println(dur);
}
}
}
}
I believe you're getting null because google cant map between the locations you're providing.
Related
I have a program that creates a webgraph from text files. Every Time I run it I get the same message that says "Scanner Closed."
//constant final variables
public static final String PAGES_FILE = "pages.txt";
public static final String LINKS_FILE = "links.txt";
// webgraph object var
private WebGraph web;
// searchEngine constructor.
public SearchEngine() throws FileNotFoundException {
web = WebGraph.buildFromFiles(PAGES_FILE, LINKS_FILE);
}
Scanner Portion
try {
System.out.println("Loading WebGraph data...");
SearchEngine engine = new SearchEngine();
System.out.println("Success!");
Scanner scanner = new Scanner(System.in);
I have the scanner.close() right after the try block which contains all the possible user inputs. I have also attached an image of what should be happening once I run the program. Any ideas what could be going wrong? If any other code is needed I can provide that.Sample Program
Here is the image of what I am getting My Run
This is the code for the "buildFromFiles"
public static WebGraph buildFromFiles(String pagesFile, String linksFile)
throws IllegalArgumentException, FileNotFoundException {
WebGraph webGraph = new WebGraph();
File filePages = new File(pagesFile);
File fileLinks = new File(linksFile);
if (filePages.exists() && fileLinks.exists() && filePages.isFile() && fileLinks.isFile()) {
Scanner pageScanner = new Scanner(filePages);
while (pageScanner.hasNextLine()) {
String[] pageData = pageScanner.nextLine().split("\\s+");
String url = pageData[0];
ArrayList<String> keywords = new ArrayList<String>();
for (int i = 1; i < pageData.length; i++) {
keywords.add(pageData[i]);
}
webGraph.addPage(url, keywords);
}
pageScanner.close();
Scanner linkScanner = new Scanner(fileLinks);
while (linkScanner.hasNextLine()) {
String[] linkData = pageScanner.nextLine().split("\\s+");
webGraph.addLink(linkData[0], linkData[1]);
}
linkScanner.close();
} else {
throw new IllegalArgumentException();
}
return webGraph;
}
I am testing some features of the Google Vision API and getting Empty response for images which I have clicked from my camera(5MP camera). However when I download any image from web for Example, an image of a delivery guy (with the plain background such as white) I get a meaningful response with labels. Both the sets of images are present on my local disk. Below is the code which I have written by taking reference from google's documentation,
public class ImageAnalyzer {
final static String APPLICATION_NAME ="My_APP/1.0";
final static String IMAGE_PATH = "E:/Vision/SampleImages/IMAG0013.jpg";
final static int maxResults =3;
private Vision vision;
public ImageAnalyzer(Vision vision){
this.vision=vision;
}
/**
* Connects to the Vision API using Application Default Credentials.
*/
public static Vision getVisionService() throws IOException, GeneralSecurityException {
GoogleCredential credential =
GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public Map<String, List<String>> labelImage(String imagePath){
final Map<String,List<String>> labels = new HashMap<String, List<String>>();
final Path path = Paths.get(imagePath);
try {
final byte[] raw = Files.readAllBytes(path);
/*final AnnotateImageRequest request =new AnnotateImageRequest().setImage(new Image().encodeContent(raw))
.setFeatures(ImmutableList.of(new Feature().setType("LABEL_DETECTION").setMaxResults(3)
, new Feature().setType("LOGO_DETECTION").setMaxResults(3)));*/
AnnotateImageRequest request =
new AnnotateImageRequest()
.setImage(new Image().encodeContent(raw)).setFeatures(ImmutableList.of(
new Feature()
.setType("LABEL_DETECTION")
.setMaxResults(maxResults),
new Feature()
.setType("LOGO_DETECTION")
.setMaxResults(1),
new Feature()
.setType("TEXT_DETECTION")
.setMaxResults(maxResults),
new Feature()
.setType("LANDMARK_DETECTION")
.setMaxResults(1)));
final Vision.Images.Annotate annotate = vision.images().annotate(
new BatchAnnotateImagesRequest().
setRequests(ImmutableList.of(request)));
final BatchAnnotateImagesResponse batchResponse = annotate.execute();
//assert batchResponse.getResponses().size() == 1;
System.out.println("Size of searches"+batchResponse.getResponses().size());
//final AnnotateImageResponse response = batchResponse.getResponses().get(0);
if (batchResponse.getResponses().get(0).getLabelAnnotations() != null) {
final List<String> label = new ArrayList<String>();
for (EntityAnnotation ea: batchResponse.getResponses().get(0).getLabelAnnotations()) {
label.add(ea.getDescription());
}
labels.put("LABEL_ANNOTATION", label);
}
if (batchResponse.getResponses().get(0).getLandmarkAnnotations() != null) {
final List<String> landMark = new ArrayList<String>();
for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLandmarkAnnotations()) {
landMark.add(ea.getDescription());
}
labels.put("LANDMARK_ANNOTATION", landMark);
}
if (batchResponse.getResponses().get(0).getLogoAnnotations() != null) {
final List<String> logo = new ArrayList<String>();
for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLogoAnnotations()) {
logo.add(ea.getDescription());
}
labels.put("LOGO_ANNOTATION", logo);
}
if (batchResponse.getResponses().get(0).getTextAnnotations() != null) {
List<String> text = new ArrayList<String>();
for (EntityAnnotation ea : batchResponse.getResponses().get(0).getTextAnnotations()) {
text.add(ea.getDescription());
}
labels.put("TEXT_ANNOTATION", text);
}
return labels;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void printAnnotations(final List<EntityAnnotation> entityAnnotations) {
if(entityAnnotations!=null && !entityAnnotations.isEmpty()) {
for (final EntityAnnotation entityAnnotation : entityAnnotations) {
final String desc = entityAnnotation.getDescription();
final Float score = entityAnnotation.getScore();
System.out.println(desc+" "+score);
}
}
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO Auto-generated method stub
final ImageAnalyzer analyzer = new ImageAnalyzer(getVisionService());
final Map<String, List<String>> labels = analyzer.labelImage(IMAGE_PATH);
for (Entry<String, List<String>> entry : labels.entrySet()) {
final String key = entry.getKey();
final List<String> value = entry.getValue();
if(value!=null && !value.isEmpty()) {
System.out.println("Printing for key"+key);
for (final String myLebel : value) {
System.out.println(" "+myLebel);
}
}
}
//System.out.println(System.getenv("GOOGLE_APPLICATION_CREDENTIALS"))
}
}
Can anyone help me out?
According to Usage Limits, an image must be < 4MB...
https://cloud.google.com/vision/docs/image-best-practices#usage_limits
(note; this is also asked on the OTN discussion fora - but I'm not too sure there's much activity there)
I've got a test using rdf_semantic_graph_support_for_apache_jena_2.11.1_with_12101_server_patch_build0529 and observe a OOM behavior when running the attached test-class's main() method.
I'm at a loss to see why, though.
In MAT it seems that theres a whole bunch of Oracle instances that hang around, hugging a lot of Strings - but I can verify via SQL*Developer that the connections are successfully closed.
Stripping the test down, I see the apparent leakage happen upon just about any interaction with the ModelOracleSem or GraphOracleSem.
public class OracleSemTxIntegrationWithSpringITCase {
private OracleDataSource oracleDataSource;
private OraclePool oraclePool;
#Before
public void before() throws SQLException {
java.util.Properties prop = new java.util.Properties();
prop.setProperty("MinLimit", "2"); // the cache size is 2 at least
prop.setProperty("MaxLimit", "10");
prop.setProperty("InitialLimit", "2"); // create 2 connections at startup
prop.setProperty("InactivityTimeout", "200"); // seconds
prop.setProperty("AbandonedConnectionTimeout", "100"); // seconds
prop.setProperty("MaxStatementsLimit", "10");
prop.setProperty("PropertyCheckInterval", "60"); // seconds
oracleDataSource = new OracleDataSource();
oracleDataSource.setURL("jdbc:oracle:thin:#**********");
oracleDataSource.setUser("rdfuser");
oracleDataSource.setPassword("****");
oracleDataSource.setConnectionProperties(prop);
oraclePool = new OraclePool(oracleDataSource);
}
#Test
public void testTransactionHandlingViaJdbcTransactions() throws Exception {
final Oracle oracle1 = oraclePool.getOracle();
final Oracle oracle2 = oraclePool.getOracle();
final Oracle oracle3 = oraclePool.getOracle();
final GraphOracleSem graph1 = new GraphOracleSem(oracle1, OracleMetadataDaoITCase.INTEGRATION_TEST_MODEL);
final Model model1 = new ModelOracleSem(graph1);
final GraphOracleSem graph2 = new GraphOracleSem(oracle2, OracleMetadataDaoITCase.INTEGRATION_TEST_MODEL);
final Model model2 = new ModelOracleSem(graph2);
GraphOracleSem graph3 = new GraphOracleSem(oracle3, OracleMetadataDaoITCase.INTEGRATION_TEST_MODEL);
Model model3 = new ModelOracleSem(graph3);
removePersons(model3);
model3.commit();
model3.close();
graph3 = new GraphOracleSem(oracle3, OracleMetadataDaoITCase.INTEGRATION_TEST_MODEL);
model3 = new ModelOracleSem(graph3);
model1.add(model1.createResource("http://www.tv2.no/people/person-1"), DC.description, "A dude");
model2.add(model1.createResource("http://www.tv2.no/people/person-2"), DC.description, "Another dude");
int countPersons = countPersons(model3);
assertEquals(0, countPersons);
model1.commit();
countPersons = countPersons(model3);
assertEquals(1, countPersons);
model2.commit();
countPersons = countPersons(model3);
assertEquals(2, countPersons);
oracle1.commitTransaction();
oracle2.commitTransaction();
oracle3.commitTransaction();
model1.close();
model2.close();
model3.close();
oracle1.dispose();
oracle2.dispose();
oracle3.dispose();
System.err.println("all disposed");
}
public static void main(String ...args) throws Exception {
OracleSemTxIntegrationWithSpringITCase me = new OracleSemTxIntegrationWithSpringITCase();
me.before();
Stopwatch sw = Stopwatch.createStarted();
for(int n = 0; n < 1000; n++) {
me.testTransactionHandlingViaJdbcTransactions();
}
System.err.println("DONE: " + sw.stop());
me.after();
}
#After
public void after() throws SQLException {
oracleDataSource.close();
}
private int countPersons(final Model model) {
return listPersons(model).size();
}
private void removePersons(final Model model) {
final List<Resource> persons = listPersons(model);
persons.stream().forEach(per -> model.removeAll(per, null, null));
}
private List<Resource> listPersons(final Model model) {
final List<Resource> persons = Lists.newArrayList();
ExtendedIterator<Resource> iter = model.listSubjects()
.filterKeep(new Filter<Resource>() {
#Override
public boolean accept(Resource o) {
return o.getURI().startsWith("http://www.tv2.no/people/person-");
}
})
;
iter.forEachRemaining(item -> persons.add(item));
iter.close();
return persons;
}
}
Oracle has provided a fix for this, which I would assume will be publicly available at some time.
I am trying to pass Java class as parameter in function, reason behind it it that I have several pojo classes for different APIs and I am trying to create a single parser utility for all the API URL and pojo class, I have tried with little or no success.
below is the code example -
public class util {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
List<JsonGenMovies> jsongen = null;
String url = "http://www.dishanywhere.com/radish/v20/dol/movies/carousels/featured.json?nkey=0e1345ee597cf280c8a2cde367b6b894";
getMovieParser(jsongen, url);
List<JsonGenShow> jsongenShow = null;
String URL = "http://www.dishanywhere.com/radish/v20/dol/shows/carousels/featured.json";
getShowParser(jsongenShow, URL);
}
public static String[] getMovieParser (List<JsonGenMovies> jsongen, String url ) throws JsonParseException, JsonMappingException, IOException
{
URL jsonUrl = new URL(url);
ObjectMapper objmapper = new ObjectMapper();
jsongen = objmapper.readValue(jsonUrl, new TypeReference<List<JsonGenMovies>>() {});
String[] shows = new String [jsongen.size()];
int i = 0;
for(JsonGenMovies element : jsongen) {
shows[i++]=element.getName();
}
for(int j =0; j<shows.length;j++)
{
System.out.println(shows[j]);
}
return shows;
}
public static String[] getShowParser (List<JsonGen> jsongenShow, String URL ) throws JsonParseException, JsonMappingException, IOException
{
URL jsonUrl = new URL(URL);
ObjectMapper objmapper = new ObjectMapper();
jsongenShow = objmapper.readValue(jsonUrl, new TypeReference<List<JsonGen>>() {});
String[] shows = new String [jsongenShow.size()];
int i = 0;
for(JsonGen element : jsongenShow) {
shows[i++]=element.getName();
}
for(int j =0; j<shows.length;j++)
{
System.out.println(shows[j]);
}
return shows;
}
}
in the line -
jsongen = objmapper.readValue(jsonUrl, new TypeReference<List<JsonGen>>() {});
I still have <List<JsonGen>>a hard coded class name which I am trying to replace with arguments. please if you can help.
Please reply with little explanation, one liner might not be my thing.
Regards
Shek
If i understand correctly you want to have one function instead of two or more.
You can do that with generic type
E.g
public static <T> String[] getParser(List<T> jsongen, String url) throws JsonParseException, JsonMappingException, IOException {
URL jsonUrl = new URL(url);
ObjectMapper objmapper = new ObjectMapper();
jsongen = objmapper.readValue(jsonUrl, new TypeReference<List<T>>() {
});
String[] shows = new String[jsongen.size()];
int i = 0;
for (T element : jsongen) {
shows[i++] = element.getName();
}
for (int j = 0; j < shows.length; j++) {
System.out.println(shows[j]);
}
return shows;
}
If both JsonGenMovies and JsonGen extends/implements an interface or class, E.g JsonGenMovies extends Json then you can do this :
public static <T extends Json> String[] getParser(List<T> jsongen, String url)
T is a generic type, it does not really exist but it will be replaced at runtime by Class used for jsongen arg.
For example in :
List<String> myList;
getParser(myList, "http://blablabla.blalb.com");
All T are replaced by String.
I hope this is what you are looking for.
you can found more explanation about generic type here with better explanation than mine.
EDIT:
If you want to keep your POJO pattern then you can try this (not sure it will works)
public static String[] getParser(List<?> jsongen, String url) throws Exception {
URL jsonUrl = new URL(url);
ObjectMapper objmapper = new ObjectMapper();
jsongen = objmapper.readValue(jsonUrl, new TypeReference<List<?>>() {
});
String[] shows = new String[jsongen.size()];
int i = 0;
for (Object element : jsongen) {
Method method = element.getClass().getMethod("getName");
shows[i++] = (String) method.invoke(element);
}
for (int j = 0; j < shows.length; j++) {
System.out.println(shows[j]);
}
return shows;
}
I have the following reducer Code and i am trying to use PowerMock to test it .
package com.cerner.cdh.examples.reducer;
public class LinkReversalReducer extends TableReducer<Text, Text, ImmutableBytesWritable> {
#Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
StringBuilder inlinks = new StringBuilder();
for (Text value : values) {
inlinks.append(value.toString());
inlinks.append(" ");
}
byte[] docIdBytes = Bytes.toBytes(key.toString());
Put put = new Put(docIdBytes);
put.add(WikiConstants.COLUMN_FAMILY_BYTES, WikiConstants.INLINKS_COLUMN_QUALIFIER_BYTES,
Bytes.toBytes(inlinks.toString().trim()));
context.write(new ImmutableBytesWritable(docIdBytes), put);
}
}
Below is the test i have written for the above:
#Test
public void testLinkReversalReducer() throws IOException, InterruptedException {
Text key = new Text("key");
#SuppressWarnings("rawtypes")
Context context = PowerMockito.mock(Context.class);
Iterable<Text> values = generateText();
StringBuilder inlinks = new StringBuilder();
for (Text value : values) {
inlinks.append(value);
inlinks.append(" ");
}
LinkReversalReducer reducer = new LinkReversalReducer();
byte[] docIdBytes = Bytes.toBytes(key.toString());
byte[] argument1 = WikiConstants.COLUMN_FAMILY_BYTES;
byte[] argument2 = WikiConstants.INLINKS_COLUMN_QUALIFIER_BYTES;
byte[] argument3 = Bytes.toBytes(inlinks.toString().trim());
Put put = new Put(docIdBytes);
put.add(argument1, argument2, argument3);
reducer.reduce(key, values, context);
Mockito.verify(context).write(new ImmutableBytesWritable(docIdBytes), put);
}
private List<Text> generateText() {
Text value = new Text("AB");
List<Text> texts = new ArrayList<Text>();
texts.add(value);
return texts;
}
}
So the thing is that my Mockito.verify(context).write(new ImmutableBytesWritable(docIdBytes), put); seems to get called with the right values in place and also my junit result shows that the Invoked and the Actual give the same response. But the test still seems to fail. Does anyone have a clue ? . Any help would be appreciated :)
The problem here is, that the Put class does not define an equals method. Therefore the verify method thinks that the actual Put passed to context.write inside yourLinkReversalReducer.reduce method is different to the expected Putassembled in your testLinkReversalReducer method.
To work around this problem you could do the following:
Mockito.verify(context).write(Mockito.eq(new ImmutableBytesWritable(docIdBytes)), MockitoHelper.eq(put));
...
class MockitoHelper {
public static Put eq(final Put expectedPut) {
return Mockito.argThat(new CustomTypeSafeMatcher<Put>(expectedPut.toString()) {
#Override
protected boolean matchesSafely(Put actualPut) {
return Bytes.equals(toBytes(expectedPut), toBytes(actualPut));
}
});
}
private static byte[] toBytes(Put put) {
ByteArrayDataOutput out = new ByteArrayDataOutput();
try {
put.write(out);
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}