List of usage examples for org.apache.http.util Args notNull
public static <T> T notNull(T t, String str)
From source file:org.esigate.http.HttpResponseUtils.java
/** * Copied from org.apache.http.entity.InputStreamEntity.writeTo(OutputStream) method but flushes the buffer after * each read in order to allow streaming and web sockets. * // ww w .j a va 2 s . c o m * @param httpEntity * The entity to copy to the OutputStream * @param outstream * The OutputStream * @throws IOException * If a problem occurs */ public static void writeTo(final HttpEntity httpEntity, final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = httpEntity.getContent(); try { final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE]; int l; if (httpEntity.getContentLength() < 0) { // consume until EOF while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); outstream.flush(); LOG.debug("Flushed {} bytes of data"); } } else { // consume no more than length long remaining = httpEntity.getContentLength(); while (remaining > 0) { l = instream.read(buffer, 0, (int) Math.min(OUTPUT_BUFFER_SIZE, remaining)); if (l == -1) { break; } outstream.write(buffer, 0, l); outstream.flush(); LOG.debug("Flushed {} bytes of data"); remaining -= l; } } } finally { instream.close(); } }
From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java
/** * Build an {@link SSLSessionStrategy}./* w ww .j a v a 2 s . c o m*/ * * @param trustStore the trust store * @param trustStorePassword the truststore password (if any) * @param keyStore the keystore * @param keyStorePassword the keystore password (if any) * @param keyAliases the key aliases that are candidates for use (if any) * @param keyPassword the key password (if any) * @param allowedProtocols the allowed transport protocols. * <strong><em>Avoid specifying insecure protocols</em></strong> * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults * @param trustSelfSigned true if self signed certificates can be trusted. * <strong><em>Use with caution</em></strong> * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match * certificate hostname). <strong><em>Do not use in production</em></strong> * @return the connection socket factory * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system * @throws KeyStoreException if there was a problem with the keystore * @throws CertificateException if there was a problem with the certificate * @throws IOException if the truststore could not be found or was invalid * @throws KeyManagementException if there is a problem with keys * @throws UnrecoverableKeyException if the key cannot be recovered */ public static SSLSessionStrategy build(String trustStore, String trustStorePassword, String keyStore, String keyStorePassword, String[] keyAliases, String keyPassword, String[] allowedProtocols, String[] allowedCiphers, boolean allowAnyHostname, boolean trustSelfSigned) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException { Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$ Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$ TrustStrategy trustStrategy = trustSelfSigned ? SELF_SIGNED : null; HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases); boolean clientAuth = keyStore == null ? false : true; SSLContextBuilder builder = SSLContexts.custom(); if (trustStore != null) { loadTrustMaterial(builder, new File(trustStore), trustStorePassword.toCharArray(), trustStrategy); } if (keyStore != null) { char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray(); char[] kp = keyPassword == null ? null : keyPassword.toCharArray(); loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy); } SSLContext sslContext = builder.build(); return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory( sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth)); }
From source file:net.dv8tion.jda.core.EmbedBuilder.java
/** * Appends to the description of the embed. This is where the main chunk of text for an embed is typically placed. * * <p><b><a href="http://i.imgur.com/lbchtwk.png">Example</a></b> * * @param description/*from www . jav a2 s . co m*/ * the string to append to the description of the embed * * @throws java.lang.IllegalArgumentException * <ul> * <li>If the provided {@code description} String is null</li> * <li>If the length of {@code description} is greater than {@link net.dv8tion.jda.core.entities.MessageEmbed#TEXT_MAX_LENGTH}.</li> * </ul> * * @return the builder after the description has been set */ public EmbedBuilder appendDescription(CharSequence description) { Args.notNull(description, "description"); Args.check(this.description.length() + description.length() <= MessageEmbed.TEXT_MAX_LENGTH, "Description cannot be longer than %d characters.", MessageEmbed.TEXT_MAX_LENGTH); this.description.append(description); return this; }
From source file:net.dv8tion.jda.core.managers.fields.PermissionField.java
/** * Adds the specified permissions to the result value * <br>These will override permissions that are given through {@link #givePermissions(Collection)} and {@link #givePermissions(Permission...)}! * <br><b>This does not apply immediately - it is applied in the value returned by {@link #getValue()}</b> * * @param permissions//from ww w.j a v a2 s .co m * Permissions that should be revoked * * @throws IllegalArgumentException * If any of the provided Permissions is {@code null} * * @return The {@link net.dv8tion.jda.core.managers.RoleManagerUpdatable RoleManagerUpdatable} instance * for this PermissionField for chaining convenience */ public RoleManagerUpdatable revokePermissions(Collection<Permission> permissions) { Args.notNull(permissions, "Permission Collection"); permissions.forEach(p -> { Args.notNull(p, "Permission in the Collection"); checkPermission(p); }); permsRevoked.addAll(permissions); permsGiven.removeAll(permissions); set = true; return manager; }
From source file:com.ok2c.lightmtp.impl.protocol.ReceiveDataCodec.java
@Override public void consumeData(final IOSession iosession, final ServerState sessionState) throws IOException, SMTPProtocolException { Args.notNull(iosession, "IO session"); Args.notNull(sessionState, "Session state"); SessionInputBuffer buf = this.iobuffers.getInbuf(); synchronized (sessionState) { boolean hasData = true; while (hasData && !this.dataReceived) { int bytesRead = buf.fill(iosession.channel()); if (buf.readLine(this.lineBuf, bytesRead == -1)) { processLine();// www. j av a 2 s. c om if (!this.dataReceived) { this.contentBuf.writeLine(this.lineBuf); } this.lineBuf.clear(); } else { hasData = false; } if (this.dataReceived || this.contentBuf.length() > 4 * 1024 || bytesRead == -1) { this.contentBuf.flush(this.fileStore.channel()); } if (bytesRead == -1) { throw new UnexpectedEndOfStreamException(); } } if (this.contentBuf.hasData()) { this.contentBuf.flush(this.fileStore.channel()); } if (this.dataReceived && this.pendingDelivery == null) { this.fileStore.reset(); File file = this.fileStore.getFile(); SMTPContent<ReadableByteChannel> content = new FileSource(file); DeliveryRequest deliveryRequest = new BasicDeliveryRequest(sessionState.getSender(), sessionState.getRecipients(), content); String messageId = sessionState.getMessageId(); this.pendingDelivery = this.handler.handle(messageId, deliveryRequest, new OutputTrigger<DeliveryResult>(sessionState, iosession)); } } }
From source file:com.wudaosoft.net.httpclient.Request.java
/** * /*ww w .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; }
From source file:com.serphacker.serposcope.scraper.http.extensions.CloseableBasicHttpClientConnectionManager.java
@Override public synchronized void releaseConnection(final HttpClientConnection conn, final Object state, final long keepalive, final TimeUnit tunit) { Args.notNull(conn, "Connection"); Asserts.check(conn == this.conn, "Connection not obtained from this manager"); if (this.log.isDebugEnabled()) { this.log.debug("Releasing connection " + conn); }//from w w w .ja v a2 s . co m if (this.isShutdown.get()) { return; } try { this.updated = System.currentTimeMillis(); if (!this.conn.isOpen()) { this.conn = null; this.route = null; this.conn = null; this.expiry = Long.MAX_VALUE; } else { this.state = state; if (this.log.isDebugEnabled()) { final String s; if (keepalive > 0) { s = "for " + keepalive + " " + tunit; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } if (keepalive > 0) { this.expiry = this.updated + tunit.toMillis(keepalive); } else { this.expiry = Long.MAX_VALUE; } } } finally { this.leased = false; } }
From source file:com.serphacker.serposcope.scraper.http.extensions.CloseableBasicHttpClientConnectionManager.java
@Override public void connect(final HttpClientConnection conn, final HttpRoute route, final int connectTimeout, final HttpContext context) throws IOException { Args.notNull(conn, "Connection"); Args.notNull(route, "HTTP route"); Asserts.check(conn == this.conn, "Connection not obtained from this manager"); final HttpHost host; if (route.getProxyHost() != null) { host = route.getProxyHost();//from ww w . j a va2 s .c o m } else { host = route.getTargetHost(); } final InetSocketAddress localAddress = route.getLocalSocketAddress(); this.connectionOperator.connect(this.conn, host, localAddress, connectTimeout, this.socketConfig, context); }