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

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

Introduction

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

Prototype

public static <T> T notNull(T t, String str) 

Source Link

Usage

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);//w  w  w . j a  va2s.  c  o m
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:net.dv8tion.jda.core.managers.fields.PermissionField.java

/**
 * Adds the specified permissions to the result value
 * <br>If any of the specified permissions is present in the revoked permissions it will be removed!
 * <br><b>This does not apply immediately - it is applied in the value returned by {@link #getValue()}</b>
 *
 * @param  permissions//from   ww w  .  ja va 2  s  .  c  o  m
 *         Permissions that should be granted
 *
 * @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 givePermissions(Collection<Permission> permissions) {
    Args.notNull(permissions, "Permission Collection");
    permissions.forEach(p -> {
        Args.notNull(p, "Permission in the Collection");
        checkPermission(p);
    });

    permsGiven.addAll(permissions);
    permsRevoked.removeAll(permissions);

    set = true;

    return manager;
}

From source file:com.ok2c.lightmtp.impl.protocol.SendDataCodec.java

@Override
public void consumeData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionInputBuffer buf = this.iobuffers.getInbuf();

    while (this.codecState != CodecState.COMPLETED) {
        int bytesRead = buf.fill(iosession.channel());

        SMTPReply reply = this.parser.parse(buf, bytesRead == -1);
        if (reply == null) {
            if (bytesRead == -1 && !sessionState.isTerminated()) {
                throw new UnexpectedEndOfStreamException();
            } else {
                break;
            }/*from   w  ww  . ja va2 s . co  m*/
        }

        switch (this.codecState) {
        case CONTENT_RESPONSE_EXPECTED:
            if (this.mode.equals(DataAckMode.PER_RECIPIENT)) {
                String recipient = this.recipients.removeFirst();
                if (reply.getCode() != SMTPCodes.OK) {
                    sessionState.getFailures().add(new RcptResult(reply, recipient));
                }
            }
            if (this.recipients.isEmpty()) {
                this.codecState = CodecState.COMPLETED;
            }
            sessionState.setReply(reply);
            break;
        default:
            throw new SMTPProtocolException("Unexpected reply: " + reply);
        }
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.CloseableBasicHttpClientConnectionManager.java

@Override
public final ConnectionRequest requestConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "Route");
    return new ConnectionRequest() {

        @Override/*  w w w . jav a2s  .  c om*/
        public boolean cancel() {
            // Nothing to abort, since requests are immediate.
            return false;
        }

        @Override
        public HttpClientConnection get(final long timeout, final TimeUnit tunit) {
            return CloseableBasicHttpClientConnectionManager.this.getConnection(route, state);
        }

    };
}

From source file:net.dv8tion.jda.core.entities.impl.VoiceChannelImpl.java

@Override
public RestAction<PermissionOverride> createPermissionOverride(Role role) {
    checkPermission(Permission.MANAGE_PERMISSIONS);
    Args.notNull(role, "role");
    if (!guild.equals(role.getGuild()))
        throw new IllegalArgumentException("Provided role is not from the same guild as this channel!");
    if (getRoleOverrideMap().containsKey(role))
        throw new IllegalStateException("Provided role already has a PermissionOverride in this channel!");

    final PermissionOverride override = new PermissionOverrideImpl(this, null, role);

    JSONObject body = new JSONObject().put("id", role.getId()).put("type", "role").put("allow", 0).put("deny",
            0);//from w ww . j  a v  a2  s.c  om

    Route.CompiledRoute route = Route.Channels.CREATE_PERM_OVERRIDE.compile(id, role.getId());
    return new RestAction<PermissionOverride>(getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request request) {
            if (!response.isOk())
                request.onFailure(response);

            getRoleOverrideMap().put(role, override);
            request.onSuccess(override);
        }
    };
}

From source file:io.soabase.client.apache.WrappedHttpClient.java

private <T> T internalExecute(final HttpUriRequest uriRequest, final HttpHost target, final HttpRequest request,
        final ResponseHandler<? extends T> responseHandler, final HttpContext context) throws IOException {
    Args.notNull(responseHandler, "Response handler");

    final HttpResponse response = (uriRequest != null) ? execute(uriRequest, context)
            : execute(target, request, context);

    final T result;
    try {/* w w w.  j  a v a 2  s  .c o  m*/
        result = responseHandler.handleResponse(response);
    } catch (final Exception t) {
        final HttpEntity entity = response.getEntity();
        try {
            EntityUtils.consume(entity);
        } catch (final Exception t2) {
            // Log this exception. The original exception is more
            // important and will be thrown to the caller.
            // TODO this.log.warn("Error consuming content after an exception.", t2);
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new UndeclaredThrowableException(t);
    }

    // Handling the response was successful. Ensure that the content has
    // been fully consumed.
    final HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    return result;
}

From source file:com.ok2c.lightmtp.impl.protocol.AuthCodec.java

@Override
public void consumeData(final IOSession iosession, final ClientState state)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(state, "Session state");

    SessionInputBuffer buf = this.iobuffers.getInbuf();

    int bytesRead = buf.fill(iosession.channel());
    SMTPReply reply = this.parser.parse(buf, bytesRead == -1);

    if (reply != null) {

        switch (this.codecState) {
        case AUTH_RESPONSE_READY:
            AuthMode mode = (AuthMode) iosession.getAttribute(AUTH_TYPE);

            if (reply.getCode() == SMTPCodes.START_AUTH_INPUT) {
                if (mode == AuthMode.PLAIN) {
                    this.codecState = CodecState.AUTH_PLAIN_INPUT_READY;
                } else if (mode == AuthMode.LOGIN) {
                    this.codecState = CodecState.AUTH_LOGIN_USERNAME_INPUT_READY;
                }/*from  w w w .  ja va2  s  .  com*/
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
            }
            break;

        case AUTH_PLAIN_INPUT_RESPONSE_EXPECTED:

            if (reply.getCode() == SMTPCodes.AUTH_OK) {
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);

            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
            }
            break;

        case AUTH_LOGIN_USERNAME_INPUT_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.START_AUTH_INPUT) {
                this.codecState = CodecState.AUTH_LOGIN_PASSWORD_INPUT_READY;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                throw new SMTPProtocolException("Unexpected reply:" + reply);
            }

            break;

        case AUTH_LOGIN_PASSWORD_INPUT_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.AUTH_OK) {
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);

            }
            break;

        default:
            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                state.setReply(reply);
                this.codecState = CodecState.COMPLETED;
            } else {
                throw new SMTPProtocolException("Unexpected reply:" + reply);
            }
        }
    } else {
        if (bytesRead == -1 && !state.isTerminated()) {
            throw new UnexpectedEndOfStreamException();
        }
    }
}

From source file:co.paralleluniverse.fibers.httpclient.FiberHttpClient.java

/**
 * {@inheritDoc}/* ww  w .j  a v  a  2  s.  c o m*/
 */
@Override
@Suspendable
public CloseableHttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {
    Args.notNull(request, "HTTP request");
    return doExecute(target, request, context);
}

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

/**
 * Parses textual representation of <code>Content-Type</code> value.
 *
 * @param s text/*  w  ww  .j a v a2  s . co  m*/
 * @return content type
 * @throws ParseException              if the given text does not represent a valid
 *                                     <code>Content-Type</code> value.
 * @throws UnsupportedCharsetException Thrown when the named charset is not available in
 *                                     this instance of the Java virtual machine
 */
public static ContentType parse(final String s) throws ParseException, UnsupportedCharsetException {
    Args.notNull(s, "Content type");
    final CharArrayBuffer buf = new CharArrayBuffer(s.length());
    buf.append(s);
    final ParserCursor cursor = new ParserCursor(0, s.length());
    final HeaderElement[] elements = BasicHeaderValueParser.DEFAULT.parseElements(buf, cursor);
    if (elements.length > 0) {
        return create(elements[0]);
    } else {
        throw new ParseException("Invalid content type: " + s);
    }
}