Link to home
Create AccountLog in
Avatar of James Hancock
James HancockFlag for United States of America

asked on

What would Java List Object hardcoded instantiation look like?

Hi
I'm doing a project where a paid service returns me a List Object of Strings for a certain query.
I hate getting the service to charge me for every x compiles.
It fills the list like this . .

(Assume appropriate setup, etc ) searchTerm is a String


 Customsearch customsearch = builder.build();
        Search searchResult = customsearch.cse().list(searchTerm).execute();
        System.out.println("About " + searchResult.getSearchInformation().getTotalResults() + " results available");
        List<Result> items = searchResult.getItems();
        return items;


It correctly returns 10 Strings of the search I desire. But I always top the limit of 100 daily searches from multiple compiles.
How can I replace this section entirely with a simple hardcoding of the Strings List Object?
Thanks
Avatar of mccarl
mccarl
Flag of Australia image

No, the code returns you a list of "Result" type objects not "String" objects.

But if you can stub out a List of Strings instead, this is how you can hardcode it...
List<String> strings = Arrays.asList("Test", "Test2", "Test3");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of James Hancock

ASKER

CEHJ, I really like that class. Thanks

So, in this area of my code, at the end, how do I correctly create a StringList that equals the contents of the items List, so I can create a StringList Object to save ? for loop?


List<Result> items = new ArrayList<Result>();
       
        for (long i = 1; i <= 10; i += 10) { //change first 10 to 100 to get more results
            items.addAll(executeSearch("search terms", i));
        }
       
        // do correct StringList stringList =items;

Thanks
Can you post your Result class?
Sorry, I didn't realize it wasn't all standard stuff.
It's in a jar file. How do I find out which jar file? Custom search Google API has a river of jars
Would you like the jar file? Can I post jar files here? It might even need them all from the API page.

Thanks
Oh if it's part of the Google api - don't worry. I'll take a look at the javadoc

Update: can't find the Result class in the javadoc. Can you post a link?
Hi,
I'm not sure what that means? I only have the jar files and Google.

Thanks
A link to the javadoc (api docs) for the Result class. Do you have one?
Unfortunately not. Sorry. I cant find it.
Where might I find them?
The only files in the development libraries are JAR files, no documentation
Other ideas?

Thanks
I'm surprised you're able to use the Result class then ;) The point is, what is going to be the point of correspondence between Result and a String in a List? Presumably result.url? (i'm guessing). That needs to be established. Then, do you need to be able to take a String and (re)create a Result instance?
Good, Thanks

I decided to put in a very hot topic right now, "muslim brotherhood" and Google in Safari found  "About 199000000 results available" - 200 million

and it went on to list 100 links to sites, as my code instructs, like

99:    Cairo protesters to Obama: Stop supporting the Muslim ... - Twitchy (http://twitchy.com/2013/06/27/cairo-protesters-to-obama-stop-supporting-the-muslim-brotherhoods-fascist-regime-photos/)
100:    BBC News - Profile: Egypt's Muslim Brotherhood (http://www.bbc.co.uk/news/world-middle-east-12313405)

How will we get 1000's more?, not just 100
. . my . . Code Below, I took out duplication of String[] as you suggested
What else would you suggest to collect many URL's?
If I ask it for 1000 items, search results, it crashes.    * * example output at the end of the code *

Thanks

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.Customsearch.Builder;
import com.google.api.services.customsearch.CustomsearchRequest;
import com.google.api.services.customsearch.CustomsearchRequestInitializer;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;

public class TestCustomSearchAPI {
    
    public static void main(String[] args) throws GeneralSecurityException, IOException {
        List<Result> items = new ArrayList<Result>();
        
        for (long i = 1; i <= 100; i += 10) { //change first 10 to 100 to get more results
            items.addAll(executeSearch("muslim brotherhood", i));
        }
        

        
        //new controlFrame();
        int i = 1;
        //StringList stringList =items;
        for (Result item : items) {
            System.out.println(i++ + ":    " + item.getTitle() + " (" + item.getLink() + ")");
            
            
        }
    }

    private static List<Result> executeSearch(String searchTerm, final Long start) throws GeneralSecurityException, IOException {
        Builder builder = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), null);
        //builder.setApplicationName("Google bot");
        builder.setCustomsearchRequestInitializer(new CustomsearchRequestInitializer() {
            @Override
            protected void initializeCustomsearchRequest(CustomsearchRequest<?> request) throws IOException {
                request.setKey("AIzaSy- my own key - vLUs");
                request.set("cx", "009- my own- code - sya4");
                request.set("start", start);
            }
        });
        Customsearch customsearch = builder.build();
        Search searchResult = customsearch.cse().list(searchTerm).execute();
        System.out.println("About " + searchResult.getSearchInformation().getTotalResults() + " results available");
        List<Result> items = searchResult.getItems();
        
        return items;
    }  // executeSearch()
}




/*
Example output

About 399000000 results available
1:    Barack Obama - Wikipedia, the free encyclopedia (http://en.wikipedia.org/wiki/Barack_Obama)
2:    Barack Obama (http://www.barackobama.com/)
3:    President Barack Obama | The White House (http://www.whitehouse.gov/administration/president-obama)
4:    Barack Obama (BarackObama) on Twitter (https://twitter.com/BarackObama)
5:    Barack Obama - The Biography Channel (http://www.biography.com/people/barack-obama-12782369)
6:    Barack Obama News - Bloomberg (http://topics.bloomberg.com/barack-obama/)
7:    Barack Obama news, photos and video - chicagotribune.com (http://www.chicagotribune.com/topic/politics/government/barack-obama-PEPLT007408.topic)
8:    Barack Obama - New York Daily News (http://www.nydailynews.com/topics/Barack%20Obama)
*/

Open in new window




Thanks,
It gives 100 URL returns, not just 8, right now. How can we increase that?
We need to focus on one question at a time - the number of search results is quite a different issue and should be the subject of a different question.

Anyway, if you want to create a StringList to hold the List<Result> found, the point of correspondence being probably the link the Result holds, you need to do something like:

List<Result> results = TestCustomSearchAPI.executeSearch(foo, bar);
StringList latestResultsLinks = new StringList(results.size());
for(Result r : results) {
   latestResultsLinks.add(r.getLink());
}

Open in new window

Add this ctor to StringList:
   public StringList(int numElements) {
	super(numElements);
    }

Open in new window

Okay, this output looks good. . . below

I just need to find out how to get more at a time? in another question? Returns Title and URL

output . . . for Mickey Mouse

About 199000000 results available

About 25000000 results available
0:    Mickey Mouse - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Mickey_Mouse
1:    Mickey Mouse Barack Obama Shirt - Those Shirts http://www.thoseshirts.com/mic.html
2:    Rand Paul hits Obama for playing 'Mickey Mouse games' – CNN ... http://politicalticker.blogs.cnn.com/2013/03/11/rand-paul-hits-obama-for-playing-mickey-mouse-games/
3:    Mickey Mouse Clubhouse - Mickey's Fishy Story - YouTube http://www.youtube.com/watch?v=PC2jgDyJqBo
4:    Obama attorney: 'Mickey Mouse' could be on ballot - WND http://www.wnd.com/2012/04/obama-attorney-mickey-mouse-could-be-on-ballot/
5:    Mickey Mouse Clubhouse - Online Activites and Fun | Disney Junior http://disney.go.com/disneyjunior/mickey-mouse-clubhouse
6:    ACORN: Mickey Mouse for Obama? | The Economist http://www.economist.com/node/12432392
7:    Mickey Mouse follows Obama in backing gay marriage - The Guardian http://www.guardian.co.uk/world/2012/may/17/mickey-mouse-gay-marriage
8:    Mickey Mouse makes an appearance - The Washington Post http://www.washingtonpost.com/business/mickey-mouse-makes-an-appearance/2013/07/06/d9561d8e-df60-11e2-b2d4-ea6d8f477a01_story.html
9:    Chris Matthews: Obama “Big Bird” Ad is “Mickey Mouse” http://www.aim.org/don-irvine-blog/chris-matthews-obama-big-bird-ad-is-mickey-mouse/
:)