Example usage for com.squareup.okhttp MediaType parse

List of usage examples for com.squareup.okhttp MediaType parse

Introduction

In this page you can find the example usage for com.squareup.okhttp MediaType parse.

Prototype

public static MediaType parse(String string) 

Source Link

Document

Returns a media type for string , or null if string is not a well-formed media type.

Usage

From source file:com.liferay.mobile.android.http.file.InputStreamBody.java

License:Open Source License

@Override
public MediaType contentType() {
    return MediaType.parse(data.getMimeType());
}

From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java

License:Open Source License

public static void signIn(Config config, CookieCallback callback) {
    try {//from   www.j  ava 2s.c  om
        Authentication auth = config.auth();

        if (!(auth instanceof BasicAuthentication)) {
            throw new Exception(
                    "Can't sign in if authentication implementation is not " + "BasicAuthentication");
        }

        OkHttpClient client = new OkHttpClient();

        CookieManager cookieManager = new CookieManager();

        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

        client.setCookieHandler(cookieManager);
        client.setFollowRedirects(true);

        Builder builder = new Builder();

        MediaType contentType = MediaType.parse("application/x-www-form-urlencoded");

        builder.post(RequestBody.create(contentType, getBody((BasicAuthentication) auth)));

        builder.addHeader("Cookie", "COOKIE_SUPPORT=true;");
        builder.url(getLoginURL(config.server()));

        Call call = client.newCall(builder.build());

        call.enqueue(getCallback(callback, cookieManager));
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:com.magnet.max.android.Attachment.java

License:Apache License

/**
 * Upload the attachment to Max Server//from   w  w  w  .  j  a va2s  . c  om
 * @param listener
 */
public void upload(final UploadListener listener) {
    if (StringUtil.isNotEmpty(mAttachmentId)) {
        // Already uploaded
        Log.d(TAG, "Already uploaded");
        if (null != listener) {
            listener.onComplete(this);
        }
        return;
    }

    if (mStatus == Status.INIT || mStatus == Status.ERROR) {
        if (null != listener) {
            listener.onStart(this);
        }

        final AtomicReference<Long> startTime = new AtomicReference<>();
        Callback<Map<String, String>> uploadCallback = new Callback<Map<String, String>>() {
            @Override
            public void onResponse(Response<Map<String, String>> response) {
                if (response.isSuccess()) {
                    Map<String, String> result = response.body();
                    if (null != result && !result.isEmpty()) {
                        mAttachmentId = result.values().iterator().next();
                        mStatus = Status.COMPLETE;
                        Log.d(TAG, "It took " + (System.currentTimeMillis() - startTime.get()) / 1000
                                + " seconds to upload attachment " + mAttachmentId);
                        if (null != listener) {
                            listener.onComplete(Attachment.this);
                        }
                    } else {
                        handleError(new Exception("Can't get attachmentId from response"));
                    }
                } else {
                    handleError(new Exception(response.message()));
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                handleError(throwable);
            }

            private void handleError(Throwable throwable) {
                mStatus = Status.ERROR;
                Log.d(TAG, "Failed to upload attachment " + mName, throwable);
                if (null != listener) {
                    listener.onError(Attachment.this, throwable);
                }
            }
        };

        RequestBody requestBody = null;
        if (mSourceType == ContentSourceType.FILE) {
            requestBody = RequestBody.create(MediaType.parse(getMimeType()), (File) mContent);
        } else {
            requestBody = RequestBody.create(MediaType.parse(getMimeType()), getAsBytes());
        }
        startTime.set(System.currentTimeMillis());

        String partName = StringUtil.isNotEmpty(mName) ? mName : "attachment";
        getAttachmentService()
                .uploadMultiple(mMetaData,
                        new MultipartBuilder().type(MultipartBuilder.FORM)
                                .addFormDataPart(partName, partName, requestBody).build(),
                        uploadCallback)
                .executeInBackground();

        mStatus = Status.TRANSFERING;
    } else if (mStatus == Status.TRANSFERING) {
        if (null != listener) {
            listener.onError(this, new IllegalStateException("Attachment is being uploading"));
        }
    }
}

From source file:com.magnet.max.android.logging.remote.LogFileManager.java

License:Apache License

public static synchronized void uploadFile(final File file, final ApiCallback<Boolean> callback) {
    if (isCurrentFile(file.getName())) {
        rotateFile();//from  w  w w .j av  a  2s. c o  m
    }

    RequestBody fileBody = RequestBody.create(MediaType.parse("text/plain"), file);
    MagnetCall<Void> call = getLogCollectorService().addEventsFromFile(fileBody, new Callback<Void>() {
        @Override
        public void onResponse(retrofit.Response<Void> response) {
            if (response.isSuccess()) {
                Log.d(TAG, "Success uploading file..");
                file.delete();
                if (null != callback) {
                    callback.success(true);
                }
            } else {
                if (null != callback) {
                    Log.d(TAG, "Uploading file failed due to : " + response.message());
                    callback.failure(new ApiError(response.message(), response.code()));
                }
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            Log.e(TAG, "Error uploading file.." + throwable.getMessage());
            if (null != callback) {
                callback.failure(new ApiError(throwable));
            }
        }
    });
    call.executeInBackground();
}

From source file:com.magnet.max.android.rest.qos.internal.CachedRequest.java

License:Apache License

public Request toRequest() {
    Headers responseHeaders = Headers.of(headers);
    String contentType = responseHeaders.get("Content-Type");
    return new Request.Builder().url(url).method(method, RequestBody.create(MediaType.parse(contentType), body))
            .headers(responseHeaders).build();
}

From source file:com.magnet.max.android.rest.qos.internal.CachedResponse.java

License:Apache License

public Response toResponse(Request request) {
    Headers responseHeaders = Headers.of(headers);
    String contentType = responseHeaders.get("Content-Type");
    Response cachedResponse = new Response.Builder().code(code).protocol(getProtocolEnum()).message(message)
            .headers(responseHeaders).request(request).build();
    return cachedResponse.newBuilder().body(ResponseBody.create(MediaType.parse(contentType), body))
            .cacheResponse(cachedResponse).build();
}

From source file:com.magnet.max.android.tests.EventsCollectionTestLog.java

License:Apache License

private void testUploadLogFile(LogEventsCollectionService myService) {
    EventLog log = new EventLog.LogBuilder().name("logtest").category("test").message("test").build();
    Gson gson = new Gson();
    final RequestBody fileBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(log));
    final CountDownLatch signal = new CountDownLatch(1);
    myService.addEventsFromFile(fileBody, new retrofit.Callback<Void>() {

        @Override/*from   ww  w.ja  v  a2 s .  c  om*/
        public void onResponse(retrofit.Response<Void> response) {
            signal.countDown();
        }

        @Override
        public void onFailure(Throwable throwable) {
            fail(throwable.getMessage());
            signal.countDown();
        }
    }).executeInBackground();

    try {
        signal.await(10, TimeUnit.SECONDS);
    } catch (Throwable e) {
        Log.e(TAG, "addEventsFromFile timeout");
        fail("addEventsFromFile timeout");
    }

    assertEquals(0, signal.getCount());
}

From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java

License:Apache License

@SmallTest
public void testDateTypeUnmarshalling() {
    Converter magnetGsonConverter = magnetGsonConverterFactory.get(Date.class);
    String str = "2015-01-01T01:01:00.000Z";
    try {//from  w w w.  j  av a2s .  co  m
        Date date = (Date) magnetGsonConverter
                .fromBody(ResponseBody.create(MediaType.parse("application/json"), str));
        assertNotNull(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        assertEquals(2015, cal.get(Calendar.YEAR));
        assertEquals(0, cal.get(Calendar.MONTH));
        assertEquals(1, cal.get(Calendar.DAY_OF_MONTH));
        assertEquals(1, cal.get(Calendar.HOUR_OF_DAY));
        assertEquals(1, cal.get(Calendar.MINUTE));
        assertEquals(0, cal.get(Calendar.SECOND));
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java

License:Apache License

@SmallTest
public void testStringTypeUnmarshalling() {
    Converter magnetGsonConverter = magnetGsonConverterFactory.get(String.class);
    String str = "hello world";
    try {/* ww  w . j ava2 s.  co  m*/
        String value = (String) magnetGsonConverter
                .fromBody(ResponseBody.create(MediaType.parse("application/json"), str));
        assertEquals(str, value);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java

License:Apache License

@SmallTest
public void testEnumTypeUnmarshalling() {
    Converter magnetGsonConverter = magnetGsonConverterFactory.get(TestEnumType.class);
    try {/*from ww  w. j  av  a  2 s . c o  m*/
        TestEnumType enumType = (TestEnumType) magnetGsonConverter
                .fromBody(ResponseBody.create(MediaType.parse("application/json"), "ENUM1"));
        assertEquals(TestEnumType.ENUM1, enumType);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}