Java 类com.google.api.client.http.FileContent 实例源码

项目:SpartanDrive    文件:AddActionHandler.java   
private void uploadFileToDrive(java.io.File file) {
    try {
    // File's metadata.
    final File body = new File();
    body.setTitle(file.getName());
    InputStream is = new BufferedInputStream(new FileInputStream(file));
    body.setMimeType(URLConnection.guessContentTypeFromStream(is));
    //TODO: Upload to specific folder!
    // File's content.
    final FileContent mediaContent = new FileContent(URLConnection.guessContentTypeFromStream(is), file);
        new Thread() {
            public void run() {
                try {
                    File uploadedFile = DriveFiles.getDriveFileInstance().getDrive_files().insert(body, mediaContent).execute();
                    closeActionHandlerDialog();
                    new RefreshAction().updateAction(context);
                }
                catch(Exception ie){
                    closeActionHandlerDialog();
                }
            }
        }.start();
    } catch (Exception e) {
        closeActionHandlerDialog();
    }
}
项目:AGIA    文件:GoogleDriveServiceImpl.java   
@Override
public File createFile(String sParentID, String sName, java.io.File sFile, String sMimeType, Map<String, String> sProperties) throws IOException {
    File aResult = null;
    if (drive != null) {
        File fileMetadata = new File();
        fileMetadata.setTitle(sName);
        ParentReference aParentReference = new ParentReference();
        aParentReference.setId(sParentID);
        fileMetadata.setParents(Arrays.asList(aParentReference));

        FileContent mediaContent = new FileContent(sMimeType, sFile);

        Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
        MediaHttpUploader uploader = insert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        aResult = insert.execute();

        setProperties(aResult.getId(), sProperties);
    }
    return aResult;
}
项目:wireless-positioning    文件:UploadFileToDrive.java   
private String insertFile(java.io.File dir, String filename) throws IOException {

        String result = "File not updated: " + filename;
        // File's binary content
        java.io.File localFile = new java.io.File(dir, filename);
        FileContent fileContent = new FileContent(DetectorActivity.OUTPUT_MIME_TYPE, localFile);

        // File's metadata.
        File file = new File();
        file.setTitle(localFile.getName());
        file.setMimeType(DetectorActivity.OUTPUT_MIME_TYPE);

        File insertedFile = service.files().insert(file, fileContent).execute();
        if (insertedFile != null) {
            result = "File created: " + insertedFile.getTitle();
        }
        return result;
    }
项目:wireless-positioning    文件:UploadFileToDrive.java   
private String updateFile(java.io.File dir, String filename, File file) throws IOException {

        String result = "File not updated: " + filename;

        // File's new content.
        java.io.File localFile = new java.io.File(dir, filename);
        FileContent fileContent = new FileContent(DetectorActivity.OUTPUT_MIME_TYPE, localFile);

        // Send the request to the API.
        File updatedFile = service.files().update(file.getId(), file, fileContent).execute();

        if (updatedFile != null) {
            result = ("File updated: " + updatedFile.getTitle());
        }
        return result;
    }
项目:gdx-gamesvcs    文件:GpgsClient.java   
/**
 * Blocking version of {@link #saveGameState(String, byte[], long, ISaveGameStateResponseListener)}
 *
 * @param fileId
 * @param gameState
 * @param progressValue
 * @throws IOException
 */
public void saveGameStateSync(String fileId, byte[] gameState, long progressValue) throws IOException {

    java.io.File file = java.io.File.createTempFile("games", "dat");
    new FileHandle(file).writeBytes(gameState, false);

    // no type since it is binary data
    FileContent mediaContent = new FileContent(null, file);

    // find file on server
    File remoteFile = findFileByNameSync(fileId);

    // file exists then update it
    if (remoteFile != null) {

        // just update content, leave metadata intact.

        GApiGateway.drive.files().update(remoteFile.getId(), null, mediaContent).execute();

        Gdx.app.log(TAG, "File updated ID: " + remoteFile.getId());
    }
    // file doesn't exists then create it
    else {
        File fileMetadata = new File();
        fileMetadata.setName(fileId);

        // app folder is a reserved keyyword for current application private folder.
        fileMetadata.setParents(Collections.singletonList("appDataFolder"));

        remoteFile = GApiGateway.drive.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();

        Gdx.app.log(TAG, "File created ID: " + remoteFile.getId());
    }

}
项目:joanne    文件:UploadFiles.java   
public void simpleUpload(java.io.File filePath,String name,String mime) throws IOException{
    driveService = getDriveService();
    File fileMetadata = new File();
    fileMetadata.setName(name);
    fileMetadata.setMimeType(mime);

    FileContent mediaContent = new FileContent(mime, filePath);
    File file = driveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
    System.out.println("File ID: " + file.getId());
}
项目:ExcelToGoogleSpreadSheet    文件:SpreadSheet.java   
public static boolean convertToSpreedSheet(Drive drive,
                                           String path) {
    com.google.api.services.drive.model.File fileMetaData = new com.google.api.services.drive.model.File();
    java.io.File file = new java.io.File(path);
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    fileMetaData.setName(file.getName());
    String googleSheetMimeType = "application/vnd.google-apps.spreadsheet";
    fileMetaData.setMimeType(googleSheetMimeType);

    FileContent mediaContent = new FileContent(mimeTypesMap.getContentType(file), file);

    com.google.api.services.drive.model.File f = null;
    Drive.Files.Create create = null;

    try {
        System.out.println("Uploading file " + file.getName());
        create = drive.files().create(fileMetaData, mediaContent)
                .setFields("id, parents, mimeType, webViewLink");
        create.getMediaHttpUploader().setProgressListener(new FileUpdateProgressListener());

        // Using default chunk size of 10MB.
        create.getMediaHttpUploader().setChunkSize(MediaHttpUploader.DEFAULT_CHUNK_SIZE);
        f = create.execute();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    System.out.println("File ID: " + f.getId() + " Parent: " + f.getParents().toString()
    + " MimeType: " + f.getMimeType() + " link: " + f.getWebViewLink());
    return true;

}
项目:jenkins-plugin-google-driver-uploader    文件:GoogleDriveManager.java   
/**
 * Insert new file.
 *
 * @param title Title of the file to insert, including the extension.
 * @param description Description of the file to insert.
 * @param parentId Optional parent folder's ID.
 * @param mimeType MIME type of the file to insert.
 * @param file The file to insert.
 * @return Inserted file metadata if successful, {@code null} otherwise.
 */
private File insertFile(String title, String description, String parentId, String mimeType, java.io.File file)
        throws IOException {
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    if (parentId != null && parentId.length() > 0) {
        body.setParents(Collections.singletonList(new ParentReference().setId(parentId)));
    }

    FileContent mediaContent = new FileContent(mimeType, file);
    return drive.files().insert(body, mediaContent).execute();
}
项目:pubsub    文件:GCEController.java   
/**
 * Uploads a given file to Google Storage.
 */
private void uploadFile(Path filePath) throws IOException {
  try {
    byte[] md5hash =
        Base64.decodeBase64(
            storage
                .objects()
                .get(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
                .execute()
                .getMd5Hash());
    try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) {
      if (Arrays.equals(md5hash, DigestUtils.md5(inputStream))) {
        log.info("File " + filePath.getFileName() + " is current, reusing.");
        return;
      }
    }
    log.info("File " + filePath.getFileName() + " is out of date, uploading new version.");
    storage
        .objects()
        .delete(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() != NOT_FOUND) {
      throw e;
    }
  }

  storage
      .objects()
      .insert(
          projectName + "-cloud-pubsub-loadtest",
          null,
          new FileContent("application/octet-stream", filePath.toFile()))
      .setName(filePath.getFileName().toString())
      .execute();
  log.info("File " + filePath.getFileName() + " created.");
}
项目:Camel    文件:AbstractGoogleDriveTestSupport.java   
protected File uploadTestFile() {
    File fileMetadata = new File();
    fileMetadata.setTitle(UPLOAD_FILE.getName());
    FileContent mediaContent = new FileContent(null, UPLOAD_FILE);

    final Map<String, Object> headers = new HashMap<String, Object>();
    // parameter type is com.google.api.services.drive.model.File
    headers.put("CamelGoogleDrive.content", fileMetadata);
    // parameter type is com.google.api.client.http.AbstractInputStreamContent
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);

    File result = requestBodyAndHeaders("google-drive://drive-files/insert", null, headers);
    return result;
}
项目:Camel    文件:DriveFilesIntegrationTest.java   
@Test
public void testUpdate1() throws Exception {       

    // First retrieve the file from the API.
    File testFile = uploadTestFile();
    String fileId = testFile.getId();

    // using String message body for single parameter "fileId"
    final File file = requestBody("direct://GET", fileId);

    // File's new metadata.
    file.setTitle("camel.png");

    // File's new content.
    java.io.File fileContent = new java.io.File(TEST_UPLOAD_IMG);
    FileContent mediaContent = new FileContent(null, fileContent);

    // Send the request to the API.

    final Map<String, Object> headers = new HashMap<String, Object>();
    // parameter type is String
    headers.put("CamelGoogleDrive.fileId", fileId);
    // parameter type is com.google.api.services.drive.model.File
    headers.put("CamelGoogleDrive.content", file);
    // parameter type is com.google.api.client.http.AbstractInputStreamContent
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);

    File result = requestBodyAndHeaders("direct://UPDATE_1", null, headers);

    assertNotNull("update result", result);
    LOG.debug("update: " + result);
}
项目:java-docs-samples    文件:OnlinePredictionSample.java   
public static void main(String[] args) throws Exception {
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build();

  RestDescription api = discovery.apis().getRest("ml", "v1").execute();
  RestMethod method = api.getResources().get("projects").getMethods().get("predict");

  JsonSchema param = new JsonSchema();
  String projectId = "YOUR_PROJECT_ID";
  // You should have already deployed a model and a version.
  // For reference, see https://cloud.google.com/ml-engine/docs/deploying-models.
  String modelId = "YOUR_MODEL_ID";
  String versionId = "YOUR_VERSION_ID";
  param.set(
      "name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId));

  GenericUrl url =
      new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true));
  System.out.println(url);

  String contentType = "application/json";
  File requestBodyFile = new File("input.txt");
  HttpContent content = new FileContent(contentType, requestBodyFile);
  System.out.println(content.getLength());

  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
  HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content);

  String response = request.execute().parseAsString();
  System.out.println(response);
}
项目:components    文件:GoogleDriveUtils.java   
public File putResource(GoogleDrivePutParameters parameters) throws IOException {
    String folderId = parameters.getDestinationFolderId();
    File putFile = new File();
    putFile.setParents(Collections.singletonList(folderId));
    Files.List fileRequest = drive.files().list()
            .setQ(format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER, folderId));
    LOG.debug("[putResource] `{}` Exists in `{}` ? with `{}`.", parameters.getResourceName(),
            parameters.getDestinationFolderId(), fileRequest.getQ());
    FileList existingFiles = fileRequest.execute();
    if (existingFiles.getFiles().size() > 1) {
        throw new IOException(messages.getMessage("error.file.more.than.one", parameters.getResourceName()));
    }
    if (existingFiles.getFiles().size() == 1) {
        if (!parameters.isOverwriteIfExist()) {
            throw new IOException(messages.getMessage("error.file.already.exist", parameters.getResourceName()));
        }
        LOG.debug("[putResource] {} will be overwritten...", parameters.getResourceName());
        drive.files().delete(existingFiles.getFiles().get(0).getId()).execute();
    }
    putFile.setName(parameters.getResourceName());
    String metadata = "id,parents,name";
    if (!StringUtils.isEmpty(parameters.getFromLocalFilePath())) {
        // Reading content from local fileName
        FileContent fContent = new FileContent(null, new java.io.File(parameters.getFromLocalFilePath()));
        putFile = drive.files().create(putFile, fContent).setFields(metadata).execute();
        //

    } else if (parameters.getFromBytes() != null) {
        AbstractInputStreamContent content = new ByteArrayContent(null, parameters.getFromBytes());
        putFile = drive.files().create(putFile, content).setFields(metadata).execute();
    }
    return putFile;
}
项目:Cam2PDF    文件:UpvertTask.java   
@Override
protected Exception doInBackground(String... photos) {
    try {
        // Get output Directory
        // Create the PDF and set some metadata
        Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN);
        Resources resources = mContext.getResources();
        document.addTitle(mFilename);
        document.addAuthor(resources.getString(R.string.app_name));
        document.addSubject(resources.getString(R.string.file_subject));
        // Open the file that we will write the pdf to.
        java.io.File fileContent = new java.io.File(ImageUtils.getAlbumStorageDir(MainActivity.ALBUM_NAME) + mFilename);
        OutputStream outputStream = new FileOutputStream(fileContent);
        PdfWriter.getInstance(document, outputStream);
        document.open();
        // Get the document's size
        Rectangle pageSize = document.getPageSize();
        float pageWidth = pageSize.getWidth() - (document.leftMargin() + document.rightMargin());
        float pageHeight = pageSize.getHeight();
        //Loop through images and add them to the document
        for (String path : photos) {
            Image image = Image.getInstance(path);
            image.scaleToFit(pageWidth, pageHeight);
            document.add(image);
            document.newPage();
        }
        // Cleanup
        document.close();
        outputStream.close();
        // Upload time!
        FileContent mediaContent = new FileContent("application/pdf", fileContent);
        File body = new File();
        if (mFolder != null)
            body.setParents(Arrays.asList(new ParentReference().setId(mFolder.getId())));
        body.setTitle(mFilename);
        body.setDescription(resources.getString(R.string.file_subject));
        body.setMimeType("application/pdf");
        Drive.Files.Insert insert = mService.files().insert(body, mediaContent);
        MediaHttpUploader uploader = insert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
        uploader.setProgressListener(new FileProgressListener());
        File file = insert.execute();
        Log.d("C2P", "File Id: " + file.getId());
        /* Database Code */
        DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
        Date date = new Date();
        //file.getFileSize().toString()
        String parentFolder = mFolder != null ? mFolder.getId() : "root";
        Long size = file.getFileSize();
        String fileSizeString = humanReadableByteCount(size);
        Upload upload = new Upload(-1, mFilename, mFolderPath, fileSizeString, parentFolder, format.format(date), mService.about().get().execute().getUser().getEmailAddress());
        UploadDataAdapter mUploadDataAdapter = new UploadDataAdapter(mContext);
        mUploadDataAdapter.open();
        mUploadDataAdapter.addUpload(upload);
        mUploadDataAdapter.close();
    } catch (Exception e) {
        Log.d("C2P", "ERROR", e);
        return e;
    }
    return null;
}
项目:secor    文件:GsUploadManager.java   
@Override
public Handle<?> upload(LogFilePath localPath) throws Exception {
    final String gsBucket = mConfig.getGsBucket();
    final String gsKey = localPath.withPrefix(mConfig.getGsPath()).getLogFilePath();
    final File localFile = new File(localPath.getLogFilePath());
    final boolean directUpload = mConfig.getGsDirectUpload();

    LOG.info("uploading file {} to gs://{}/{}", localFile, gsBucket, gsKey);

    final StorageObject storageObject = new StorageObject().setName(gsKey);
    final FileContent storageContent = new FileContent(Files.probeContentType(localFile.toPath()), localFile);

    final Future<?> f = executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                Storage.Objects.Insert request = mClient.objects().insert(gsBucket, storageObject, storageContent);

                if (directUpload) {
                    request.getMediaHttpUploader().setDirectUploadEnabled(true);
                }

                request.getMediaHttpUploader().setProgressListener(new MediaHttpUploaderProgressListener() {
                    @Override
                    public void progressChanged(MediaHttpUploader uploader) throws IOException {
                        LOG.debug("[{} %] upload file {} to gs://{}/{}",
                                (int) uploader.getProgress() * 100, localFile, gsBucket, gsKey);
                    }
                });

                request.execute();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });

    return new FutureHandle(f);
}
项目:steemj-image-upload    文件:SteemJImageUpload.java   
/**
 * This method handles the final upload to the
 * {@link SteemJImageUploadConfig#getSteemitImagesEndpoint()
 * SteemitImagesEndpoint}.
 * 
 * @param accountName
 *            The Steem account used to sign the upload.
 * @param signature
 *            The signature for this upload.
 * @param fileToUpload
 *            The image to upload.
 * @return A URL object that contains the download URL of the image.
 * @throws HttpResponseException
 *             In case the
 *             {@link SteemJImageUploadConfig#getSteemitImagesEndpoint()
 *             SteemitImagesEndpoint} returned an error.
 */
private static URL executeMultipartRequest(AccountName accountName, String signature, File fileToUpload)
        throws IOException {
    NetHttpTransport.Builder builder = new NetHttpTransport.Builder();

    MultipartContent content = new MultipartContent().setMediaType(new HttpMediaType("multipart/form-data")
            .setParameter("boundary", "----WebKitFormBoundaryaAsqCuJ0UrJUS0dz"));

    FileContent fileContent = new FileContent(URLConnection.guessContentTypeFromName(fileToUpload.getName()),
            fileToUpload);

    MultipartContent.Part part = new MultipartContent.Part(fileContent);

    part.setHeaders(new HttpHeaders().set("Content-Disposition",
            String.format("form-data; name=\"image\"; filename=\"%s\"", fileToUpload.getName())));

    content.addPart(part);

    HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer())
            .buildPostRequest(new GenericUrl(SteemJImageUploadConfig.getInstance().getSteemitImagesEndpoint() + "/"
                    + accountName.getName() + "/" + signature), content);

    LOGGER.debug("{} {}", httpRequest.getRequestMethod(), httpRequest.getUrl().toURI());

    HttpResponse httpResponse = httpRequest.execute();

    LOGGER.debug("{} {} {} ({})", httpResponse.getRequest().getRequestMethod(),
            httpResponse.getRequest().getUrl().toURI(), httpResponse.getStatusCode(),
            httpResponse.getStatusMessage());

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode response = objectMapper.readTree(httpResponse.parseAsString());

    return new URL(response.get("url").asText());
}
项目:Xero-Java    文件:OAuthRequestResource.java   
public  OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, String contentType, File file, Map<? extends String, ?> params) {
    this(config, signerFactory, resource, method, params);
    this.contentType = contentType;
    this.requestBody = new FileContent(contentType, file);
}
项目:DriveBackup    文件:GoogleUploader.java   
public static void uploadFile(java.io.File file, String type) throws IOException {
    Drive service = getDriveService();

    File body = new File();
    body.setTitle(file.getName());
    body.setDescription("DriveBackup plugin");
    body.setMimeType("application/zip");

    String destination = Config.getDestination();

    FileContent mediaContent = new FileContent("application/zip", file);

    File parentFolder = getFolder(destination);
    if (parentFolder == null) {
        System.out.println("Creating a folder");
        parentFolder = new File();
        parentFolder.setTitle(destination);
        parentFolder.setMimeType("application/vnd.google-apps.folder");
        parentFolder = service.files().insert(parentFolder).execute();
    }

    File childFolder = getFolder(type, parentFolder);
    ParentReference childFolderParent = new ParentReference();
    childFolderParent.setId(parentFolder.getId());
    if (childFolder == null) {
        System.out.println("Creating a folder");
        childFolder = new File();
        childFolder.setTitle(type);
        childFolder.setMimeType("application/vnd.google-apps.folder");
        childFolder.setParents(Collections.singletonList(childFolderParent));

        childFolder = service.files().insert(childFolder).execute();
    }

    ParentReference newParent = new ParentReference();
    newParent.setId(childFolder.getId());
    body.setParents(Collections.singletonList(newParent));

    try {
        service.files().insert(body, mediaContent).execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        if (Config.isDebug())
            e.printStackTrace();
    }

    deleteFiles(type);
}
项目:caboclo    文件:GoogleDriveClient.java   
@Override
public void putFile(java.io.File file, String path) throws IOException {

    path = path.replace("\\", "/");

    int pos = path.lastIndexOf("/");
    if (pos > 0) {
        path = path.substring(0, pos);
    }

    String parentId = this.getId(path);

    //The path does not exists! 
    //FIXME-It is necessary to construct the path based on the last
    //valid id
    if (parentId.equals("root") && !path.equals("")
            && !path.equals("/") && !path.equals("\\")) {
        this.makedir(path);
        parentId = this.getId(path);
    }

    try {
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());

        mimeType = (mimeType == null) ? "application/octet-stream"
                : mimeType;

        File body = new File();
        body.setTitle(getTitle(file.getName()));
        body.setMimeType(mimeType);

        if (parentId != null || !parentId.equals("")) {
            body.setParents(Arrays.asList(new ParentReference()
                    .setId(parentId)));
        }

        FileContent mediaContent = new FileContent(mimeType, file);

        File f = service.files().insert(body, mediaContent).execute();

    } catch (IOException e) {
        e.printStackTrace();
    }

}
项目:gradle-backup-plugin    文件:GoogleDriveUploadTask.java   
/**
 * Uploads {@link #setArchive(File) specified file} to Google Drive.
 */
@TaskAction
public void run() {
    try {
        Preconditions.checkNotNull(this.clientId, "Google Drive client ID must not be null");
        Preconditions.checkNotNull(this.clientSecret, "Google Drive client secret must not be null");
        Preconditions.checkNotNull(this.accessToken, "Google Drive access token must not be null");
        Preconditions.checkNotNull(this.refreshToken, "Google Drive refresh token must not be null");
        Preconditions.checkNotNull(this.archive, "Archive must not be null");
        Preconditions.checkArgument(this.archive.exists(), "Archive must exist");
        Preconditions.checkArgument(this.archive.isFile(), "Archive must be a file");

        final Drive drive = constructDrive();

        final com.google.api.services.drive.model.File parent = locateParent(drive);

        final com.google.api.services.drive.model.File descriptor = new com.google.api.services.drive.model.File();
        final FileContent content = new FileContent(mimeType, archive);

        if (null != parent) {
            descriptor.setParents(Arrays.<ParentReference>asList(new ParentReference().setId(parent.getId())));
        }
        descriptor.setMimeType(content.getType());
        descriptor.setTitle(content.getFile().getName());

        final Drive.Files.Insert insert = drive.files().insert(descriptor, content);
        final MediaHttpUploader uploader = insert.getMediaHttpUploader();

        uploader.setChunkSize(1 * 1024 * 1024 /* bytes */);

        if (listenForUpload) {
            uploader.setProgressListener(new MediaHttpUploaderProgressListener() {
                @Override
                public void progressChanged(MediaHttpUploader u) throws IOException {
                    final double progress = (double) u.getNumBytesUploaded() / content.getLength();

                    System.out.printf("\r[%-50.50s] %.2f%%", Strings.repeat("#", (int) (progress * 50)), progress * 100);
                    System.out.flush();
                }
            });
        }

        insert.execute();
    } catch (Exception e) {
        throw new TaskExecutionException(this, e);
    }
}
项目:leanbean    文件:BasicUploadApk.java   
public static void main(String[] args) {
    try {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME),
                "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(
                ApplicationConfig.APPLICATION_NAME, ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes to your listing.
        Insert editRequest = edits
                .insert(ApplicationConfig.PACKAGE_NAME,
                        null /** no content */);
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final InputStream is = BasicUploadApk.class.getResourceAsStream((ApplicationConfig.APK_FILE_PATH));
        File apkTmpFile = AndroidPublisherHelper.getTempFile(is, "apk");
        URL resource = BasicUploadApk.class.getResource(ApplicationConfig.APK_FILE_PATH);
        //final String apkPath = BasicUploadApk.class
        //       .getResource(ApplicationConfig.APK_FILE_PATH)
        //        .toURI().getPath();
        final AbstractInputStreamContent apkFile =
                new FileContent(AndroidPublisherHelper.MIME_TYPE_APK, apkTmpFile);
        Upload uploadRequest = edits
                .apks()
                .upload(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        apkFile);
        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded",
                apk.getVersionCode()));

        // Assign apk to alpha track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits
                .tracks()
                .update(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        TRACK_ALPHA,
                        new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | GeneralSecurityException ex) {
        log.error("Excpetion was thrown while uploading apk to alpha track", ex);
    }
}
项目:playstorepublisher    文件:BasicUploadApk.java   
public static void main(String[] args) {
    try {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME), "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(ApplicationConfig.APPLICATION_NAME, ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes to your listing.
        Insert editRequest = edits.insert(ApplicationConfig.PACKAGE_NAME, null /** no content */);
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final String apkPath = BasicUploadApk.class
                .getResource(ApplicationConfig.APK_FILE_PATH)
                .toURI().getPath();

        final AbstractInputStreamContent apkFile = new FileContent(AndroidPublisherHelper.MIME_TYPE_APK, new File(apkPath));
        Upload uploadRequest = edits
                .apks()
                .upload(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        apkFile);

        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded",
                apk.getVersionCode()));

        // Assign apk to alpha track.
        List<Integer> apkVersionCodes = new ArrayList<Integer>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits
                .tracks()
                .update(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        TRACK_ALPHA,
                        new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | URISyntaxException | GeneralSecurityException ex) {
        log.error("Excpetion was thrown while uploading apk to alpha track", ex);
    }
}
项目:android-play-publisher-api    文件:BasicUploadApk.java   
public static void main(String[] args) {
    try {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME),
                "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(
                ApplicationConfig.APPLICATION_NAME, ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes to your listing.
        Insert editRequest = edits
                .insert(ApplicationConfig.PACKAGE_NAME,
                        null /** no content */);
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final String apkPath = BasicUploadApk.class
                .getResource(ApplicationConfig.APK_FILE_PATH)
                .toURI().getPath();
        final AbstractInputStreamContent apkFile =
                new FileContent(AndroidPublisherHelper.MIME_TYPE_APK, new File(apkPath));
        Upload uploadRequest = edits
                .apks()
                .upload(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        apkFile);
        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded",
                apk.getVersionCode()));

        // Assign apk to alpha track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits
                .tracks()
                .update(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        TRACK_ALPHA,
                        new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | URISyntaxException | GeneralSecurityException ex) {
        log.error("Excpetion was thrown while uploading apk to alpha track", ex);
    }
}
项目:android-play-publisher-api    文件:UploadApkWithListing.java   
public static void main(String[] args) {
    try {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME),
                "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(
                ApplicationConfig.APPLICATION_NAME, ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes.
        Insert editRequest = edits
                .insert(ApplicationConfig.PACKAGE_NAME,
                        null /** no content */);
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final String apkPath = UploadApkWithListing.class
                .getResource(ApplicationConfig.APK_FILE_PATH)
                .toURI().getPath();
        final AbstractInputStreamContent apkFile =
                new FileContent(AndroidPublisherHelper.MIME_TYPE_APK, new File(apkPath));
        Upload uploadRequest = edits
                .apks()
                .upload(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        apkFile);
        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded",
                apk.getVersionCode()));

        // Assign apk to beta track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits
                .tracks()
                .update(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        TRACK_BETA,
                        new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Update recent changes field in apk listing.
        final ApkListing newApkListing = new ApkListing();
        newApkListing.setRecentChanges(APK_LISTING_RECENT_CHANGES_TEXT);

        Apklistings.Update
        updateRecentChangesRequest = edits
                .apklistings()
                .update(ApplicationConfig.PACKAGE_NAME,
                        editId,
                        apk.getVersionCode(),
                        Locale.US.toString(),
                        newApkListing);
        updateRecentChangesRequest.execute();
        log.info("Recent changes has been updated.");

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | URISyntaxException | GeneralSecurityException ex) {
        log.error(
                "Exception was thrown while uploading apk and updating recent changes",
                ex);
    }
}