Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BasicApnsConnection {
- private final Socket apnsSocket;
- private final DataInputStream apnsIn;
- private final OutputStream apnsOut;
- private final ExecutorService apnsInExecutor;
- private final Future<ApnsException> inputstreamTask;
- BasicApnsConnection(SocketFactory socketFactory, String host, int port)
- throws UnknownHostException, IOException {
- apnsSocket = socketFactory.createSocket();
- apnsSocket.setKeepAlive(true); // I tried to add this line, but it didn't work
- apnsSocket.connect(new InetSocketAddress(host, port));
- apnsIn = new DataInputStream(this.apnsSocket.getInputStream());
- apnsOut = this.apnsSocket.getOutputStream();
- apnsInExecutor = Executors.newSingleThreadExecutor();
- inputstreamTask = apnsInExecutor.submit(new InputstreamHandler());
- }
- public synchronized void push(ApnsNotification notification)
- throws ApnsException {
- if (notification == null) {
- throw new IllegalArgumentException("notification is null");
- }
- checkIfExceptionOccurred();
- ByteArrayOutputStream bytesBuffer = new ByteArrayOutputStream();
- notification.serialize(bytesBuffer);
- byte[] dataBytes = bytesBuffer.toByteArray();
- try {
- apnsOut.write(dataBytes);
- apnsOut.flush();
- } catch (IOException ex) {
- throw new ApnsNetworkException("IOException occurred during " +
- "pushing a notification to the APNS server", ex);
- }
- }
- private void checkIfExceptionOccurred() throws ApnsException {
- try {
- if (inputstreamTask.isDone()) {
- throw inputstreamTask.get();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
- private class InputstreamHandler implements Callable<ApnsException> {
- @Override
- public ApnsException call() throws IOException, ApnsException {
- byte[] errorResponse = new byte[6];
- try {
- apnsIn.readFully(errorResponse);
- byte command = errorResponse[0];
- if (ApnsCommand.ERROR_COMMAND.getCode() != command) {
- return new ApnsException(String.format(
- "Unknwon command: %b from the APNS error response",
- command));
- }
- byte status = errorResponse[1];
- int identifier = SerializationUtils.toInt(errorResponse, 2);
- if (status == ErrorStatus.NO_ERRORS) {
- return new ApnsException("no errors"); // never reaches
- } else if (status > ErrorStatus.NO_ERRORS &&
- status <= ErrorStatus.INVALID_TOKEN) {
- return new ApnsMalformedException(status, identifier);
- } else if (status == ErrorStatus.SHUTDOWN) {
- return new ApnsShutdownException(identifier);
- } else {
- return new ApnsException("Unknown");
- }
- } catch (IOException ex) {
- return new ApnsNetworkException(
- "IOException occurred while pushing a notification",
- ex);
- } catch (Exception ex) {
- return new ApnsException("Unknown exception", ex);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement