Example usage for java.lang IllegalStateException getMessage

List of usage examples for java.lang IllegalStateException getMessage

Introduction

In this page you can find the example usage for java.lang IllegalStateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.padaf.preflight.font.AbstractFontValidator.java

/**
 * Type0, Type1 and TrueType FontValidatir call this method to check the
 * FontFile meta data.//from ww  w.  j  a v a2 s  .c o  m
 * 
 * @param fontDesc
 *          The FontDescriptor which contains the FontFile stream
 * @param fontFile
 *          The font file stream to check
 * @return true if the meta data is valid, false otherwise
 * @throws ValidationException when checking fails
 */
protected boolean checkFontFileMetaData(PDFontDescriptor fontDesc, PDStream fontFile)
        throws ValidationException {
    PDMetadata metadata = null;
    try {
        metadata = fontFile.getMetadata();
    } catch (IllegalStateException e) {
        fontContainer.addError(new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT_UNKOWN,
                "The Metadata entry doesn't reference a stream object"));
        return false;
    }
    if (metadata != null) {
        // --- Filters are forbidden in a XMP stream
        if (metadata.getFilters() != null && !metadata.getFilters().isEmpty()) {
            fontContainer.addError(new ValidationError(ValidationConstants.ERROR_SYNTAX_STREAM_INVALID_FILTER,
                    "Filter specified in font file metadata dictionnary"));
            return false;
        }

        // --- extract the meta data content
        byte[] mdAsBytes = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            InputStream metaDataContent = metadata.createInputStream();
            IOUtils.copyLarge(metaDataContent, bos);
            IOUtils.closeQuietly(metaDataContent);
            IOUtils.closeQuietly(bos);
            mdAsBytes = bos.toByteArray();
        } catch (IOException e) {
            throw new ValidationException("Unable to read font metadata due to : " + e.getMessage(), e);
        }

        try {

            XMPDocumentBuilder xmpBuilder = new XMPDocumentBuilder();
            XMPMetadata xmpMeta = xmpBuilder.parse(mdAsBytes);

            FontMetaDataValidation fontMDval = new FontMetaDataValidation();
            List<ValidationError> ve = new ArrayList<ValidationError>();
            boolean isVal = fontMDval.analyseFontName(xmpMeta, fontDesc, ve);
            isVal = isVal & fontMDval.analyseRights(xmpMeta, fontDesc, ve);
            for (ValidationError validationError : ve) {
                fontContainer.addError(validationError);
            }
            return isVal;

        } catch (XmpUnknownValueTypeException e) {
            fontContainer.addError(
                    new ValidationError(ValidationConstants.ERROR_METADATA_UNKNOWN_VALUETYPE, e.getMessage()));
            return false;
        } catch (XmpParsingException e) {
            fontContainer
                    .addError(new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT, e.getMessage()));
            return false;
        } catch (XmpSchemaException e) {
            fontContainer
                    .addError(new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT, e.getMessage()));
            return false;
        } catch (XmpExpectedRdfAboutAttribute e) {
            fontContainer.addError(new ValidationError(
                    ValidationConstants.ERROR_METADATA_RDF_ABOUT_ATTRIBUTE_MISSING, e.getMessage()));
            return false;
        } catch (BadFieldValueException e) {
            fontContainer.addError(new ValidationError(
                    ValidationConstants.ERROR_METADATA_CATEGORY_PROPERTY_INVALID, e.getMessage()));
            return false;
        } catch (XmpXpacketEndException e) {
            throw new ValidationException("Unable to parse font metadata due to : " + e.getMessage(), e);
        }
    }

    // --- No MetaData, valid
    return true;
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * The main method of this job. Called by confluence every time the mail2news trigger
 * fires.// w w  w. j  a  v  a2  s .c o m
 *
 * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext)
 */
public void doExecute(JobExecutionContext arg0) throws JobExecutionException {

    /* The mailstore object used to connect to the server */
    Store store = null;

    try {

        this.log.info("Executing mail2news plugin.");

        /* check if we have all necessary components */
        if (pageManager == null) {
            throw new Exception("Null PageManager instance.");
        }
        if (spaceManager == null) {
            throw new Exception("Null SpaceManager instance.");
        }
        if (configurationManager == null) {
            throw new Exception("Null ConfigurationManager instance.");
        }

        /* get the mail configuration from the manager */
        MailConfiguration config = configurationManager.getMailConfiguration();
        if (config == null) {
            throw new Exception("Null MailConfiguration instance.");
        }

        /* create the properties for the session */
        Properties prop = new Properties();

        /* get the protocol to use */
        if (config.getProtocol() == null) {
            throw new Exception("Cannot get protocol.");
        }
        String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : "");
        /* assemble the property prefix for this protocol */
        String propertyPrefix = "mail.";
        propertyPrefix = propertyPrefix.concat(protocol).concat(".");

        /* get the server port from the configuration and add it to the properties,
         * but only if it is actually set. If port = 0 this means we use the standard
         * port for the chosen protocol */
        int port = config.getPort();
        if (port != 0) {
            prop.setProperty(propertyPrefix.concat("port"), "" + port);
        }

        /* set connection timeout (10 seconds) */
        prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000");

        /* get the session for connecting to the mail server */
        Session session = Session.getInstance(prop, null);

        /* get the mail store, using the desired protocol */
        if (config.getSecure()) {
            store = session.getStore(protocol);
        } else {
            store = session.getStore(protocol);
        }

        /* get the host and credentials for the mail server from the configuration */
        String host = config.getServer();
        String username = config.getUsername();
        String password = config.getPassword();

        /* sanity check */
        if (host == null || username == null || password == null) {
            throw new Exception("Incomplete mail configuration settings (at least one setting is null).");
        }

        /* connect to the mailstore */
        try {
            store.connect(host, username, password);
        } catch (AuthenticationFailedException afe) {
            throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe);
        } catch (MessagingException me) {
            throw new Exception("Connecting to mail store failed: " + me.getMessage(), me);
        } catch (IllegalStateException ise) {
            throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise);
        } catch (Exception e) {
            throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e);
        }

        /***
         * Open the INBOX
         ***/

        /* get the INBOX folder */
        Folder folderInbox = store.getFolder("INBOX");
        /* we need to open it READ_WRITE, because we want to move messages we already handled */
        try {
            folderInbox.open(Folder.READ_WRITE);
        } catch (FolderNotFoundException fnfe) {
            throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe);
        } catch (Exception e) {
            throw new Exception("Could not open INBOX folder: " + e.getMessage(), e);
        }

        /* here we have to split, because IMAP will be handled differently from POP3 */
        if (config.getProtocol().toLowerCase().equals("imap")) {
            /***
             * Open the default folder, under which will be the processed
             * and the invalid folder.
             ***/

            Folder folderDefault = null;
            try {
                folderDefault = store.getDefaultFolder();
            } catch (MessagingException me) {
                throw new Exception("Could not get default folder: " + me.getMessage(), me);
            }
            /* sanity check */
            try {
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            } catch (MessagingException me) {
                throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me);
            }

            /**
             * This is kind of a fallback mechanism. For some reasons it can happen that
             * the default folder has an empty name and exists() returns true, but when
             * trying to create a subfolder it generates an error message.
             * So what we do here is if the name of the default folder is empty, we
             * look for the "INBOX" folder, which has to exist and then create the
             * subfolders under this folder.
             */
            if (folderDefault.getName().equals("")) {
                this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder.");
                folderDefault = store.getFolder("INBOX");
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            }

            /***
             * Open the folder for processed messages
             ***/

            /* get the folder where we store processed messages */
            Folder folderProcessed = folderDefault.getFolder("Processed");
            /* check if it exists */
            if (!folderProcessed.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'processed' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderProcessed.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e);
            }

            /***
             * Open the folder for invalid messages
             ***/

            /* get the folder where we store invalid messages */
            Folder folderInvalid = folderDefault.getFolder("Invalid");
            /* check if it exists */
            if (!folderInvalid.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'invalid' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderInvalid.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e);
            }

            /***
             * Get all new messages
             ***/

            /* get all messages in the INBOX */
            Message message[] = folderInbox.getMessages();

            /* go through all messages and get the unseen ones (all should be unseen,
             * as the seen ones get moved to a different folder
             */
            for (int i = 0; i < message.length; i++) {

                if (message[i].isSet(Flags.Flag.SEEN)) {
                    /* this message has been seen, should not happen */
                    /* send email to the sender */
                    sendErrorMessage(message[i],
                            "This message has already been flagged as seen before being handled and was thus ignored.");
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* move the message to the processed folder */
                moveMessage(message[i], folderInbox, folderProcessed);

            }

            /* close the folders, expunging deleted messages in the process */
            folderInbox.close(true);
            folderProcessed.close(true);
            folderInvalid.close(true);
            /* close the store */
            store.close();

        } else if (config.getProtocol().toLowerCase().equals("pop3")) {
            /* get all messages in this POP3 account */
            Message message[] = folderInbox.getMessages();

            /* go through all messages */
            for (int i = 0; i < message.length; i++) {

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* finished processing this message, delete it */
                message[i].setFlag(Flags.Flag.DELETED, true);
                /* get the next message, this message will be deleted when
                 * closing the folder */

            }

            /* close the pop3 folder, deleting all messages flagged as DELETED */
            folderInbox.close(true);
            /* close the mail store */
            store.close();

        } else {
            throw new Exception("Unknown protocol: " + config.getProtocol());
        }

    } catch (Exception e) {
        /* catch any exception which was not handled so far */
        this.log.error("Error while executing mail2news job: " + e.getMessage(), e);
        JobExecutionException jee = new JobExecutionException(
                "Error while executing mail2news job: " + e.getMessage(), e, false);
        throw jee;
    } finally {
        /* try to do some cleanup */
        try {
            store.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.libreplan.web.tree.TreeController.java

public void addElement(Component cmp) {
    viewStateSnapshot = TreeViewStateSnapshot.takeSnapshot(tree);
    Textbox name = (Textbox) cmp.getFellow("newOrderElementName");
    Intbox hours = (Intbox) cmp.getFellow("newOrderElementHours");

    if (StringUtils.isEmpty(name.getValue())) {
        throw new WrongValueException(name, _("cannot be empty"));
    }// ww  w .  ja  va2  s . c  o  m

    if (hours.getValue() == null) {
        hours.setValue(0);
    }

    Textbox nameTextbox = null;

    // Parse hours
    try {
        if (tree.getSelectedCount() == 1) {
            T node = getSelectedNode();

            T newNode = getModel().addElementAt(node, name.getValue(), hours.getValue());
            getRenderer().refreshHoursValueForThisNodeAndParents(newNode);
            getRenderer().refreshBudgetValueForThisNodeAndParents(newNode);

            // Moved here in order to have items already renderer in order to select the proper element to focus
            reloadTreeUIAfterChanges();

            if (node.isLeaf() && !node.isEmptyLeaf()) {
                // Then a new container will be created
                nameTextbox = getRenderer().getNameTextbox(node);
            } else {
                // Select the parent row to add new children ASAP

                /*
                 * Unnecessary to call methods, because org.zkoss.zul.Tree API was changed
                 * tree.setSelectedItem(getRenderer().getTreeitemForNode(node));
                 */
            }
        } else {
            getModel().addElement(name.getValue(), hours.getValue());

            // This is needed in both parts of the if, but it's repeated in order to simplify the code
            reloadTreeUIAfterChanges();
        }
    } catch (IllegalStateException e) {
        LOG.warn("exception ocurred adding element", e);
        messagesForUser.showMessage(Level.ERROR, e.getMessage());
    }

    name.setValue("");
    hours.setValue(0);

    if (nameTextbox != null) {
        nameTextbox.focus();
    } else {
        name.focus();
    }
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleProducer(final CommandProducer cmdProducer) {
    checkArgument(state == State.Connected);
    CompletableFuture<Boolean> authorizationFuture;
    if (service.isAuthorizationEnabled()) {
        authorizationFuture = service.getAuthorizationManager()
                .canProduceAsync(DestinationName.get(cmdProducer.getTopic().toString()), authRole);
    } else {/*ww  w  . j a  va 2s  . c  o  m*/
        authorizationFuture = CompletableFuture.completedFuture(true);
    }

    // Use producer name provided by client if present
    final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName()
            : service.generateUniqueProducerName();
    final String topicName = cmdProducer.getTopic();
    final long producerId = cmdProducer.getProducerId();
    final long requestId = cmdProducer.getRequestId();
    authorizationFuture.thenApply(isAuthorized -> {
        if (isAuthorized) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Client is authorized to Produce with role {}", remoteAddress, authRole);
            }
            CompletableFuture<Producer> producerFuture = new CompletableFuture<>();
            CompletableFuture<Producer> existingProducerFuture = producers.putIfAbsent(producerId,
                    producerFuture);

            if (existingProducerFuture != null) {
                if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) {
                    Producer producer = existingProducerFuture.getNow(null);
                    log.info("[{}] Producer with the same id is already created: {}", remoteAddress, producer);
                    ctx.writeAndFlush(Commands.newProducerSuccess(requestId, producer.getProducerName()));
                    return null;
                } else {
                    // There was an early request to create a producer with
                    // same producerId. This can happen when
                    // client
                    // timeout is lower the broker timeouts. We need to wait
                    // until the previous producer creation
                    // request
                    // either complete or fails.
                    ServerError error = !existingProducerFuture.isDone() ? ServerError.ServiceNotReady
                            : getErrorCode(existingProducerFuture);
                    log.warn("[{}][{}] Producer is already present on the connection", remoteAddress,
                            topicName);
                    ctx.writeAndFlush(Commands.newError(requestId, error,
                            "Producer is already present on the connection"));
                    return null;
                }
            }

            log.info("[{}][{}] Creating producer. producerId={}", remoteAddress, topicName, producerId);

            service.getTopic(topicName).thenAccept((Topic topic) -> {
                // Before creating producer, check if backlog quota exceeded
                // on topic
                if (topic.isBacklogQuotaExceeded(producerName)) {
                    IllegalStateException illegalStateException = new IllegalStateException(
                            "Cannot create producer on topic with backlog quota exceeded");
                    BacklogQuota.RetentionPolicy retentionPolicy = topic.getBacklogQuota().getPolicy();
                    if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) {
                        ctx.writeAndFlush(
                                Commands.newError(requestId, ServerError.ProducerBlockedQuotaExceededError,
                                        illegalStateException.getMessage()));
                    } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) {
                        ctx.writeAndFlush(
                                Commands.newError(requestId, ServerError.ProducerBlockedQuotaExceededException,
                                        illegalStateException.getMessage()));
                    }
                    producerFuture.completeExceptionally(illegalStateException);
                    producers.remove(producerId, producerFuture);
                    return;
                }

                disableTcpNoDelayIfNeeded(topicName, producerName);

                Producer producer = new Producer(topic, ServerCnx.this, producerId, producerName, authRole);

                try {
                    topic.addProducer(producer);

                    if (isActive()) {
                        if (producerFuture.complete(producer)) {
                            log.info("[{}] Created new producer: {}", remoteAddress, producer);
                            ctx.writeAndFlush(Commands.newProducerSuccess(requestId, producerName));
                            return;
                        } else {
                            // The producer's future was completed before by
                            // a close command
                            producer.closeNow();
                            log.info("[{}] Cleared producer created after timeout on client side {}",
                                    remoteAddress, producer);
                        }
                    } else {
                        producer.closeNow();
                        log.info("[{}] Cleared producer created after connection was closed: {}", remoteAddress,
                                producer);
                        producerFuture.completeExceptionally(
                                new IllegalStateException("Producer created after connection was closed"));
                    }
                } catch (BrokerServiceException ise) {
                    log.error("[{}] Failed to add producer to topic {}: {}", remoteAddress, topicName,
                            ise.getMessage());
                    ctx.writeAndFlush(Commands.newError(requestId,
                            BrokerServiceException.getClientErrorCode(ise), ise.getMessage()));
                    producerFuture.completeExceptionally(ise);
                }

                producers.remove(producerId, producerFuture);
            }).exceptionally(exception -> {
                Throwable cause = exception.getCause();
                if (!(cause instanceof ServiceUnitNotReadyException)) {
                    // Do not print stack traces for expected exceptions
                    log.error("[{}] Failed to create topic {}", remoteAddress, topicName, exception);
                }

                // If client timed out, the future would have been completed
                // by subsequent close. Send error back to
                // client, only if not completed already.
                if (producerFuture.completeExceptionally(exception)) {
                    ctx.writeAndFlush(Commands.newError(requestId,
                            BrokerServiceException.getClientErrorCode(cause), cause.getMessage()));
                }
                producers.remove(producerId, producerFuture);

                return null;
            });
        } else {
            String msg = "Client is not authorized to Produce";
            log.warn("[{}] {} with role {}", remoteAddress, msg, authRole);
            ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg));
        }
        return null;
    });
}

From source file:com.svpino.longhorn.fragments.StockListFragment.java

public void refreshStockInformation(List<Stock> stocks) {
    try {// w w  w  .ja  va  2 s . co  m
        for (Stock stock : stocks) {
            View view = findTile(stock);
            StockTileViewHolder stockTileViewHolder = (StockTileViewHolder) view.getTag();
            if (stockTileViewHolder != null) {
                stockTileViewHolder.refresh(getResources(), stock);
            }

            if (this.viewFlipper != null && this.viewFlipper.getTag() != null) {
                StockOverviewLayout stockOverviewLayout = (StockOverviewLayout) this.viewFlipper
                        .getChildAt(this.viewFlipper.getDisplayedChild());
                if (stockOverviewLayout != null
                        && stockOverviewLayout.getStock().getSymbol().equals(stock.getSymbol())) {
                    stockOverviewLayout.setStock(stock);
                }
            }
        }
    } catch (IllegalStateException e) {
        /*
         * For some reason, some devices are reporting an IllegalStateException when trying to
         * access the method
         * getResources() from above. The full error message is the following:
         * java.lang.IllegalStateException: Fragment StockListFragment{40540d98} not attached to
         * Activity
         * 
         * Since this error happens while refreshing the stock information, I'm going to ignore
         * it.
         */

        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

From source file:org.eclipse.gyrex.server.internal.roles.ServerRole.java

/**
 * @param applicationId//from w  ww  .j  ava  2  s .  co m
 */
private void stopApplication(final String applicationId) {
    if (BootDebug.roles) {
        LOG.debug("Stopping application {}", applicationId);
    }
    try {
        final ApplicationHandle handle = launchedApps.get(applicationId);
        if (null == handle) {
            LOG.warn("Application handle for application {} not found! Unable to stop application.",
                    applicationId);
            return;
        }

        // shutdown the app
        try {
            handle.destroy();
        } catch (final IllegalStateException e) {
            // this is thrown when the service is not unregistered
            if (BootDebug.roles) {
                LOG.debug("Application {} not active.", applicationId);
            }
        }

        // wait for application to shutdown
        long timeout = 2000l;
        String state = null;
        try {
            do {
                state = handle.getState();
                if (BootDebug.roles) {
                    LOG.debug("Application {} state: {}", applicationId, state);
                }
                if (StringUtils.equals(state, ApplicationHandle.STOPPING)) {
                    try {
                        timeout -= 150;
                        Thread.sleep(150);
                    } catch (final InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            } while ((timeout > 0) && StringUtils.equals(state, ApplicationHandle.STOPPING));
        } catch (final IllegalStateException e) {
            // this is thrown when the service has been unregistered
            if (BootDebug.roles) {
                LOG.debug("Application {} state {}: {}", new Object[] { applicationId, state, e.getMessage() });
            }
        }

        // log warning if it didn't stop
        if (StringUtils.equals(state, ApplicationHandle.STOPPING)) {
            LOG.warn(
                    "Application {} still in STOPPING state after waiting for ordered shutdown. Server role {} might not be shutdown cleanly!",
                    new Object[] { applicationId, state, getId() });
        } else if (BootDebug.roles) {
            LOG.debug("Application {} stopped.", applicationId);
        }
    } catch (final Exception e) {
        LOG.warn("Error during shutdown of application {} while deactivating role {}. {}",
                new Object[] { applicationId, getId(), e.getMessage() }, e);
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//* w w w . j  a  v  a2 s. c o  m*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:org.camunda.bpm.engine.test.api.externaltask.ExternalTaskServiceTest.java

@Deployment(resources = "org/camunda/bpm/engine/test/api/externaltask/ExternalTaskServiceTest.testFetchVariables.bpmn20.xml")
public void testShouldNotFetchSerializedVariables() {
    // given//from w  ww.ja  va 2s .c  o m
    ExternalTaskCustomValue customValue = new ExternalTaskCustomValue();
    customValue.setTestValue("value1");
    runtimeService.startProcessInstanceByKey("subProcessExternalTask",
            Variables.createVariables().putValue("processVar1", customValue));

    // when
    List<LockedExternalTask> externalTasks = externalTaskService.fetchAndLock(1, WORKER_ID)
            .topic(TOPIC_NAME, LOCK_TIME).variables("processVar1").execute();

    // then
    LockedExternalTask task = externalTasks.get(0);
    VariableMap variables = task.getVariables();
    assertEquals(1, variables.size());

    try {
        variables.get("processVar1");
        fail("did not receive an exception although variable was serialized");
    } catch (IllegalStateException e) {
        assertEquals("Object is not deserialized.", e.getMessage());
    }
}

From source file:ch.entwine.weblounge.kernel.site.SiteDispatcherServiceImpl.java

/**
 * Removes a site from the dispatcher./*from  ww  w  .  j  a va2 s.c om*/
 * 
 * @param site
 *          the site to remove
 */
private void removeSite(Site site) {
    // Remove site dispatcher servlet
    ServiceRegistration servletRegistration = servletRegistrations.remove(site);

    try {
        servletRegistration.unregister();
    } catch (IllegalStateException e) {
        // Never mind, the service has been unregistered already
    } catch (Throwable t) {
        logger.error("Unregistering site '{}' failed: {}", site.getIdentifier(), t.getMessage());
    }

    // We are no longer interested in site events
    site.removeSiteListener(this);

    // Stop the site's precompiler
    Precompiler compiler = precompilers.get(site);
    if (compiler != null) {
        if (compiler.isRunning()) {
            compiler.stop();
        } else if (preferencesService != null) {
            Preferences preferences = preferencesService.getSystemPreferences();
            String date = WebloungeDateFormat.formatStatic(new Date());
            preferences.put(compiler.getCompilerKey(), date);
            try {
                preferences.flush();
            } catch (BackingStoreException e) {
                logger.warn("Failed to store precompiler results: {}", e.getMessage());
            }
        } else if (preferencesService == null) {
            logger.warn("Unable to store precompiler results: preference service unavailable");
        }
    }

    siteServlets.remove(site);

    // TODO: unregister site dispatcher

    logger.debug("Site {} unregistered", site);
}