Example usage for org.apache.http.util Args check

List of usage examples for org.apache.http.util Args check

Introduction

In this page you can find the example usage for org.apache.http.util Args check.

Prototype

public static void check(boolean z, String str) 

Source Link

Usage

From source file:net.dv8tion.jda.core.utils.IOUtil.java

/**
 * Used as an alternate to Java's nio Files.readAllBytes.
 * <p>/*from  w ww  . ja va 2 s . c om*/
 * This customized version for File is provide (instead of just using {@link #readFully(java.io.InputStream)} with a FileInputStream)
 * because
 * with a File we can determine the total size of the array and do not need to have a buffer. This results
 * in a memory footprint that is half the size of {@link #readFully(java.io.InputStream)}
 * <p>
 * Code provided from <a href="http://stackoverflow.com/a/6276139">http://stackoverflow.com/a/6276139</a>
 *
 * @param file
 *          The file from which we should retrieve the bytes from
 * @return
 *      A byte[] containing all of the file's data
 * @throws IOException
 *      Thrown if there is a problem while reading the file.
 */
public static byte[] readFully(File file) throws IOException {
    Args.notNull(file, "File");
    Args.check(file.exists(), "Provided file does not exist!");

    try (InputStream is = new FileInputStream(file)) {
        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            throw new IOException("Cannot read the file into memory completely due to it being too large!");
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}

From source file:net.dv8tion.jda.core.entities.Icon.java

/**
 * Creates an {@link Icon Icon} with the specified {@link java.io.File File}.<br>
 * We here read the specified File and forward the retrieved byte data to {@link #from(byte[])}.
 *
 * @param file//  w  w  w .  java  2 s  . c  o  m
 *      An existing, not-null file.
 * @return
 *      An Icon instance representing the specified File
 * @throws IllegalArgumentException
 *      if the provided file is either null or does not exist
 * @throws IOException
 *      if there is a problem while reading the file.
 * @see net.dv8tion.jda.core.utils.IOUtil#readFully(File)
 */
public static Icon from(File file) throws IOException {
    Args.notNull(file, "Provided File");
    Args.check(file.exists(), "Provided file does not exist!");

    return from(IOUtil.readFully(file));
}

From source file:org.zalando.stups.oauth2.httpcomponents.AccessTokensRequestInterceptor.java

public AccessTokensRequestInterceptor(final String tokenId, final AccessTokens accessTokens) {
    Args.check(tokenId != null, "'tokenId' should never be null");
    Args.check(accessTokens != null, "'accessTokens' should never be null");
    Args.check(!tokenId.trim().isEmpty(), "'tokenId' should never be empty");
    this.tokenId = tokenId;
    this.accessTokens = accessTokens;
}

From source file:com.wudaosoft.net.httpclient.FileResponseHandler.java

public FileResponseHandler(final String dir) {
    this.dir = new File(Args.notBlank(dir, "dir"));
    Args.check(this.dir.isDirectory(), "dir must be a directory");
}

From source file:com.wudaosoft.net.httpclient.FileResponseHandler.java

@Override
public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();

    if (status != 200) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }//w  w  w. j  a v a 2 s  .c o  m

    HttpEntity entity = response.getEntity();

    if (entity == null || !entity.isStreaming()) {
        throw new ClientProtocolException("Response contains no content");
    }

    File tempFile = null;

    if (this.file != null) {
        tempFile = this.file;
    } else if (this.dir != null) {
        Header contentDisposition = response.getLastHeader("Content-disposition");
        String filename = contentDisposition.getValue().split(";")[1].split("=")[1].replace("\"", "");
        tempFile = new File(this.dir, filename);
    }

    Args.notNull(tempFile, "file");
    Args.check(tempFile.canWrite(), "file must be writeable");

    InputStream inputStream = entity.getContent();
    FileOutputStream outputStream = new FileOutputStream(tempFile);

    try {

        byte[] buff = new byte[4096];
        int size = -1;
        while ((size = inputStream.read(buff)) != -1) {

            outputStream.write(buff, 0, size);
        }

        outputStream.flush();

        return tempFile;
    } finally {
        try {
            outputStream.close();
        } catch (IOException e) {
        }
    }

}

From source file:me.ixfan.wechatkit.user.UserManager.java

/**
 * ?? UnionId ?????UnionId ?//from w  w w . j a  v  a 2  s.com
 *
 * @param openId  OpenId
 * @param lang zh_CN zh_TW ?en  zh_CN
 * @return {@link WeChatFollower}
 * @throws WeChatApiErrorException API??
 */
public WeChatFollower getUserInfo(final String openId, String lang) throws WeChatApiErrorException {
    Args.notBlank(openId, "OpenId");
    if (TextUtils.isBlank(lang)) {
        lang = "zh_CN";
    }
    Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"),
            "'lang' ? zh_CN, zh_TW  en.");

    final String url = WeChatConstants.WECHAT_GET_USER_INFO
            .replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken()).replace("${OPENID}", openId)
            .replace("${LANG}", lang);
    JsonObject jsonResponse;
    try {
        jsonResponse = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (jsonResponse.has("subscribe")) {
        return WeChatFollower.fromJson(jsonResponse);
    } else {
        throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                jsonResponse.get("errmsg").getAsString());
    }
}

From source file:cn.aage.robot.http.entity.ContentType.java

/**
 * Creates a new instance of {@link ContentType}.
 *
 * @param mimeType MIME type. It may not be <code>null</code> or empty. It may not contain
 *                 characters <">, <;>, <,> reserved by the HTTP specification.
 * @param charset  charset./* ww w . j  a v  a  2s . co  m*/
 * @return content type
 */
public static ContentType create(final String mimeType, final Charset charset) {
    final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ENGLISH);
    Args.check(valid(type), "MIME type may not contain reserved characters");
    return new ContentType(type, charset);
}

From source file:com.digitalpebble.stormcrawler.protocol.httpclient.HttpProtocol.java

private static final byte[] toByteArray(final HttpEntity entity, int maxContent, MutableBoolean trimmed)
        throws IOException {

    if (entity == null)
        return new byte[] {};

    final InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }/*from  w ww  .  j  ava  2  s .co  m*/
    try {
        Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
                "HTTP entity too large to be buffered in memory");
        int i = (int) entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
        final byte[] tmp = new byte[4096];
        int l;
        int total = 0;
        while ((l = instream.read(tmp)) != -1) {
            // check whether we need to trim
            if (maxContent != -1 && total + l > maxContent) {
                buffer.append(tmp, 0, maxContent - total);
                trimmed.setValue(true);
                break;
            }
            buffer.append(tmp, 0, l);
            total += l;
        }
        return buffer.toByteArray();
    } finally {
        instream.close();
    }
}

From source file:me.ixfan.wechatkit.user.UserManager.java

/**
 * ?????100?//from w  w  w  .  ja  v a2s  . co  m
 * @param openIds  OpenId 
 * @param lang zh_CN zh_TW ?en  zh-CN
 * @return {@link WeChatFollower}s
 * @throws WeChatApiErrorException API??
 */
public List<WeChatFollower> batchGetUserInfo(final List<String> openIds, String lang)
        throws WeChatApiErrorException {
    Args.notEmpty(openIds, "OpenIds");
    if (TextUtils.isBlank(lang)) {
        lang = "zh_CN";
    }
    Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"),
            "'lang' ? zh_CN, zh_TW  en.");

    final String finalLang = lang;
    JsonObject jsonResponse;
    try {
        final List<Map<String, String>> data = new ArrayList<>();
        openIds.forEach(openid -> {
            Map<String, String> map = new HashMap<>();
            map.put("openid", openid);
            map.put("lang", finalLang);
            data.add(map);
        });
        final Map<String, List<Map<String, String>>> jsonMap = new HashMap<>();
        jsonMap.put("user_list", data);
        Gson gson = new Gson();
        jsonResponse = HttpClientUtil
                .sendPostRequestWithJsonBody(WeChatConstants.WECHAT_POST_BATCH_GET_USER_INFO
                        .replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken()), gson.toJson(jsonMap));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (jsonResponse.has("user_info_list")) {
        return WeChatFollower.batchFromJson(jsonResponse.get("user_info_list").getAsJsonArray());
    } else {
        throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                jsonResponse.get("errmsg").getAsString());
    }
}

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * //  www . j  a v  a 2 s  . c  o  m
 * @param workerBuilder
 * @param responseHandler
 * @return
 * @throws Exception
 */
public <T> T doRequest(WorkerBuilder workerBuilder, ResponseHandler<T> responseHandler) throws Exception {

    String method = workerBuilder.getMethod();
    String url = workerBuilder.getUrl();

    Args.notNull(workerBuilder, "WorkerBuilder");
    Args.notEmpty(method, "WorkerBuilder.getMethod()");
    Args.notEmpty(url, "WorkerBuilder.getUrl()");
    Args.notNull(responseHandler, "responseHandler");

    //      if(!workerBuilder.isAnyHost()) {
    if (!isFullUrl(url)) {
        //         notFullUrl(url);
        Args.notEmpty(hostConfig.getHostUrl(), "HostConfig.getHostUrl()");
        url = hostConfig.getHostUrl() + url;
    }

    Charset charset = hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset();
    String stringBody = workerBuilder.getStringBody();
    File fileBody = workerBuilder.getFileBody();
    InputStream streamBody = workerBuilder.getStreamBody();
    Map<String, String> params = workerBuilder.getParameters();

    String contentType = null;

    if (responseHandler instanceof JsonResponseHandler) {
        contentType = MediaType.APPLICATION_JSON_VALUE;
    } else if (responseHandler instanceof SAXSourceResponseHandler
            || responseHandler instanceof XmlResponseHandler) {
        contentType = MediaType.APPLICATION_XML_VALUE;
    } else if (responseHandler instanceof FileResponseHandler || responseHandler instanceof ImageResponseHandler
            || responseHandler instanceof OutputStreamResponseHandler) {
        contentType = MediaType.ALL_VALUE;
    } else if (responseHandler instanceof NoResultResponseHandler) {
        contentType = ((NoResultResponseHandler) responseHandler).getContentType().getMimeType();
    } else {
        contentType = MediaType.TEXT_PLAIN_VALUE;
    }

    RequestBuilder requestBuilder = RequestBuilder.create(method).setCharset(charset).setUri(url);

    if (stringBody != null) {

        StringEntity reqEntity = new StringEntity(stringBody, charset);
        reqEntity.setContentType(contentType + ";charset=" + charset.name());
        requestBuilder.setEntity(reqEntity);

    } else if (fileBody != null || streamBody != null) {

        String filename = workerBuilder.getFilename();

        MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().setLaxMode();

        if (fileBody != null) {
            Args.check(fileBody.isFile(), "fileBody must be a file");
            Args.check(fileBody.canRead(), "fileBody must be readable");

            if (filename == null && streamBody == null)
                filename = fileBody.getName();

            FileBody bin = new FileBody(fileBody, ContentType.APPLICATION_OCTET_STREAM,
                    streamBody != null ? fileBody.getName() : filename);
            reqEntity.addPart(workerBuilder.getFileFieldName(), bin);
        }

        Args.notEmpty(filename, "filename");

        if (streamBody != null)
            reqEntity.addBinaryBody(workerBuilder.getFileFieldName(), streamBody,
                    ContentType.APPLICATION_OCTET_STREAM, filename);

        buildParameters(reqEntity, params, charset);

        requestBuilder.setEntity(reqEntity.build());
    }

    if (fileBody == null && streamBody == null) {
        buildParameters(requestBuilder, params);
    }

    if (workerBuilder.getReadTimeout() > -1) {

        requestBuilder.setConfig(RequestConfig.copy(this.hostConfig.getRequestConfig())
                .setSocketTimeout(workerBuilder.getReadTimeout()).build());
    }

    HttpUriRequest httpRequest = ParameterRequestBuilder.build(requestBuilder);

    setAcceptHeader(httpRequest, contentType);

    if (workerBuilder.isAjax())
        setAjaxHeader(httpRequest);

    HttpClientContext context = workerBuilder.getContext();
    if (context == null)
        context = defaultHttpContext;

    T result = getHttpClient().execute(httpRequest, responseHandler, context);

    if (log.isDebugEnabled()) {
        log.debug(String.format("Send data to path:[%s]\"%s\". result: %s", method, url, result));
    }

    return result;
}