1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
/* * Copyright 2014 Loic Merckel * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * * The original version of this file (i.e., the one that is copyrighted 2013 Google Inc.) * can be found here: * * https://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples * */ package io.uploader.drive; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import io.uploader.drive.auth.DriveUploaderAuthorizationCodeInstalledApp; import io.uploader.drive.auth.webbrowser.Browser; import io.uploader.drive.auth.webbrowser.SimpleBrowserImpl; import io.uploader.drive.config.Configuration; import io.uploader.drive.config.auth.AuthenticationSettingsImpl; import io.uploader.drive.gui.MainWindow; import io.uploader.drive.gui.dlg.MessageDialogs; import io.uploader.drive.gui.dlg.MessageDialogs.Response; import io.uploader.drive.util.Callback; import io.uploader.drive.util.ObserverService; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import org.apache.commons.configuration.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.common.base.Preconditions; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.WindowEvent; public class DriveUploader extends Application { private static final Logger logger = LoggerFactory.getLogger(DriveUploader.class); private static final boolean activateNativeLookAndFeelForMacOs = true ; public static boolean isMacOsX () { if (!activateNativeLookAndFeelForMacOs) { return false ; } String os = System.getProperty("os.name") ; return (os != null && os.toLowerCase().contains("mac")) ; } /** * Be sure to specify the name of your application. If the application name * is {@code null} or blank, the application will log a warning. Suggested * format is "MyCompany-ProductName/1.0". */ private static final String APPLICATION_NAME = Configuration.INSTANCE.getAppName() ; /** Directory to store user credentials. */ private static final java.io.File DATA_STORE_DIR = new java.io.File(Configuration.INSTANCE.getDataStoreDirectory()); /** * Global instance of the {@link DataStoreFactory}. The best practice is to * make it a single globally shared instance across your application. */ private static FileDataStoreFactory dataStoreFactory; /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = JacksonFactory .getDefaultInstance(); /** Global instance of the HTTP transport. */ private static HttpTransport httpTransport; private static Drive client; private static final AppEvent appEvent = new AppEvent () ; public static void main(String[] args) { if (isMacOsX ()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", Configuration.INSTANCE.getAppName()); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { logger.error("Error occurred while initializing the UI", e); } } Platform.setImplicitExit(false); // load the settings String settingsFile = "driveuploader-settings.xml" ; if (!new java.io.File (settingsFile).exists()) settingsFile = null ; try { Configuration.INSTANCE.load(settingsFile); } catch (ConfigurationException e) { logger.error("Error occurred while initializing the configuration", e); } try { // initialize the transport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // initialize the data store factory dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); } catch (IOException e) { logger.error("Error occurred while initializing the drive", e); Platform.exit() ; } catch (Throwable t) { logger.error("Error occurred while initializing the drive", t); Platform.exit() ; } launch(args); } private static void authorize(final Browser browser, final Callback<Credential> callback) { try { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, new InputStreamReader(AuthenticationSettingsImpl.getClientSecretJson())); if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out .println("Overwrite the src/main/resources/client_secrets.json file with the client secrets file " + "you downloaded from the Quickstart tool or manually enter your Client ID and Secret " + "from https://code.google.com/apis/console/?api=drive#project:94720202188 " + "into src/main/resources/client_secrets.json"); System.exit(1); } Configuration.INSTANCE.setAuthenticationSettingsImpl(new AuthenticationSettingsImpl (clientSecrets)); // Set up authorization code flow. Set<String> scopes = new HashSet<String>(); scopes.add(DriveScopes.DRIVE); // old api for large file support (where upload takes more than one hour) scopes.add("https://docs.google.com/feeds") ; final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, scopes) .setDataStoreFactory(dataStoreFactory) .setAccessType("offline").setApprovalPrompt("force").build(); // authorize final VerificationCodeReceiver receiver = new LocalServerReceiver() ; ObserverService<Credential> service = new ObserverService<Credential>() { private volatile DriveUploaderAuthorizationCodeInstalledApp driveUploaderAuthorizationCodeInstalledApp = null ; @Override protected Task<Credential> createTask() { Task<Credential> task = new Task<Credential>() { @Override protected Credential call() throws Exception { driveUploaderAuthorizationCodeInstalledApp = new DriveUploaderAuthorizationCodeInstalledApp( flow, receiver, browser) ; Credential credential = driveUploaderAuthorizationCodeInstalledApp.authorize("user"); return credential; } }; return task ; } }; service.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { logger.info("Login success") ; Credential ret = (Credential) t.getSource().getValue(); callback.onSuccess(ret); } }); appEvent.addObserver(service) ; service.start(); } catch (Exception e) { callback.onFailure(e) ; } } @Override public void stop() throws Exception { logger.info("Stop!") ; super.stop(); } @Override public void start(final Stage stage) throws Exception { Preconditions.checkNotNull(stage) ; try { stage.onCloseRequestProperty().set(new EventHandler<WindowEvent>() { public void handle(WindowEvent e) { logger.info("Close request") ; if (Response.NO == MessageDialogs.showConfirmDialog(stage, "Are you sure you want to close the application?", "Confirmation")) { e.consume(); return ; } appEvent.exit () ; Platform.exit (); // TODO: // Investigate why when we shutdown the authentication service // before the end of the process, the app hangs after closing the main window... // http://stackoverflow.com/questions/4425350/how-to-terminate-a-thread-blocking-on-socket-io-operation-instantly //if (client == null) { System.exit(0) ; //} } }); final List<Integer> logoSizeList = Arrays.asList(16, 32, 64, 128, 256, 512) ; final String logoNameBase = "DriveUploader" ; final String logoNameExt = ".png" ; for (Integer size : logoSizeList) { StringBuilder logoName = new StringBuilder () ; logoName.append(logoNameBase) ; logoName.append(size) ; logoName.append(logoNameExt) ; Image logo = new Image(getClass().getResourceAsStream("/images/" + logoName)) ; stage.getIcons().add(logo); } //final Browser browser = new SimpleBrowser (new Stage (), null) ; final Browser browser = new SimpleBrowserImpl (stage, null) ; authorize (browser, new Callback<Credential> () { @Override public void onSuccess(Credential result) { logger.info("Received credential") ; client = new Drive.Builder(httpTransport, JSON_FACTORY, result) .setApplicationName(APPLICATION_NAME).build(); Configuration.INSTANCE.setCredential(result); //browser.close () ; try { MainWindow mainWindow = new MainWindow (client, stage, appEvent, Configuration.INSTANCE) ; mainWindow.show() ; } catch (IOException e) { logger.error("Error occurred while creating the main window", e) ; Platform.exit() ; } } @Override public void onFailure(Throwable cause) { logger.error("Error occurred while authenticating", cause) ; Platform.exit() ; }}) ; }catch (Exception e) { Platform.exit() ; throw e ; } } } |
https://github.com/roikku/drive-uploader