Example usage for java.net SocketException SocketException

List of usage examples for java.net SocketException SocketException

Introduction

In this page you can find the example usage for java.net SocketException SocketException.

Prototype

public SocketException(String msg) 

Source Link

Document

Constructs a new SocketException with the specified detail message.

Usage

From source file:edu.si.services.beans.edansidora.UCT_EdanSidoraTest.java

@Test
public void edanIdsHTTPExceptionTest() throws Exception {
    Integer minEdanHTTPRedelivery = Integer.valueOf(getExtra().getProperty("min.edan.http.redeliveries"));

    MockEndpoint mockResult = getMockEndpoint("mock:result");
    mockResult.expectedMessageCount(0);/* w  w  w  . j  ava 2  s  .c o  m*/
    mockResult.expectedHeaderReceived("redeliveryCount", minEdanHTTPRedelivery);

    MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);
    if ((minEdanHTTPRedelivery % 2) == 0) {
        mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT)
                .isInstanceOf(HttpOperationFailedException.class);
    } else {
        mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(SocketException.class);
    }
    mockError.expectedHeaderReceived("redeliveryCount", minEdanHTTPRedelivery); //headers are not preserved from split

    context.getRouteDefinition("EdanIdsProcessCtDeployment").adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {

            /**
             * I have not been able to come up with a way of testing other exceptions (exception bar) being thrown
             * during retries for original exception (exception foo)
             * See link for a good explanation and example of the issue
             * https://stackoverflow.com/questions/13684775/camel-retry-control-with-multiple-exceptions
             */

            //processor used to test onException and retries
            final Processor processor = new Processor() {
                public void process(Exchange exchange) throws Exception {
                    Message in = exchange.getIn();
                    log.info("Redelivery Count = {}", in.getHeader(Exchange.REDELIVERY_COUNTER));
                    exchange.setProperty(Exchange.TO_ENDPOINT, in.getHeader("CamelHttpUri"));
                    log.info("exchangeProperty(Exchange.TO_ENDPOINT) = {}",
                            exchange.getProperty(Exchange.TO_ENDPOINT));
                    in.setHeader("redeliveryCount", in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class));

                    if (in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class) != null) {
                        if ((in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class) % 2) != 0
                                && in.getHeader("redeliveryCount", Integer.class) != 0) {
                            log.info("if block Redelivery Count = {}",
                                    in.getHeader(Exchange.REDELIVERY_COUNTER));
                            log.info("if exchangeProperty(Exchange.TO_ENDPOINT) = {}",
                                    exchange.getProperty(Exchange.TO_ENDPOINT));
                            throw new SocketException("Simulated SocketException!!!");
                        } else {
                            throw new HttpOperationFailedException("http://somehost", 404, null, null, null,
                                    null);
                        }
                    } else {
                        throw new HttpOperationFailedException("http://somehost", 404, null, null, null, null);
                    }
                }
            };

            //this will not trigger the onWhen in the onException use interceptSendToEndpoint
            //weaveById("ctProcessGetFedoraDatastream").replace().process(processor);

            interceptSendToEndpoint("http4:*").skipSendToOriginalEndpoint().process(processor);
            weaveById("logEdanIdsHTTPException").after().to("mock:error");
            weaveById("ctProcessEdanUpdate").replace().to("mock:result").stop();
        }
    });

    Exchange exchange = new DefaultExchange(context);
    exchange.getIn().setHeader("addEdanIds", "true");
    exchange.getIn().setHeader("ProjectId", "testProjectId");
    exchange.getIn().setHeader("SiteId", "testDeploymentId");
    exchange.getIn().setHeader("SitePID", "test:003");
    exchange.getIn().setHeader("PIDAggregation",
            "test:004,test:005,test:006,test:007,test:008,test:009,test:010,test:011,test:012");
    exchange.getIn().setHeader("ResearcherObservationPID", "test:010");
    exchange.getIn().setHeader("VolunteerObservationPID", "test:011");
    exchange.getIn().setHeader("ImageObservationPID", "test:012");

    template.send("activemq:queue:" + JMS_TEST_QUEUE, exchange);

    assertMockEndpointsSatisfied();
}

From source file:davmail.imap.ImapConnection.java

@Override
public void run() {
    final String capabilities;
    int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60;
    if (imapIdleDelay > 0) {
        capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE MOVE";
    } else {//  ww  w  .  j  a va 2 s .  c o m
        capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN MOVE";
    }

    String line;
    String commandId = null;
    IMAPTokenizer tokens;
    try {
        //            ExchangeSessionFactory.checkConfig();
        sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion()
                + " server ready");
        for (;;) {
            line = readClient();
            // unable to read line, connection closed ?
            if (line == null) {
                break;
            }

            tokens = new IMAPTokenizer(line);
            if (tokens.hasMoreTokens()) {
                commandId = tokens.nextToken();

                checkInfiniteLoop(line);

                if (tokens.hasMoreTokens()) {
                    String command = tokens.nextToken();

                    if ("LOGOUT".equalsIgnoreCase(command)) {
                        sendClient("* BYE Closing connection");
                        sendClient(commandId + " OK LOGOUT completed");
                        break;
                    }
                    if ("capability".equalsIgnoreCase(command)) {
                        sendClient("* " + capabilities);
                        sendClient(commandId + " OK CAPABILITY completed");
                    } else if ("login".equalsIgnoreCase(command)) {
                        parseCredentials(tokens);
                        // detect shared mailbox access
                        splitUserName();
                        try {
                            session = ExchangeSessionFactory.getInstance(userName, password);
                            sendClient(commandId + " OK Authenticated");
                            state = State.AUTHENTICATED;
                        } catch (Exception e) {
                            DavGatewayTray.error(e);
                            sendClient(commandId + " NO LOGIN failed");
                            state = State.INITIAL;
                        }
                    } else if ("AUTHENTICATE".equalsIgnoreCase(command)) {
                        if (tokens.hasMoreTokens()) {
                            String authenticationMethod = tokens.nextToken();
                            if ("LOGIN".equalsIgnoreCase(authenticationMethod)) {
                                try {
                                    sendClient("+ " + base64Encode("Username:"));
                                    state = State.LOGIN;
                                    userName = base64Decode(readClient());
                                    // detect shared mailbox access
                                    splitUserName();
                                    sendClient("+ " + base64Encode("Password:"));
                                    state = State.PASSWORD;
                                    password = base64Decode(readClient());
                                    session = ExchangeSessionFactory.getInstance(userName, password);
                                    sendClient(commandId + " OK Authenticated");
                                    state = State.AUTHENTICATED;
                                } catch (Exception e) {
                                    DavGatewayTray.error(e);
                                    sendClient(commandId + " NO LOGIN failed");
                                    state = State.INITIAL;
                                }
                            } else {
                                sendClient(commandId + " NO unsupported authentication method");
                            }
                        } else {
                            sendClient(commandId + " BAD authentication method required");
                        }
                    } else {
                        if (state != State.AUTHENTICATED) {
                            sendClient(commandId + " BAD command authentication required");
                        } else {
                            // check for expired session
                            session = ExchangeSessionFactory.getInstance(session, userName, password);
                            if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String folderContext;
                                    if (baseMailboxPath == null) {
                                        folderContext = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    } else {
                                        folderContext = baseMailboxPath
                                                + BASE64MailboxDecoder.decode(tokens.nextToken());
                                    }
                                    if (tokens.hasMoreTokens()) {
                                        String folderQuery = folderContext
                                                + BASE64MailboxDecoder.decode(tokens.nextToken());
                                        if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) {
                                            List<ExchangeSession.Folder> folders = session.getSubFolders(
                                                    folderQuery.substring(0, folderQuery.length() - 3), false);
                                            for (ExchangeSession.Folder folder : folders) {
                                                sendClient(
                                                        "* " + command + " (" + folder.getFlags() + ") \"/\" \""
                                                                + BASE64MailboxEncoder.encode(folder.folderPath)
                                                                + '\"');
                                                sendSubFolders(command, folder.folderPath, false);
                                            }
                                            sendClient(commandId + " OK " + command + " completed");
                                        } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) {
                                            if ("/*".equals(folderQuery) || "/%".equals(folderQuery)
                                                    || "/%/%".equals(folderQuery)) {
                                                folderQuery = folderQuery.substring(1);
                                                if ("%/%".equals(folderQuery)) {
                                                    folderQuery = folderQuery.substring(0,
                                                            folderQuery.length() - 2);
                                                }
                                                sendClient(
                                                        "* " + command + " (\\HasChildren) \"/\" \"/public\"");
                                            }
                                            if ("*%".equals(folderQuery)) {
                                                folderQuery = "*";
                                            }
                                            boolean recursive = folderQuery.endsWith("*")
                                                    && !folderQuery.startsWith("/public");
                                            sendSubFolders(command,
                                                    folderQuery.substring(0, folderQuery.length() - 1),
                                                    recursive);
                                            sendClient(commandId + " OK " + command + " completed");
                                        } else {
                                            ExchangeSession.Folder folder = null;
                                            try {
                                                folder = session.getFolder(folderQuery);
                                            } catch (HttpForbiddenException e) {
                                                // access forbidden, ignore
                                                DavGatewayTray.debug(new BundleMessage(
                                                        "LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery));
                                            } catch (HttpNotFoundException e) {
                                                // not found, ignore
                                                DavGatewayTray.debug(
                                                        new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery));
                                            } catch (HttpException e) {
                                                // other errors, ignore
                                                DavGatewayTray
                                                        .debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR",
                                                                folderQuery, e.getMessage()));
                                            }
                                            if (folder != null) {
                                                sendClient(
                                                        "* " + command + " (" + folder.getFlags() + ") \"/\" \""
                                                                + BASE64MailboxEncoder.encode(folder.folderPath)
                                                                + '\"');
                                                sendClient(commandId + " OK " + command + " completed");
                                            } else {
                                                sendClient(commandId + " NO Folder not found");
                                            }
                                        }
                                    } else {
                                        sendClient(commandId + " BAD missing folder argument");
                                    }
                                } else {
                                    sendClient(commandId + " BAD missing folder argument");
                                }
                            } else if ("select".equalsIgnoreCase(command)
                                    || "examine".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" })
                                    String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    if (baseMailboxPath != null && !folderName.startsWith("/")) {
                                        folderName = baseMailboxPath + folderName;
                                    }
                                    try {
                                        currentFolder = session.getFolder(folderName);
                                        currentFolder.loadMessages();
                                        sendClient("* " + currentFolder.count() + " EXISTS");
                                        sendClient("* " + currentFolder.recent + " RECENT");
                                        sendClient("* OK [UIDVALIDITY 1]");
                                        if (currentFolder.count() == 0) {
                                            sendClient("* OK [UIDNEXT 1]");
                                        } else {
                                            sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']');
                                        }
                                        sendClient(
                                                "* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)");
                                        sendClient(
                                                "* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]");
                                        if ("select".equalsIgnoreCase(command)) {
                                            sendClient(
                                                    commandId + " OK [READ-WRITE] " + command + " completed");
                                        } else {
                                            sendClient(commandId + " OK [READ-ONLY] " + command + " completed");
                                        }
                                    } catch (HttpNotFoundException e) {
                                        sendClient(commandId + " NO Not found");
                                    } catch (HttpForbiddenException e) {
                                        sendClient(commandId + " NO Forbidden");
                                    }
                                } else {
                                    sendClient(commandId + " BAD command unrecognized");
                                }
                            } else if ("expunge".equalsIgnoreCase(command)) {
                                if (expunge(false)) {
                                    // need to refresh folder to avoid 404 errors
                                    session.refreshFolder(currentFolder);
                                }
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("close".equalsIgnoreCase(command)) {
                                expunge(true);
                                // deselect folder
                                currentFolder = null;
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("create".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    session.createMessageFolder(folderName);
                                    sendClient(commandId + " OK folder created");
                                } else {
                                    sendClient(commandId + " BAD missing create argument");
                                }
                            } else if ("rename".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                try {
                                    session.moveFolder(folderName, targetName);
                                    sendClient(commandId + " OK rename completed");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("delete".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                try {
                                    session.deleteFolder(folderName);
                                    sendClient(commandId + " OK folder deleted");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("uid".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String subcommand = tokens.nextToken();
                                    if ("fetch".equalsIgnoreCase(subcommand)) {
                                        if (currentFolder == null) {
                                            sendClient(commandId + " NO no folder selected");
                                        } else {
                                            String ranges = tokens.nextToken();
                                            if (ranges == null) {
                                                sendClient(commandId + " BAD missing range parameter");
                                            } else {
                                                String parameters = null;
                                                if (tokens.hasMoreTokens()) {
                                                    parameters = tokens.nextToken();
                                                }
                                                UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                        currentFolder.messages, ranges);
                                                while (uidRangeIterator.hasNext()) {
                                                    DavGatewayTray.switchIcon();
                                                    ExchangeSession.Message message = uidRangeIterator.next();
                                                    try {
                                                        handleFetch(message, uidRangeIterator.currentIndex,
                                                                parameters);
                                                    } catch (HttpNotFoundException e) {
                                                        LOGGER.warn("Ignore missing message "
                                                                + uidRangeIterator.currentIndex);
                                                    } catch (SocketException e) {
                                                        // client closed connection
                                                        throw e;
                                                    } catch (IOException e) {
                                                        DavGatewayTray.log(e);
                                                        sendClient(
                                                                commandId + " NO Unable to retrieve message: "
                                                                        + e.getMessage());
                                                    }
                                                }
                                                sendClient(commandId + " OK UID FETCH completed");
                                            }
                                        }

                                    } else if ("search".equalsIgnoreCase(subcommand)) {
                                        List<Long> uidList = handleSearch(tokens);
                                        StringBuilder buffer = new StringBuilder("* SEARCH");
                                        for (long uid : uidList) {
                                            buffer.append(' ');
                                            buffer.append(uid);
                                        }
                                        sendClient(buffer.toString());
                                        sendClient(commandId + " OK SEARCH completed");

                                    } else if ("store".equalsIgnoreCase(subcommand)) {
                                        UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                currentFolder.messages, tokens.nextToken());
                                        String action = tokens.nextToken();
                                        String flags = tokens.nextToken();
                                        handleStore(commandId, uidRangeIterator, action, flags);
                                    } else if ("copy".equalsIgnoreCase(subcommand)
                                            || "move".equalsIgnoreCase(subcommand)) {
                                        try {
                                            UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                    currentFolder.messages, tokens.nextToken());
                                            String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                            if (!uidRangeIterator.hasNext()) {
                                                sendClient(commandId + " NO " + "No message found");
                                            } else {
                                                while (uidRangeIterator.hasNext()) {
                                                    DavGatewayTray.switchIcon();
                                                    ExchangeSession.Message message = uidRangeIterator.next();
                                                    if ("copy".equalsIgnoreCase(subcommand)) {
                                                        session.copyMessage(message, targetName);
                                                    } else {
                                                        session.moveMessage(message, targetName);
                                                    }
                                                }
                                                sendClient(commandId + " OK " + subcommand + " completed");
                                            }
                                        } catch (HttpException e) {
                                            sendClient(commandId + " NO " + e.getMessage());
                                        }
                                    }
                                } else {
                                    sendClient(commandId + " BAD command unrecognized");
                                }
                            } else if ("search".equalsIgnoreCase(command)) {
                                if (currentFolder == null) {
                                    sendClient(commandId + " NO no folder selected");
                                } else {
                                    List<Long> uidList = handleSearch(tokens);
                                    if (uidList.isEmpty()) {
                                        sendClient("* SEARCH");
                                    } else {
                                        int currentIndex = 0;
                                        for (ExchangeSession.Message message : currentFolder.messages) {
                                            currentIndex++;
                                            if (uidList.contains(message.getImapUid())) {
                                                sendClient("* SEARCH " + currentIndex);
                                            }
                                        }
                                    }
                                    sendClient(commandId + " OK SEARCH completed");
                                }
                            } else if ("fetch".equalsIgnoreCase(command)) {
                                if (currentFolder == null) {
                                    sendClient(commandId + " NO no folder selected");
                                } else {
                                    RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                            tokens.nextToken());
                                    String parameters = null;
                                    if (tokens.hasMoreTokens()) {
                                        parameters = tokens.nextToken();
                                    }
                                    while (rangeIterator.hasNext()) {
                                        DavGatewayTray.switchIcon();
                                        ExchangeSession.Message message = rangeIterator.next();
                                        try {
                                            handleFetch(message, rangeIterator.currentIndex, parameters);
                                        } catch (HttpNotFoundException e) {
                                            LOGGER.warn("Ignore missing message " + rangeIterator.currentIndex);
                                        } catch (SocketException e) {
                                            // client closed connection, rethrow exception
                                            throw e;
                                        } catch (IOException e) {
                                            DavGatewayTray.log(e);
                                            sendClient(commandId + " NO Unable to retrieve message: "
                                                    + e.getMessage());
                                        }

                                    }
                                    sendClient(commandId + " OK FETCH completed");
                                }

                            } else if ("store".equalsIgnoreCase(command)) {
                                RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                        tokens.nextToken());
                                String action = tokens.nextToken();
                                String flags = tokens.nextToken();
                                handleStore(commandId, rangeIterator, action, flags);

                            } else if ("copy".equalsIgnoreCase(command) || "move".equalsIgnoreCase(command)) {
                                try {
                                    RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                            tokens.nextToken());
                                    String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    if (!rangeIterator.hasNext()) {
                                        sendClient(commandId + " NO " + "No message found");
                                    } else {
                                        while (rangeIterator.hasNext()) {
                                            DavGatewayTray.switchIcon();
                                            ExchangeSession.Message message = rangeIterator.next();
                                            if ("copy".equalsIgnoreCase(command)) {
                                                session.copyMessage(message, targetName);
                                            } else {
                                                session.moveMessage(message, targetName);
                                            }
                                        }
                                        sendClient(commandId + " OK " + command + " completed");
                                    }
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("append".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                HashMap<String, String> properties = new HashMap<String, String>();
                                String flags = null;
                                String date = null;
                                // handle optional flags
                                String nextToken = tokens.nextQuotedToken();
                                if (nextToken.startsWith("(")) {
                                    flags = StringUtil.removeQuotes(nextToken);
                                    if (tokens.hasMoreTokens()) {
                                        nextToken = tokens.nextToken();
                                        if (tokens.hasMoreTokens()) {
                                            date = nextToken;
                                            nextToken = tokens.nextToken();
                                        }
                                    }
                                } else if (tokens.hasMoreTokens()) {
                                    date = StringUtil.removeQuotes(nextToken);
                                    nextToken = tokens.nextToken();
                                }

                                if (flags != null) {
                                    // parse flags, on create read and draft flags are on the
                                    // same messageFlags property, 8 means draft and 1 means read
                                    StringTokenizer flagtokenizer = new StringTokenizer(flags);
                                    while (flagtokenizer.hasMoreTokens()) {
                                        String flag = flagtokenizer.nextToken();
                                        if ("\\Seen".equals(flag)) {
                                            if (properties.containsKey("draft")) {
                                                // draft message, add read flag
                                                properties.put("draft", "9");
                                            } else {
                                                // not (yet) draft, set read flag
                                                properties.put("draft", "1");
                                            }
                                        } else if ("\\Flagged".equals(flag)) {
                                            properties.put("flagged", "2");
                                        } else if ("\\Answered".equals(flag)) {
                                            properties.put("answered", "102");
                                        } else if ("$Forwarded".equals(flag)) {
                                            properties.put("forwarded", "104");
                                        } else if ("\\Draft".equals(flag)) {
                                            if (properties.containsKey("draft")) {
                                                // read message, add draft flag
                                                properties.put("draft", "9");
                                            } else {
                                                // not (yet) read, set draft flag
                                                properties.put("draft", "8");
                                            }
                                        } else if ("Junk".equals(flag)) {
                                            properties.put("junk", "1");
                                        }
                                    }
                                } else {
                                    // no flags, force not draft and unread
                                    properties.put("draft", "0");
                                }
                                // handle optional date
                                if (date != null) {
                                    SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z",
                                            Locale.ENGLISH);
                                    Date dateReceived = dateParser.parse(date);
                                    SimpleDateFormat dateFormatter = new SimpleDateFormat(
                                            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                                    dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);

                                    properties.put("datereceived", dateFormatter.format(dateReceived));
                                }
                                int size = Integer.parseInt(StringUtil.removeQuotes(nextToken));
                                sendClient("+ send literal data");
                                byte[] buffer = in.readContent(size);
                                // empty line
                                readClient();
                                MimeMessage mimeMessage = new MimeMessage(null,
                                        new SharedByteArrayInputStream(buffer));

                                String messageName = UUID.randomUUID().toString() + ".EML";
                                try {
                                    session.createMessage(folderName, messageName, properties, mimeMessage);
                                    sendClient(commandId + " OK APPEND completed");
                                } catch (InsufficientStorageException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) {
                                if (currentFolder != null) {
                                    sendClient("+ idling ");
                                    // clear cache before going to idle mode
                                    currentFolder.clearCache();
                                    DavGatewayTray.resetIcon();
                                    try {
                                        int count = 0;
                                        while (in.available() == 0) {
                                            if (++count >= imapIdleDelay) {
                                                count = 0;
                                                TreeMap<Long, String> previousImapFlagMap = currentFolder
                                                        .getImapFlagMap();
                                                if (session.refreshFolder(currentFolder)) {
                                                    handleRefresh(previousImapFlagMap,
                                                            currentFolder.getImapFlagMap());
                                                }
                                            }
                                            // sleep 1 second
                                            Thread.sleep(1000);
                                        }
                                        // read DONE line
                                        line = readClient();
                                        if ("DONE".equals(line)) {
                                            sendClient(commandId + " OK " + command + " terminated");
                                        } else {
                                            sendClient(commandId + " BAD command unrecognized");
                                        }
                                    } catch (IOException e) {
                                        // client connection closed
                                        throw new SocketException(e.getMessage());
                                    }
                                } else {
                                    sendClient(commandId + " NO no folder selected");
                                }
                            } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) {
                                if (currentFolder != null) {
                                    DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command,
                                            currentFolder.folderPath));
                                    TreeMap<Long, String> previousImapFlagMap = currentFolder.getImapFlagMap();
                                    if (session.refreshFolder(currentFolder)) {
                                        handleRefresh(previousImapFlagMap, currentFolder.getImapFlagMap());
                                    }
                                }
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("subscribe".equalsIgnoreCase(command)
                                    || "unsubscribe".equalsIgnoreCase(command)) {
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("status".equalsIgnoreCase(command)) {
                                try {
                                    String encodedFolderName = tokens.nextToken();
                                    String folderName = BASE64MailboxDecoder.decode(encodedFolderName);
                                    ExchangeSession.Folder folder = session.getFolder(folderName);
                                    // must retrieve messages
                                    folder.loadMessages();
                                    String parameters = tokens.nextToken();
                                    StringBuilder answer = new StringBuilder();
                                    StringTokenizer parametersTokens = new StringTokenizer(parameters);
                                    while (parametersTokens.hasMoreTokens()) {
                                        String token = parametersTokens.nextToken();
                                        if ("MESSAGES".equalsIgnoreCase(token)) {
                                            answer.append("MESSAGES ").append(folder.count()).append(' ');
                                        }
                                        if ("RECENT".equalsIgnoreCase(token)) {
                                            answer.append("RECENT ").append(folder.recent).append(' ');
                                        }
                                        if ("UIDNEXT".equalsIgnoreCase(token)) {
                                            if (folder.count() == 0) {
                                                answer.append("UIDNEXT 1 ");
                                            } else {
                                                if (folder.count() == 0) {
                                                    answer.append("UIDNEXT 1 ");
                                                } else {
                                                    answer.append("UIDNEXT ").append(folder.getUidNext())
                                                            .append(' ');
                                                }
                                            }

                                        }
                                        if ("UIDVALIDITY".equalsIgnoreCase(token)) {
                                            answer.append("UIDVALIDITY 1 ");
                                        }
                                        if ("UNSEEN".equalsIgnoreCase(token)) {
                                            answer.append("UNSEEN ").append(folder.unreadCount).append(' ');
                                        }
                                    }
                                    sendClient("* STATUS \"" + encodedFolderName + "\" ("
                                            + answer.toString().trim() + ')');
                                    sendClient(commandId + " OK " + command + " completed");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO folder not found");
                                }
                            } else {
                                sendClient(commandId + " BAD command unrecognized");
                            }
                        }
                    }

                } else {
                    sendClient(commandId + " BAD missing command");
                }
            } else {
                sendClient("BAD Null command");
            }
            DavGatewayTray.resetIcon();
        }

        os.flush();
    } catch (SocketTimeoutException e) {
        DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT"));
        try {
            sendClient("* BYE Closing connection");
        } catch (IOException e1) {
            DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT"));
        }
    } catch (SocketException e) {
        LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION"));
    } catch (Exception e) {
        DavGatewayTray.log(e);
        try {
            String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " ");
            if (commandId != null) {
                sendClient(commandId + " BAD unable to handle request: " + message);
            } else {
                sendClient("* BAD unable to handle request: " + message);
            }
        } catch (IOException e2) {
            DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
        }
    } finally {
        close();
    }
    DavGatewayTray.resetIcon();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testConnectionException() throws Exception {
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    AbstractConnectionFactory mockCcf = mock(AbstractClientConnectionFactory.class);
    Mockito.doAnswer(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new SocketException("Failed to connect");
        }/*  ww w. j a  va 2s . c  o  m*/
    }).when(mockCcf).getConnection();
    handler.setConnectionFactory(mockCcf);
    try {
        handler.handleMessage(new GenericMessage<String>("foo"));
        fail("Expected exception");
    } catch (Exception e) {
        assertTrue(e instanceof MessagingException);
        assertTrue(e.getCause() != null);
        assertTrue(e.getCause() instanceof SocketException);
        assertEquals("Failed to connect", e.getCause().getMessage());
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

void processIncomingConnection(Socket sock) throws IOException {
    if (sock.isClosed()) {
        // This should no longer happen
        throw new SocketException("processIncomingConnection got closed socket");
    }// ww w  .  ja  v  a2s  .  co  m
    // Setup socket (SO_TIMEOUT, etc.) before SSL handshake
    setupOpenSocket(sock);
    log.debug2("Accepted connection from " + new IPAddr(sock.getInetAddress()));
    // SSL handshake now performed by channel
    BlockingPeerChannel chan = getSocketFactory().newPeerChannel(this, sock);
    chan.startIncoming();
}