Java Code Examples for retrofit.mime.TypedFile

The following examples show how to use retrofit.mime.TypedFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: talk-android   Source File: SetupUserFragment.java    License: MIT License 6 votes vote down vote up
private void uploadAvatar(final String localPath) {
    File file = new File(localPath);
    TalkClient.getInstance().getUploadApi()
            .uploadFile(file.getName(), "image/*", file.length(), new TypedFile("image/*", file))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<FileUploadResponseData>() {
                @Override
                public void call(FileUploadResponseData fileUploadResponseData) {
                    MainApp.IMAGE_LOADER.displayImage("file://" + localPath, ivAvatar);
                    user.setAvatarUrl(fileUploadResponseData.getThumbnailUrl());
                    updateUserInfo();
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {

                }
            });
}
 
Example 2
Source Project: mobilecloud-15   Source File: AutoGradingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Rubric(
		value="Attempting to submit video data for a non-existant video generates a 404",
		goal="The goal of this evaluation is to ensure that your Spring controller(s) "
				+ "produce a 404 error if a client attempts to submit video data for"
				+ " a video that does not exist.",
		points=10.0,
		reference="This test is derived from the material in these videos: "
		        + "https://class.coursera.org/mobilecloud-001/lecture/207 "
				+ "https://class.coursera.org/mobilecloud-001/lecture/69 "
				+ "https://class.coursera.org/mobilecloud-001/lecture/65"
		)
@Test
public void testAddNonExistantVideosData() throws Exception {
	long nonExistantId = getInvalidVideoId();
	try{
		videoSvc.setVideoData(nonExistantId, new TypedFile(video.getContentType(), testVideoData));
		fail("The client should receive a 404 error code and throw an exception if an invalid"
				+ " video ID is provided in setVideoData()");
	}catch(RetrofitError e){
		assertEquals(404, e.getResponse().getStatus());
	}
}
 
Example 3
Source Project: talk-android   Source File: ChatPresenter.java    License: MIT License 5 votes vote down vote up
public Subscription uploadFile(final String mimeType, String path, final String tempMsgId, final int duration, final int videoWidth, final int videoHeight) {
    File originFile = new File(path);
    if (originFile.length() <= 0) {
        return null;
    }
    if ("audio/amr".equals(mimeType) && originFile.length() < 100) {
        callback.onUploadFileInvalid(tempMsgId);
        return null;
    }
    TypedFile file = new TypedFile(mimeType, originFile);
    return uploadApi.uploadFile(originFile.getName(), mimeType, originFile.length(), file)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<FileUploadResponseData>() {
                @Override
                public void call(FileUploadResponseData fileUploadResponseData) {
                    if (mimeType.equals("audio/amr")) {
                        fileUploadResponseData.setSpeech(true);
                        fileUploadResponseData.setDuration(duration);
                    } else if (mimeType.equals("video")) {
                        fileUploadResponseData.setWidth(videoWidth);
                        fileUploadResponseData.setHeight(videoHeight);
                        fileUploadResponseData.setDuration(duration);
                    }
                    callback.onUploadFileSuccess(fileUploadResponseData, tempMsgId);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    throwable.printStackTrace();
                    callback.onUploadFileFailed(tempMsgId);
                }
            });
}
 
Example 4
@Multipart
@Headers({"Content-Type: multipart/form-data",
        "Accept: application/json",
        "Accept-Encoding: gzip, deflate"})
@POST("/api/{userID}/violation/create")
VideoAnswer uploadImage(@Part("photo") TypedFile photo,
                        @EncodedPath("userID") String userID,
                        @Part("latitude") double latitude,
                        @Part("longitude") double longitude);
 
Example 5
Source Project: droidddle   Source File: ShotFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void uploadAttachment() {
    if (!Utils.hasInternet(getActivity())) {
        Toast.makeText(getActivity(), R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    Context mContext = getActivity();
    mDialog = UiUtils.showProgressDialog(mContext, getString(R.string.creating_attachment));
    TypedFile file = new TypedFile(FileUtils.getMimeType(mFile), mFile);
    Observable<Response> observable = ApiFactory.getService(mContext).createShotAttachments(mShot.id, file);
    observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SucessCallback<Response>(mContext, R.string.create_attachment_success, mDialog), new ErrorCallback(mContext, mDialog));
}
 
Example 6
Source Project: droidddle   Source File: CreateShotFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void createShot() {
    if (mImageFile == null || !mImageFile.exists()) {
        UiUtils.showToast(getActivity(), R.string.shot_image_file_missing);
        return;
    }
    if (mMimeType == null) {
        mMimeType = FileUtils.getMimeType(mImageFile);
    }
    if (!Utils.hasInternet(getActivity())) {
        Toast.makeText(getActivity(), R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    mDialog = UiUtils.showProgressDialog(getActivity(), getString(R.string.creating));
    String text = mNameView.getText().toString();
    String des = mDescriptionView.getText().toString();
    String tag = mTagsView.getText().toString().trim();
    //TODO set image/png GIF, JPG by file ext name
    TypedFile image = new TypedFile(mMimeType, mImageFile);
    TypedString title = new TypedString(text);
    TypedString description = new TypedString(des);
    TypedString tags = new TypedString(tag);
    Observable<Response> observable = ApiFactory.getService(getActivity()).createShot(image, title, description, tags);
    observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe((response) -> {
        bucketCreated(response);
    }, new ErrorCallback(getActivity()));

}
 
Example 7
Source Project: foam   Source File: HockeyApp.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * HockeyApp requires data to be in files uploaded via multipart POST request.
 * Here we create a file containing the log data.
 * @param appId HockeyApp application ID
 * @param storedException Data to place in a log file.
 * @param deleteStoredExceptionCallback Retrofit callback that will delete the exception file
 *                                      after it is uploaded.
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
void createLogEvent(String appId, StoredException storedException,
                            final Callback<Object> deleteStoredExceptionCallback) {
    final File logFile = writeHockeyAppCrashLog(storedException.stackTrace);
    if(logFile != null && logFile.exists()) {
        final TypedFile log = new TypedFile("text/plain", logFile);
        createService().createEvent(
            appId,
            log,
            createLogEventCallback(deleteStoredExceptionCallback, logFile)
        );
    }
}
 
Example 8
Source Project: foam   Source File: HockeyAppTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCreateLogEvent() {
    final Callback mockLogEventCallback = mock(Callback.class);
    final File tempFile = createTempFile();

    HockeyApp hockeyApp = new HockeyApp(null){
        @Override
        File writeHockeyAppCrashLog(String stackTrace) {
            return tempFile;
        }

        @Override
        Callback<Response> createLogEventCallback(Callback<Object> deleteStoredExceptionCallback, File logFile) {
            return mockLogEventCallback;
        }
    };

    StoredException storedException = new StoredException(ServiceType.HOCKEYAPP, "test message", "test threadName", "test\nstack\ntrace");

    HockeyApp.HockeyAppService mockService = mock(HockeyApp.HockeyAppService.class);
    hockeyApp.hockeyAppService = mockService;
    hockeyApp.createLogEvent("UnitTestingAppId", storedException, null);

    ArgumentCaptor<TypedFile> typedFileArgumentCaptor = ArgumentCaptor.forClass(TypedFile.class);
    verify(mockService).createEvent(eq("UnitTestingAppId"), typedFileArgumentCaptor.capture(), eq(mockLogEventCallback));
    assertEquals(tempFile, typedFileArgumentCaptor.getValue().file());
    assertTrue("Failed to clean up temp file [" + tempFile.getAbsolutePath() + "].", tempFile.delete());
}
 
Example 9
Source Project: mobilecloud-15   Source File: AutoGradingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Rubric(
		value="Mpeg video data can be submitted for a video",
		goal="The goal of this evaluation is to ensure that your Spring controller(s) "
				+ "allow mpeg video data to be submitted for a video. The test also"
				+ " checks that the controller(s) can serve that video data to the"
				+ " client.",
		points=20.0,
		reference="This test is derived from the material in these videos: "
				+ "https://class.coursera.org/mobilecloud-001/lecture/69 "
				+ "https://class.coursera.org/mobilecloud-001/lecture/65 "
				+ "https://class.coursera.org/mobilecloud-001/lecture/71 "
				+ "https://class.coursera.org/mobilecloud-001/lecture/207"
		)
@Test
public void testAddVideoData() throws Exception {
	Video received = videoSvc.addVideo(video);
	VideoStatus status = videoSvc.setVideoData(received.getId(),
			new TypedFile(received.getContentType(), testVideoData));
	assertEquals(VideoState.READY, status.getState());
	
	Response response = videoSvc.getData(received.getId());
	assertEquals(200, response.getStatus());
	
	InputStream videoData = response.getBody().in();
	byte[] originalFile = IOUtils.toByteArray(new FileInputStream(testVideoData));
	byte[] retrievedFile = IOUtils.toByteArray(videoData);
	assertTrue(Arrays.equals(originalFile, retrievedFile));
}
 
Example 10
Source Project: talk-android   Source File: UploadApi.java    License: MIT License 4 votes vote down vote up
@Multipart
@POST("/upload")
Observable<FileUploadResponseData> uploadFile(@Part("name") String name, @Part("type") String mimeType, @Part("size") long fileSize, @Part("file") TypedFile file);
 
Example 11
Source Project: droidddle   Source File: ApiService.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST("/shots/{id}/attachments")
Observable<Response> createShotAttachments(@Path("id") long id, @Part("file") TypedFile file);
 
Example 12
Source Project: droidddle   Source File: ApiService.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST("/shots")
Observable<Response> createShot(@Part("image") TypedFile image, @Part("title") TypedString title, @Part("description") TypedString description);
 
Example 13
Source Project: droidddle   Source File: ApiService.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST("/shots")
Observable<Response> createShot(@Part("image") TypedFile image, @Part("title") TypedString title, @Part("description") TypedString description, @Part("tags") TypedString tags);
 
Example 14
Source Project: foam   Source File: HockeyApp.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Multipart
@POST("/api/2/apps/{APP_ID}/crashes/upload")
void createEvent(@Path("APP_ID") String appId,
                 @Part("log") TypedFile log,
                 Callback<Response> callback
);
 
Example 15
Source Project: mobilecloud-15   Source File: VideoDataMediator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Uploads the Video having the given Id.  This Id is the Id of
 * Video in Android Video Content Provider.
 * 
 * @param videoId
 *            Id of the Video to be uploaded.
 *
 * @return A String indicating the status of the video upload operation.
 */
public String uploadVideo(Context context,
                          Uri videoUri) {
    // Get the path of video file from videoUri.
    String filePath =
        VideoMediaStoreUtils.getPath(context,
                                     videoUri);

    // Get the Video from Android Video Content Provider having
    // the given filePath.
    Video androidVideo =
        VideoMediaStoreUtils.getVideo(context,
                                      filePath);

    // Check if any such Video exists in Android Video Content
    // Provider.
    if (androidVideo != null) {
        // Prepare to Upload the Video data.

        // Create an instance of the file to upload.
        File videoFile = new File(filePath);

        // Check if the file size is less than the size of the
        // video that can be uploaded to the server.
        if (videoFile.length() < Constants.MAX_SIZE_MEGA_BYTE) {

            try {
                // Add the metadata of the Video to the Video Service
                // and get the resulting Video that contains
                // additional meta-data (e.g., Id and ContentType)
                // generated by the Video Service.
                Video receivedVideo =
                    mVideoServiceProxy.addVideo(androidVideo);

                // Check if the Server returns any Video metadata.
                if (receivedVideo != null) {

                    // Finally, upload the Video data to the server
                    // and get the status of the uploaded video data.
                    VideoStatus status =
                        mVideoServiceProxy.setVideoData
                            (receivedVideo.getId(),
                             new TypedFile(receivedVideo.getContentType(),
                                           videoFile));

                    // Check if the Status of the Video or not.
                    if (status.getState() == VideoState.READY) {
                        // Video successfully uploaded.
                        return STATUS_UPLOAD_SUCCESSFUL;
                    }
                }
            } catch (Exception e) {
                // Error occured while uploading the video.
                return STATUS_UPLOAD_ERROR;
            }
        } else
            // Video can't be uploaded due to large video size.
            return STATUS_UPLOAD_ERROR_FILE_TOO_LARGE;
    }
    
    // Error occured while uploading the video.
    return STATUS_UPLOAD_ERROR;
}
 
Example 16
Source Project: mobilecloud-15   Source File: VideoSvcApi.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST(VIDEO_DATA_PATH)
public VideoStatus setVideoData(@Path(ID_PARAMETER) long id, @Part(DATA_PARAMETER) TypedFile videoData);
 
Example 17
Source Project: mobilecloud-15   Source File: VideoDataMediator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Uploads the Video having the given Id.  This Id is the Id of
 * Video in Android Video Content Provider.
 * 
 * @param videoId
 *            Id of the Video to be uploaded.
 *
 * @return A String indicating the status of the video upload operation.
 */
public String uploadVideo(Context context,
                          Uri videoUri) {
    // Get the path of video file from videoUri.
    String filePath =
        VideoMediaStoreUtils.getPath(context,
                                     videoUri);

    // Get the Video from Android Video Content Provider having
    // the given filePath.
    Video androidVideo =
        VideoMediaStoreUtils.getVideo(context,
                                      filePath);

    // Check if any such Video exists in Android Video Content
    // Provider.
    if (androidVideo != null) {
        // Prepare to Upload the Video data.

        // Create an instance of the file to upload.
        File videoFile = new File(filePath);

        // Check if the file size is less than the size of the
        // video that can be uploaded to the server.
        if (videoFile.length() < Constants.MAX_SIZE_MEGA_BYTE) {

            try {
                // Add the metadata of the Video to the Video Service
                // and get the resulting Video that contains
                // additional meta-data (e.g., Id and ContentType)
                // generated by the Video Service.
                Video receivedVideo =
                    mVideoServiceProxy.addVideo(androidVideo);

                // Check if the Server returns any Video metadata.
                if (receivedVideo != null) {

                    // Finally, upload the Video data to the server
                    // and get the status of the uploaded video data.
                    VideoStatus status =
                        mVideoServiceProxy.setVideoData
                            (receivedVideo.getId(),
                             new TypedFile("video/mpeg", videoFile));

                    // Check if the Status of the Video or not.
                    if (status.getState() == VideoState.READY) {
                        // Video successfully uploaded.
                        return STATUS_UPLOAD_SUCCESSFUL;
                    }
                }
            } catch (Exception e) {
                // Error occured while uploading the video.
                return STATUS_UPLOAD_ERROR;
            }
        } else
            // Video can't be uploaded due to large video size.
            return STATUS_UPLOAD_ERROR_FILE_TOO_LARGE;
    }
    
    // Error occured while uploading the video.
    return STATUS_UPLOAD_ERROR;
}
 
Example 18
Source Project: spark-sdk-android   Source File: ParticleDevice.java    License: Apache License 2.0 4 votes vote down vote up
@WorkerThread
public void flashBinaryFile(final File file) throws ParticleCloudException {
    performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId,
            new TypedFile("application/octet-stream", file)));
}
 
Example 19
Source Project: spark-sdk-android   Source File: ParticleDevice.java    License: Apache License 2.0 4 votes vote down vote up
@WorkerThread
public void flashCodeFile(final File file) throws ParticleCloudException {
    performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId,
            new TypedFile("multipart/form-data", file)));
}
 
Example 20
Source Project: mobilecloud-15   Source File: VideoServiceProxy.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sends a POST request to Upload the Video data to the Video Web
 * service using a two-way Retrofit RPC call.  @Multipart is used
 * to transfer multiple content (i.e. several files in case of a
 * file upload to a server) within one request entity.  When doing
 * so, a REST client can save the overhead of sending a sequence
 * of single requests to the server, thereby reducing network
 * latency.
 * 
 * @param id
 * @param videoData
 * @return videoStatus indicating status of the uploaded video.
 */
@Multipart
@POST(VIDEO_DATA_PATH)
public VideoStatus setVideoData(@Path(ID_PARAMETER) long id,
                                @Part(DATA_PARAMETER) TypedFile videoData);
 
Example 21
Source Project: mobilecloud-15   Source File: VideoSvcApi.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * This endpoint allows clients to set the mpeg video data for previously
 * added Video objects by sending multipart POST requests to the server.
 * The URL that the POST requests should be sent to includes the ID of the
 * Video that the data should be associated with (e.g., replace {id} in
 * the url /video/{id}/data with a valid ID of a video, such as /video/1/data
 * -- assuming that "1" is a valid ID of a video). 
 * 
 * @return
 */
@Multipart
@POST(VIDEO_DATA_PATH)
public VideoStatus setVideoData(@Path(ID_PARAMETER) long id, @Part(DATA_PARAMETER) TypedFile videoData);