Ejemplo n.º 1
0
  public static void main(String[] args) {
    PicasaClient client = null;
    while (true) {
      AuthenticationDialog authDialog = new AuthenticationDialog();
      authDialog.setVisible(true);
      if (authDialog.getPassword() == null || authDialog.getUsername() == null) {
        System.exit(0);
      } else {
        try {
          client = new PicasaClient(authDialog.getUsername(), authDialog.getPassword());
          break;
        } catch (IllegalArgumentException e) {
          if (JOptionPane.OK_OPTION
              == JOptionPane.showConfirmDialog(
                  null,
                  "Ћогин или пароль неверен,\nпопробовать еще раз?",
                  "ќшибка!",
                  JOptionPane.OK_CANCEL_OPTION)) {
            continue;
          } else {
            break;
          }
        }
      }
    }

    try {
      for (AlbumEntry album : client.getAlbums()) {
        System.out.println(album.getTitle().getPlainText());
      }
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (ServiceException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    try {
      FishermanMain main = new FishermanMain(client);
      main.show();
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (ServiceException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Ejemplo n.º 2
0
  private static void testTagFeed(DoubanService myService) {

    try {

      String userId = "sakinijino";
      // cat=movie&start-index=2&max-results=3
      TagFeed tf = myService.getUserTags(userId, "movie", 2, 3);
      for (TagEntry te : tf.getEntries()) {
        printTagEntry(te);
      }

      String movieId = "1424406";
      // start-index=1&max-results=10
      tf = myService.getMovieTags(movieId, 1, 10);
      for (TagEntry te : tf.getEntries()) {
        printTagEntry(te);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  private static void testWriteCollectionEntry(DoubanService myService) {
    try {
      CollectionEntry ce;

      Rating rating = new Rating();
      rating.setValue(4);

      ArrayList<Tag> tags = new ArrayList<Tag>(2);
      Tag t1 = new Tag();
      t1.setName("顾长卫");
      Tag t2 = new Tag();
      t2.setName("李樯");

      tags.add(t1);
      tags.add(t2);

      String movieId = "3036997"; // 立春(And the Spring Comes)
      SubjectEntry se = myService.getMovie(movieId);
      ce = myService.createCollection(new Status("watched"), se, tags, rating);

      printCollectionEntry(ce);

      myService.deleteCollection(ce);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  private static void testWriteNoteEntry(DoubanService myService) {
    NoteEntry noteEntry;
    try {
      String content =
          "立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春";
      noteEntry =
          myService.createNote(
              new PlainTextConstruct("立春"), new PlainTextConstruct(content), "public", "yes");

      printNoteEntry(noteEntry);
      String content2 =
          "立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋立秋";
      myService.updateNote(
          noteEntry,
          new PlainTextConstruct("立秋"),
          new PlainTextConstruct(content2),
          "public",
          "no");
      myService.deleteNote(noteEntry);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
  public static void showPicasaGallery(Long id, String name) {
    notFoundIfNull(id);
    PicasaGallery gallery = PicasaGallery.findById(id);
    notFoundIfNull(gallery);

    PicasawebService service = new PicasawebService("portfolio");
    List<PhotoEntry> photoEntries = Collections.emptyList();
    try {
      java.net.URL feedUrl = new java.net.URL(gallery.getFeedUrl());

      AlbumFeed feed = service.getFeed(feedUrl, AlbumFeed.class);
      photoEntries = feed.getPhotoEntries();
    } catch (MalformedURLException e) {
      Logger.error("Service URL for Picasa is not well formed");
      e.printStackTrace();
    } catch (IOException e) {
      Logger.error("Error I/O while communicating with Picasa Service");
      e.printStackTrace();
    } catch (ServiceException e) {
      Logger.error("Picasa service error");
      e.printStackTrace();
    }

    List<ImageView> images = new ArrayList<ImageView>();
    for (PhotoEntry entry : photoEntries) {
      ImageView image = new ImageView();
      // We take the largest
      image.thumbnail =
          entry.getMediaThumbnails().get(entry.getMediaThumbnails().size() - 1).getUrl();
      image.url = entry.getMediaContents().get(0).getUrl();
      images.add(image);
    }

    render("Application/gallery.html", images, gallery);
  }
Ejemplo n.º 6
0
  private static void testReviewEntry(DoubanService myService) {
    ReviewEntry reviewEntry;
    try {

      String reviewId = "1138468";
      reviewEntry = myService.getReview(reviewId);
      printReviewEntry(reviewEntry);

      String userId = "1026712";
      ReviewFeed reviewFeed = myService.getUserReviews(userId);
      for (ReviewEntry sf : reviewFeed.getEntries()) {
        printReviewEntry(sf);
      }

      String movieId = "1424406";
      // start-index=2&max-results=2
      reviewFeed = myService.getMovieReviews(movieId, 2, 2, "score");
      for (ReviewEntry sf : reviewFeed.getEntries()) {
        printReviewEntry(sf);
      }
      reviewFeed = myService.getMovieReviews(movieId, 2, 2, "time");
      for (ReviewEntry sf : reviewFeed.getEntries()) {
        printReviewEntry(sf);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    SpreadsheetService service = new SpreadsheetService("Sheet1");
    try {
      String sheetUrl =
          "https://spreadsheets.google.com/feeds/list/1BuEN5wHRrQJFgTj9bXN6lXEAcb1lcJ-QYg4Lya-3lCo/default/public/values";

      URL url = new URL(sheetUrl);

      // Get Feed of Spreadsheet url
      ListFeed lf = service.getFeed(url, ListFeed.class);

      // Iterate over feed to get cell value
      for (ListEntry le : lf.getEntries()) {
        CustomElementCollection cec = le.getCustomElements();
        // Pass column name to access it's cell values
        String val = cec.getValue("CustomerName");
        System.out.println(val);
        String val2 = cec.getValue("Customeremailid");
        System.out.println(val2);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 8
0
  public static void main(String[] args) {

    try {
      // myFrame.add(newSubPanel);

      JTabbedPane tabbedPane = new JTabbedPane();
      isSmall = true;
      // tabbedPane.add(new JButton("asd"));
      JMenuBar menuBar = new JMenuBar();
      // menuBar.add(tabbedPane);
      menuBar.setBackground(Color.white);
      menuBar.setVisible(true);
      menuBar.add(new ResolutionButton());
      menuBar.add(new NextPanelbutton(false));
      menuBar.add(new NextPanelbutton(true));
      // menuBar.setPreferredSize(new Dimension(1024, 20));
      UpploaderView u = new UpploaderView();
      tabbedPane.addTab("Channel", u);
      tabbedPane.addTab("Videos", newSubPanel);
      //	menuBar.add(tabbedPane);
      // tabbedPane.setTabComponentAt(0,menuBar);

      // myFrame.add(u);
      // myFrame.add(tabbedPane);
      //	myFrame.setLayout(new FlowLayout());
      // Toolkit toolkit = Toolkit.getDefaultToolkit();
      // System.out.println(toolkit.getScreenSize().width+"x"+toolkit.getScreenSize().height);
      myFrame.setSize(1024, 600);
      myFrame.setJMenuBar(menuBar);
      myFrame.addWindowListener(new WindowClose());
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setVisible(true);
      Dimension panelDim = myFrame.getRootPane().getSize();
      // myFrame.add(newSubPanel);
      for (int i = 0; i < 3; i++) {
        if (i == 0) {
          newSubs = new DoublePanelStack(new NewSubVideoPanel(panelDim));
          myFrame.add(newSubs.getCurrentPanel());
          myFrame.validate();
          myFrame.repaint();
        }
        if (StatCol.newsubsStartIndex < StatCol.MAXNEWSUBVIDEOS)
          newSubs.add(new NewSubVideoPanel(panelDim));
      }
      // u.init();
      // sub2 = new NewSubVideoPanel(newSubPanel.init(),panelDim);
      myFrame.validate();
      // myFrame.pack();

    } catch (AuthenticationException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * Main menu for the Sample Google Finance Portfolios Client.
  *
  * @param args server, user email, and user password in that order.
  */
 public static void main(String[] args) {
   // Google Finance GData service.
   FinanceService service = new FinanceService("Google-PortfoliosDemo-1.0");
   Scanner sc = new Scanner(System.in);
   System.out.println("Sample Google Finance Portfolios Client");
   if (args.length != 1 && args.length != 3) {
     printUsage();
     System.exit(0);
   }
   // Set username and password from command-line arguments if they were passed
   // in. Otherwise prompt the user to login.
   if (args.length == 3) {
     userEmail = args[1];
     userPassword = args[2];
   } else {
     System.out.print("Enter user ID: ");
     userEmail = sc.nextLine();
     System.out.print("Enter user password: "******"default";
   printMainMenuHelp();
   try {
     while (true) {
       switch (processMainMenuCommand(sc.nextLine().toLowerCase())) {
         case PORTFOLIOS:
           portfolioMenu(service, sc);
           break;
         case POSITIONS:
           positionMenu(service, sc);
           break;
         case TRANSACTIONS:
           transactionMenu(service, sc);
           break;
         case QUIT:
           System.exit(0);
         case HELP:
           printMainMenuHelp();
           break;
         default:
           printMainMenuHelp();
       }
     }
   } catch (IOException e) {
     // Communication error.
     System.err.println("There was a problem communicating with the service.");
     e.printStackTrace();
   } catch (ServiceException e) {
     // Server side error.
     System.err.println("The server had a problem handling your request.");
     e.printStackTrace();
   }
 }
Ejemplo n.º 10
0
 private static void testUserFriends(DoubanService myService) {
   try {
     UserFeed uf = myService.getUserFriends("subdragon", 1, 2);
     for (UserEntry ue : uf.getEntries()) {
       printUserEntry(ue);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ServiceException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 11
0
 public void run() {
   try {
     videoFeed = service.query(query, VideoFeed.class);
     videoEntries = (LinkedList) videoFeed.getEntries();
     setChanged();
     notifyObservers();
   } catch (IOException e) {
     e.printStackTrace();
     return;
   } catch (ServiceException e) {
     e.printStackTrace();
     return;
   }
 }
Ejemplo n.º 12
0
  private static void testCollectionEntry(DoubanService myService) {
    try {
      String cid = "1123456";

      CollectionEntry ce = myService.getCollection(cid);
      printCollectionEntry(ce);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 13
0
 private static void testCollectionFeed(DoubanService myService) {
   try {
     String userId = "sakinijino";
     // cat=movie&start-index=1&max-results=2&tag=TimBurton
     // status=null
     CollectionFeed cf = myService.getUserCollections(userId, "movie", "TimBurton", null, 1, 2);
     for (CollectionEntry ce : cf.getEntries()) {
       printCollectionEntry(ce);
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ServiceException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 14
0
  private static void testNoteEntry(DoubanService myService) {
    NoteEntry noteEntry;
    NoteFeed noteFeed;
    try {
      String noteId = "17730279";
      noteEntry = myService.getNote(noteId);
      printNoteEntry(noteEntry);

      noteFeed = myService.getUserNotes("aka", 2, 2);
      for (NoteEntry ne : noteFeed.getEntries()) {
        printNoteEntry(ne);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 15
0
  private static void testSubjectEntry(DoubanService myService) {
    SubjectEntry subjectEntry;
    try {
      String bookId = "2023013";
      subjectEntry = myService.getBook(bookId);
      printSubjectEntry(subjectEntry);

      // tag=cowboy&start-index=1&max-results=2
      // q=null
      SubjectFeed subjectFeed = myService.findMovie(null, "cowboy", 1, 2);
      for (SubjectEntry sf : subjectFeed.getEntries()) {
        printSubjectEntry(sf);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 16
0
 private static void testMiniblogEntry(DoubanService myService) {
   String userId = "sakinijino";
   MiniblogFeed mf;
   try {
     mf = myService.getUserMiniblogs(userId, 1, 2);
     for (MiniblogEntry me : mf.getEntries()) {
       printMiniblogEntry(me);
     }
     mf = myService.getContactsMiniblogs("apitest", 1, 2);
     for (MiniblogEntry me : mf.getEntries()) {
       printMiniblogEntry(me);
     }
     myService.createSaying(new PlainTextConstruct("Hello Douban API java client!"));
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ServiceException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 17
0
  /**
   * Starts up the demo and prompts for commands.
   *
   * @param username name of user to authenticate (e.g. [email protected])
   * @param password password to use for authentication
   * @throws AuthenticationException if the service is unable to validate the username and password.
   */
  public void run(String username, String password) throws AuthenticationException {
    for (String s : WELCOME_MESSAGE) {
      out.println(s);
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // Login and prompt the user to pick a sheet to use.
    login(username, password);
    try {
      loadSheet(reader);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }

    while (executeCommand(reader)) {}
  }
Ejemplo n.º 18
0
  public static void parseOneWorkSheet(
      SpreadsheetService service,
      Project project,
      ProjectMetadata metadata,
      final ImportingJob job,
      URL docURL,
      URL worksheetURL,
      int limit,
      JSONObject options,
      List<Exception> exceptions) {

    try {
      WorksheetEntry worksheetEntry = service.getEntry(worksheetURL, WorksheetEntry.class);
      String spreadsheetName = docURL.toExternalForm();
      try {
        SpreadsheetEntry spreadsheetEntry = service.getEntry(docURL, SpreadsheetEntry.class);
        spreadsheetName = spreadsheetEntry.getTitle().getPlainText();
      } catch (ServiceException e) { // RedirectRequiredException among others
        // fall back to just using the URL (better for traceability anyway?)
      }

      String fileSource = spreadsheetName + " # " + worksheetEntry.getTitle().getPlainText();

      setProgress(job, fileSource, 0);
      TabularImportingParserBase.readTable(
          project,
          metadata,
          job,
          new WorksheetBatchRowReader(job, fileSource, service, worksheetEntry, 20),
          fileSource,
          limit,
          options,
          exceptions);
      setProgress(job, fileSource, 100);
    } catch (IOException e) {
      e.printStackTrace();
      exceptions.add(e);
    } catch (ServiceException e) {
      e.printStackTrace();
      exceptions.add(e);
    }
  }
Ejemplo n.º 19
0
  private static void testUserEntry(DoubanService myService) {
    UserEntry userEntry;
    try {
      String userId = "ahbei";
      userEntry = myService.getUser(userId);
      printUserEntry(userEntry);

      // printUserEntry(myService.getAuthorizedUser());

      // q=douban&start-index=10&max-results=1
      UserFeed userFeed = myService.findUser("douban", 1, 1);
      for (UserEntry ue : userFeed.getEntries()) {
        printUserEntry(ue);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 20
0
  private static void testWriteReviewEntry(DoubanService myService) {
    ReviewEntry reviewEntry;
    try {
      String movieId = "3036997"; // 立春(And the Spring Comes)

      SubjectEntry se = myService.getMovie(movieId);
      Rating rate = new Rating();
      rate.setValue(4);
      String content =
          "立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春立春";
      reviewEntry =
          myService.createReview(
              se, new PlainTextConstruct("立春"), new PlainTextConstruct(content), rate);

      printReviewEntry(reviewEntry);

      myService.deleteReview(reviewEntry);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    UserService userService = UserServiceFactory.getUserService();

    RequestDispatcher disp = null;
    if (userService.isUserLoggedIn()) {
      User user = userService.getCurrentUser();

      PersistenceManager pm = PMF.get();
      ContactsToken token = null;
      try {
        token = pm.getObjectById(ContactsToken.class, user.getEmail());

        String teamName = req.getParameter("teamName");
        if (teamName != null) {
          Team team = TeamDAO.getTeam(teamName);

          if (team != null) {

            // Get contacts
            GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
            oauthParameters.setOAuthConsumerKey("anonymous");
            oauthParameters.setOAuthConsumerSecret("anonymous");
            oauthParameters.setOAuthToken(token.getToken());
            oauthParameters.setOAuthTokenSecret(token.getTokenSecret());
            OAuthSigner signer = new OAuthHmacSha1Signer();

            ContactsService service = new ContactsService("ContactFeedDemo");
            List<ContactEntry> result = null;
            List<String> mails = null;
            try {
              service.setOAuthCredentials(oauthParameters, signer);
              ContactFeed resultFeed =
                  service.getFeed(
                      new URL("https://www.google.com/m8/feeds/contacts/default/full"),
                      ContactFeed.class);

              result = new ArrayList<ContactEntry>(resultFeed.getEntries());
              mails = new ArrayList<String>();
              for (ContactEntry ce : result) {
                for (Email em : ce.getEmailAddresses()) {
                  mails.add(em.getAddress());
                }
              }
              for (TMember tm : team.getMembers()) {
                mails.remove(tm.getName());
              }

            } catch (OAuthException e) {
              e.printStackTrace();
            } catch (ServiceException e) {
              e.printStackTrace();
            }
            // end get contact list

            req.setAttribute("teamName", teamName);
            // req.setAttribute("teamMembers", teamMembers);
            req.setAttribute("contacts", mails);
            RequestDispatcher rd = req.getRequestDispatcher("/AddMember.jsp");
            rd.forward(req, resp);

          } else {
            String errText = "team with team name " + teamName + "doesnt exist.";
            req.setAttribute("err", errText);
            disp = req.getRequestDispatcher("err.jsp");
            disp.forward(req, resp);
          }

        } else {
          String errText = "parametru teamName is null";
          req.setAttribute("err", errText);
          disp = req.getRequestDispatcher("err.jsp");
          disp.forward(req, resp);
        }

      } catch (JDOObjectNotFoundException e) {
        String consumerKey = "anonymous";
        String consumerSecret = "anonymous";
        String scope = "https://www.google.com/m8/feeds";
        String callback = "http://vrchlpet-pc.appspot.com/callbackservlet";

        GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
        oauthParameters.setOAuthConsumerKey(consumerKey);
        oauthParameters.setOAuthConsumerSecret(consumerSecret);
        oauthParameters.setScope(scope);
        oauthParameters.setOAuthCallback(callback);

        OAuthSigner signer = new OAuthHmacSha1Signer();
        GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);

        try {
          oauthHelper.getUnauthorizedRequestToken(oauthParameters);
          String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
          req.getSession().setAttribute("tokenSecret", oauthParameters.getOAuthTokenSecret());
          resp.sendRedirect(approvalPageUrl);
          return;
        } catch (OAuthException ee) {
          ee.printStackTrace();
        }
      }

    } else {
      disp = req.getRequestDispatcher("/projectcontrol");
      disp.forward(req, resp);
    }
  }
  private boolean uploadOneSubmission(
      String id, String instanceFilePath, String jrFormId, String token, String formFilePath) {
    // if the token is null fail immediately
    if (token == null) {
      mResults.put(id, oauth_fail + Collect.getInstance().getString(R.string.invalid_oauth));
      return false;
    }

    HashMap<String, String> answersToUpload = new HashMap<String, String>();
    HashMap<String, String> photosToUpload = new HashMap<String, String>();
    HashMap<String, PhotoEntry> uploadedPhotos = new HashMap<String, PhotoEntry>();

    HttpTransport h = AndroidHttp.newCompatibleTransport();
    GoogleCredential gc = new GoogleCredential();
    gc.setAccessToken(token);

    PicasaClient client = new PicasaClient(h.createRequestFactory(gc));

    // get instance file
    File instanceFile = new File(instanceFilePath);

    // first check to see how many columns we have:
    ArrayList<String> columnNames = new ArrayList<String>();
    try {
      getColumns(formFilePath, columnNames);
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (XmlPullParserException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (IOException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (FormException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    }

    if (columnNames.size() > 255) {
      mResults.put(
          id, Collect.getInstance().getString(R.string.sheets_max_columns, columnNames.size()));
      return false;
    }

    // make sure column names are legal
    for (String n : columnNames) {
      if (!isValidGoogleSheetsString(n)) {
        mResults.put(
            id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_form, n));
        return false;
      }
    }

    // parses the instance file and populates the answers and photos
    // hashmaps.
    try {
      processInstanceXML(instanceFile, answersToUpload, photosToUpload);
    } catch (XmlPullParserException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (FormException e) {
      mResults.put(id, form_fail + Collect.getInstance().getString(R.string.google_repeat_error));
      return false;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    try {
      Thread.sleep(GOOGLE_SLEEP_TIME);
    } catch (InterruptedException e3) {
      e3.printStackTrace();
    }

    // make sure column names in submission are legal (may be different than form)
    for (String n : answersToUpload.keySet()) {
      if (!isValidGoogleSheetsString(n)) {
        mResults.put(
            id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_instance, n));
        return false;
      }
    }

    // if we have any photos to upload,
    // get the picasa album or create a new one
    // then upload the photos
    if (photosToUpload.size() > 0) {
      // First set up a picasa album to upload to:
      // maybe we should move this, because if we don't have any
      // photos we don't care...
      AlbumEntry albumToUse;
      try {
        albumToUse = getOrCreatePicasaAlbum(client, jrFormId);
      } catch (IOException e) {
        e.printStackTrace();
        GoogleAuthUtil.invalidateToken(Collect.getInstance(), token);
        mResults.put(id, picasa_fail + e.getMessage());
        return false;
      }

      try {
        uploadPhotosToPicasa(photosToUpload, uploadedPhotos, client, albumToUse, instanceFile);
      } catch (IOException e1) {
        e1.printStackTrace();
        mResults.put(id, picasa_fail + e1.getMessage());
        return false;
      }
    }

    // All photos have been sent to picasa (if there were any)
    // now upload data to Google Sheet

    String selection = InstanceColumns._ID + "=?";
    String[] selectionArgs = {id};

    Cursor cursor = null;
    String urlString = null;
    try {
      // see if the submission element was defined in the form
      cursor =
          Collect.getInstance()
              .getContentResolver()
              .query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);

      if (cursor.getCount() > 0) {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
          int subIdx = cursor.getColumnIndex(InstanceColumns.SUBMISSION_URI);
          urlString = cursor.isNull(subIdx) ? null : cursor.getString(subIdx);

          // if we didn't find one in the content provider,
          // try to get from settings
          if (urlString == null) {
            SharedPreferences settings =
                PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
            urlString =
                settings.getString(
                    PreferencesActivity.KEY_GOOGLE_SHEETS_URL,
                    Collect.getInstance().getString(R.string.default_google_sheets_url));
          }
        }
      }
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }

    // now parse the url string if we have one
    final String googleHeader = "docs.google.com/spreadsheets/d/";
    String sheetId;
    if (urlString == null || urlString.length() < googleHeader.length()) {
      mResults.put(
          id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString));
      return false;
    } else {
      int start = urlString.indexOf(googleHeader) + googleHeader.length();
      int end = urlString.indexOf("/", start);
      if (end == -1) {
        // if there wasn't a "/", just try to get the end
        end = urlString.length();
      }
      if (start == -1 || end == -1) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString));
        return false;
      }
      sheetId = urlString.substring(start, end);
    }

    SpreadsheetService service = new SpreadsheetService("ODK-Collect");
    service.setAuthSubToken(token);

    // Define the URL to request.
    URL spreadsheetFeedURL = null;
    try {
      spreadsheetFeedURL =
          new URL("https://spreadsheets.google.com/feeds/worksheets/" + sheetId + "/private/full");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    WorksheetQuery query = new WorksheetQuery(spreadsheetFeedURL);
    WorksheetFeed feed = null;
    try {
      feed = service.query(query, WorksheetFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      if (e.getLocalizedMessage().equalsIgnoreCase("forbidden")) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied));
      } else {
        mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody()));
      }
      return false;
    }

    List<WorksheetEntry> spreadsheets = feed.getEntries();
    // get the first worksheet
    WorksheetEntry we = spreadsheets.get(0);

    // check the headers....
    URL headerFeedUrl = null;
    try {
      headerFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + we.getColCount()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    }

    CellFeed headerFeed = null;
    try {
      headerFeed = service.getFeed(headerFeedUrl, CellFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    boolean emptyheaders = true;

    // go through headers
    // if they're empty, resize and add
    for (CellEntry c : headerFeed.getEntries()) {
      if (c.getCell().getValue() != null) {
        emptyheaders = false;
        break;
      }
    }

    if (emptyheaders) {
      // if the headers were empty, resize the spreadsheet
      // and add the headers
      we.setColCount(columnNames.size());
      try {
        we.update();
      } catch (IOException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
      } catch (ServiceException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
      } catch (UnsupportedOperationException e) {
        e.printStackTrace();
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_update_error));
        return false;
      }

      // get the cell feed url
      URL cellFeedUrl = null;
      try {
        cellFeedUrl =
            new URI(
                    we.getCellFeedUrl().toString()
                        + "?min-row=1&max-row=1&min-col=1&max-col="
                        + columnNames.size()
                        + "&return-empty=true")
                .toURL();
      } catch (MalformedURLException e1) {
        e1.printStackTrace();
        mResults.put(id, form_fail + e1.getMessage());
        return false;
      } catch (URISyntaxException e1) {
        e1.printStackTrace();
        mResults.put(id, form_fail + e1.getMessage());
        return false;
      }

      // and the cell feed
      CellFeed cellFeed = null;
      try {
        cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
      } catch (IOException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
      } catch (ServiceException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
      }

      // write the headers
      for (int i = 0; i < cellFeed.getEntries().size(); i++) {
        CellEntry cell = cellFeed.getEntries().get(i);
        String column = columnNames.get(i);
        cell.changeInputValueLocal(column);
        try {
          cell.update();
        } catch (IOException e) {
          e.printStackTrace();
          mResults.put(id, form_fail + e.getMessage());
          return false;
        } catch (ServiceException e) {
          e.printStackTrace();
          mResults.put(id, form_fail + e.getMessage());
          return false;
        }
      }
    }

    // we may have updated the feed, so get a new one
    // update the feed
    try {
      headerFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + we.getColCount()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e3) {
      e3.printStackTrace();
      mResults.put(id, form_fail + e3.getMessage());
      return false;
    } catch (URISyntaxException e3) {
      e3.printStackTrace();
      mResults.put(id, form_fail + e3.getMessage());
      return false;
    }
    try {
      headerFeed = service.getFeed(headerFeedUrl, CellFeed.class);
    } catch (IOException e2) {
      e2.printStackTrace();
      mResults.put(id, form_fail + e2.getMessage());
      return false;
    } catch (ServiceException e2) {
      e2.printStackTrace();
      mResults.put(id, form_fail + e2.getMessage());
      return false;
    }

    // see if our columns match, now
    URL cellFeedUrl = null;
    try {
      cellFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + headerFeed.getEntries().size()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    }
    CellFeed cellFeed = null;
    try {
      cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    // first, get all the columns in the spreadsheet
    ArrayList<String> sheetCols = new ArrayList<String>();
    for (int i = 0; i < cellFeed.getEntries().size(); i++) {
      CellEntry cell = cellFeed.getEntries().get(i);
      sheetCols.add(cell.getPlainTextContent());
    }

    ArrayList<String> missingColumns = new ArrayList<String>();
    for (String col : columnNames) {
      if (!sheetCols.contains(col)) {
        missingColumns.add(col);
      }
    }

    if (missingColumns.size() > 0) {
      // we had some missing columns, so error out
      String missingString = "";
      for (int i = 0; i < missingColumns.size(); i++) {
        missingString += missingColumns.get(i);
        if (i < missingColumns.size() - 1) {
          missingString += ", ";
        }
      }
      mResults.put(
          id,
          form_fail
              + Collect.getInstance()
                  .getString(R.string.google_sheets_missing_columns, missingString));
      return false;
    }

    // if we get here.. all has matched
    // so write the values
    ListEntry row = new ListEntry();

    // add photos to answer set
    Iterator<String> photoIterator = uploadedPhotos.keySet().iterator();
    while (photoIterator.hasNext()) {
      String key = photoIterator.next();
      String url = uploadedPhotos.get(key).getImageLink();
      answersToUpload.put(key, url);
    }

    Iterator<String> answerIterator = answersToUpload.keySet().iterator();
    while (answerIterator.hasNext()) {
      String path = answerIterator.next();
      String answer = answersToUpload.get(path);
      // Check to see if answer is a location, if so, get rid of accuracy
      // and altitude
      // try to match a fairly specific pattern to determine
      // if it's a location
      // [-]#.# [-]#.# #.# #.#
      Pattern p =
          Pattern.compile(
              "^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\" + ".[0-9]+\\s[0-9]+\\.[0-9]+$");
      Matcher m = p.matcher(answer);
      if (m.matches()) {
        // get rid of everything after the second space
        int firstSpace = answer.indexOf(" ");
        int secondSpace = answer.indexOf(" ", firstSpace + 1);
        answer = answer.substring(0, secondSpace);
        answer = answer.replace(' ', ',');
      }
      row.getCustomElements().setValueLocal(TextUtils.htmlEncode(path), answer);
    }

    // Send the new row to the API for insertion.
    try {
      URL listFeedUrl = we.getListFeedUrl();
      row = service.insert(listFeedUrl, row);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      if (e.getLocalizedMessage().equalsIgnoreCase("Forbidden")) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied));
      } else {
        mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody()));
      }
      return false;
    }

    mResults.put(id, Collect.getInstance().getString(R.string.success));
    return true;
  }
  public void processRequest(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    //		PrintWriter out = resp.getWriter();
    //	    resp.setContentType("text/plain");

    String signedReq = req.getParameter("signed_request");
    if (signedReq == null) {
      System.out.println("ERROR: Unable to retrieve signed_request parameter");

    } else {
      int count = 0;
      String payload = null;

      // The parameter contains encoded signature and payload separated by Ô.Õ
      StringTokenizer st = new StringTokenizer(signedReq, ".");

      // Retrieve payload (Note: encoded signature is used for internal verification and it is
      // optional)
      while (st.hasMoreTokens()) {
        if (count == 1) {
          payload = st.nextToken();
          break;
        } else st.nextToken();

        count++;
      }

      // Initialize Base64 decoder
      Base64 dec = new Base64();

      // Replace special character in payload as indicated by FB
      payload = payload.replace("-", "+").replace("_", "/").trim();

      // Decode payload
      try {
        byte[] decodedPayload = dec.decode(payload.getBytes());
        payload = new String(decodedPayload, "UTF8");
        //	            out.println("payload");
        //	            out.println(payload);
      } catch (IOException e) {
        System.out.println("ERROR: Unable to perform Base64 Decode");
      }

      // JSON Decode - payload
      try {
        UserAccount acct = new UserAccount();
        JSONObject payloadObject = new JSONObject(payload);
        String facebookId = "" + payloadObject.get("user_id"); // Retrieve user ID
        String oauthToken = "" + payloadObject.get("oauth_token"); // Retrieve oauth token

        acct.setFacebookId(facebookId);
        acct.setOauthToken(oauthToken);

        String regData = "" + payloadObject.get("registration");

        JSONObject payloadObject2 = new JSONObject(regData);
        String name = "" + payloadObject2.get("name");
        String email = "" + payloadObject2.get("email");
        String language = "" + payloadObject2.get("language");
        String method = "" + payloadObject2.get("method");
        String phone = "" + payloadObject2.get("phone");
        String loc = "" + payloadObject2.get("location");
        String send1 = "" + payloadObject2.get("send-1");
        String send2 = "" + payloadObject2.get("send-2");
        String send3 = "" + payloadObject2.get("send-3");

        acct.setName(name);
        acct.setEmail(email);
        acct.setLanguage(language);
        acct.setMethod(method);
        acct.setPhone(phone);
        acct.setSend1(send1);
        acct.setSend2(send2);
        acct.setSend3(send3);

        JSONObject payloadObject3 = new JSONObject(loc);
        String locD = "" + payloadObject3.get("name");

        acct.setLocation(locD);
        acct.setCreated(getCurrentDateTime());

        DataAct da = new DataAct();
        da.insertNewUser(acct);
      } catch (JSONException e) {
        e.printStackTrace();
        // out.println("JSON Decode - payload Error");
      } catch (ServiceException e) {
        // TODO Auto-generated catch block
        // Tout.println("ServiceException Error");
        e.printStackTrace();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        // Tout.println("Exception Error");
        e.printStackTrace();
      }
    }

    resp.sendRedirect("index.html");
  }
Ejemplo n.º 24
0
  public static void parse(
      GoogleService service,
      Project project,
      ProjectMetadata metadata,
      final ImportingJob job,
      int limit,
      JSONObject options,
      List<Exception> exceptions) {

    String docUrlString = JSONUtilities.getString(options, "docUrl", null);
    String id = getFTid(docUrlString); // Use GDataExtension.getFusionTableKey(url) ?
    // TODO: Allow arbitrary Fusion Tables URL instead of (in addition to?) constructing our own?

    try {
      List<FTColumnData> columns = new ArrayList<GDataImporter.FTColumnData>();
      List<List<String>> rows = GDataExtension.runFusionTablesSelect(service, "DESCRIBE " + id);
      if (rows.size() > 1) {
        for (int i = 1; i < rows.size(); i++) {
          List<String> row = rows.get(i);
          if (row.size() >= 2) {
            FTColumnData cd = new FTColumnData();
            cd.name = row.get(1);
            cd.type = FTColumnType.STRING;

            if (row.size() > 2) {
              String type = row.get(2).toLowerCase();
              if (type.equals("number")) {
                cd.type = FTColumnType.NUMBER;
              } else if (type.equals("datetime")) {
                cd.type = FTColumnType.DATETIME;
              } else if (type.equals("location")) {
                cd.type = FTColumnType.LOCATION;
              }
            }
            columns.add(cd);
          }
        }

        setProgress(job, docUrlString, -1);

        // Force these options for the next call because each fusion table
        // is strictly structured with a single line of headers.
        JSONUtilities.safePut(
            options, "ignoreLines", 0); // number of blank lines at the beginning to ignore
        JSONUtilities.safePut(options, "headerLines", 1); // number of header lines

        TabularImportingParserBase.readTable(
            project,
            metadata,
            job,
            new FusionTableBatchRowReader(job, docUrlString, service, id, columns, 100),
            docUrlString,
            limit,
            options,
            exceptions);
        setProgress(job, docUrlString, 100);
      }
    } catch (IOException e) {
      e.printStackTrace();
      exceptions.add(e);
    } catch (ServiceException e) {
      e.printStackTrace();
      exceptions.add(e);
    }
  }