Example usage for java.lang ClassCastException getMessage

List of usage examples for java.lang ClassCastException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:fr.landel.utils.commons.CastUtilsTest.java

/**
 * Check cast an object/*from  w  w  w . j  a  v a  2  s  . co  m*/
 */
@Test
public void testCastObject() {
    ExException map = new ExException("msg");

    assertNull(CastUtils.cast(null));

    try {
        int num = CastUtils.cast((Object) 12);
        assertEquals(12, num);
    } catch (ClassCastException e) {
        fail(e.getMessage());
    }

    try {
        int num = CastUtils.cast(map);
        fail("Map cannot be casted into: " + num);
    } catch (ClassCastException e) {
        assertNotNull(e);
    }
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {/*  w w  w.  java2 s  . c  o m*/
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

        upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setFileSizeMax(maxFileSize);

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}

From source file:org.springframework.boot.actuate.endpoint.annotation.AnnotationEndpointDiscoverer.java

private boolean isFilterMatch(EndpointFilter<T> filter, EndpointInfo<T> endpointInfo) {
    try {/*from  w w w . ja va2 s.c  o m*/
        return filter.match(endpointInfo, this);
    } catch (ClassCastException ex) {
        String msg = ex.getMessage();
        if (msg == null || msg.startsWith(endpointInfo.getClass().getName())) {
            // Possibly a lambda-defined listener which we could not resolve the
            // generic event type for
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Non-matching info type for filter: " + filter, ex);
            }
            return false;
        }
        throw ex;
    }

}

From source file:de.xirp.ui.widgets.panels.LiveChartComposite.java

/**
 * Initializes the datapool./*from w  ww . j  a v  a  2  s  . co m*/
 */
private void initDatapool() {
    try {
        pool = DatapoolManager.getDatapool(robotName);
    } catch (DatapoolException e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }

    listener = new DatapoolListener() {

        public void valueChanged(DatapoolEvent e) {
            try {
                addValueToChart(e.getKey(), (Number) e.getValue(), e.getTimestamp());
            } catch (ClassCastException ex) {
                logClass.info("Error: " + ex.getMessage() + " (check your protocol for key: " + e.getKey() + ")" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + Constants.LINE_SEPARATOR, ex);
            }
        }

        public boolean notifyOnlyWhenChanged() {
            return false;
        }
    };
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    System.out.println(conn + " [proxy<-origin] input ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.RESPONSE_RECEIVED && connState != ConnState.RESPONSE_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }//from w  w  w  .  j  a va  2 s.  c o  m

        final Response response = proxyTask.getResponse();
        try {

            ByteBuffer dst = proxyTask.getOutBuffer();
            int bytesRead = decoder.read(dst);
            if (bytesRead > 0) {
                dst.flip();
                final ByteChunk chunk = new ByteChunk(bytesRead);
                final byte[] buf = new byte[bytesRead];
                dst.get(buf);
                chunk.setBytes(buf, 0, bytesRead);
                dst.compact();
                try {
                    response.doWrite(chunk);
                } catch (ClassCastException e) {
                    System.err.println("gone bad: " + e.getMessage());
                    e.printStackTrace(System.err);
                }
                response.flush();
                System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
                System.out.println(conn + " [proxy<-origin] " + decoder);
            }
            if (!dst.hasRemaining()) {
                // Output buffer is full. Suspend origin input until
                // the client handler frees up some space in the buffer
                conn.suspendInput();
            }
            /*
                    // If there is some content in the buffer make sure client output
                    // is active
                    if (dst.position() > 0) {
                      proxyTask.getClientIOControl().requestOutput();
                    }
            */

            if (decoder.isCompleted()) {
                System.out.println(conn + " [proxy<-origin] response body received");
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
                if (!this.connStrategy.keepAlive(conn.getHttpResponse(), context)) {
                    System.out.println(conn + " [proxy<-origin] close connection");
                    proxyTask.setOriginState(ConnState.CLOSING);
                    conn.close();
                }
                proxyTask.getCompletion().run();
            } else {
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}

From source file:org.apache.pig.impl.logicalLayer.LOLoad.java

public void setInputFile(FileSpec inputFileSpec) throws IOException {
    try {/*from ww  w . ja v a2 s  .  com*/
        mLoadFunc = (LoadFunc) PigContext.instantiateFuncFromSpec(inputFileSpec.getFuncSpec());
    } catch (ClassCastException cce) {
        log.error(inputFileSpec.getFuncSpec() + " should implement the LoadFunc interface.");
        IOException ioe = new IOException(cce.getMessage());
        ioe.setStackTrace(cce.getStackTrace());
        throw ioe;
    } catch (Exception e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
    mInputFileSpec = inputFileSpec;
}

From source file:pe.com.mmh.sisgap.utils.BasicDynaBean.java

/**
 * Set the value of an indexed property with the specified name.
 *
 * @param name Name of the property whose value is to be set
 * @param index Index of the property to be set
 * @param value Value to which this property is to be set
 *
 * @exception ConversionException if the specified value cannot be
 *  converted to the type required for this property
 * @exception IllegalArgumentException if there is no property
 *  of the specified name/*from   ww  w .j a v  a 2s  . c  o  m*/
 * @exception IllegalArgumentException if the specified property
 *  exists, but is not indexed
 * @exception IndexOutOfBoundsException if the specified index
 *  is outside the range of the underlying property
 */
public void set(String name, int index, Object value) {

    Object prop = values.get(name);
    if (prop == null) {
        throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
    } else if (prop.getClass().isArray()) {
        Array.set(prop, index, value);
    } else if (prop instanceof List) {
        try {
            ((List) prop).set(index, value);
        } catch (ClassCastException e) {
            throw new ConversionException(e.getMessage());
        }
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }

}

From source file:com.ottogroup.bi.asap.pipeline.MicroPipelineFactory.java

/**
 * Returns the {@link DelayedResponseWaitStrategy} according to the provided configuration
 * @param configuration//from w  w  w  . j a v  a 2s .com
 * @return
 * @throws RequiredInputMissingException
 * @throws ComponentInstantiationFailedException 
 * @throws UnknownComponentException 
 */
protected DelayedResponseWaitStrategy getDelayedResponseWaitStrategy(
        final DelayedResponseWaitStrategyConfiguration configuration)
        throws RequiredInputMissingException, ComponentInstantiationFailedException, UnknownComponentException {

    /////////////////////////////////////////////////////////////
    // validate input
    if (configuration == null)
        throw new RequiredInputMissingException("Missing required configuration");
    if (StringUtils.isBlank(configuration.getId()))
        throw new RequiredInputMissingException("Missing required strategy id");
    if (StringUtils.isBlank(configuration.getName()))
        throw new RequiredInputMissingException("Missing required strategy name");
    if (StringUtils.isBlank(configuration.getVersion()))
        throw new RequiredInputMissingException("Missing required strategy version");
    //
    /////////////////////////////////////////////////////////////

    try {
        return (DelayedResponseWaitStrategy) componentRepository.newInstance(configuration.getId(),
                configuration.getName(), configuration.getVersion(), configuration.getSettings());
    } catch (ClassCastException e) {
        throw new ComponentInstantiationFailedException(
                "Failed to convert retrieved instance to mailbox representation. Error: " + e.getMessage());
    }
}

From source file:com.ottogroup.bi.asap.pipeline.MicroPipelineFactory.java

/**
 * Returns the {@link Mailbox} implementation according to the provided configuration
 * @param configuration/*from  ww  w.  j ava  2  s  . co  m*/
 * @return
 * @throws RequiredInputMissingException
 * @throws UnknownComponentException 
 * @throws ComponentInstantiationFailedException 
 */
protected Mailbox getMailbox(final MailboxConfiguration configuration)
        throws RequiredInputMissingException, ComponentInstantiationFailedException, UnknownComponentException {

    /////////////////////////////////////////////////////////////
    // return default mailbox if no configuration is provided
    if (configuration == null) {
        return getDefaultMailbox();
    }
    //
    /////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(configuration.getId()))
        throw new RequiredInputMissingException("Missing required mailbox id");
    if (StringUtils.isBlank(configuration.getName()))
        throw new RequiredInputMissingException("Missing required mailbox name");
    if (StringUtils.isBlank(configuration.getVersion()))
        throw new RequiredInputMissingException("Missing required mailbox version");
    //
    /////////////////////////////////////////////////////////////

    try {
        return (Mailbox) componentRepository.newInstance(configuration.getId(), configuration.getName(),
                configuration.getVersion(), configuration.getSettings());
    } catch (ClassCastException e) {
        throw new ComponentInstantiationFailedException(
                "Failed to convert retrieved instance to mailbox representation. Error: " + e.getMessage());
    }
}

From source file:org.rifidi.edge.readerplugin.llrp.LLRPReaderSession.java

/**
 * This logic executes as soon as a socket is established to initialize the
 * connection. It occurs before any commands are scheduled
 *///  w w  w  .j  av a2  s  . c om
private void onConnect() {
    logger.info(">>>>>>>>>>>>>>>>>>>LLRP Session " + this.getID() + " on sensor " + this.getSensor().getID()
            + " attempting to log in to " + host + ":" + port);
    setStatus(SessionStatus.LOGGINGIN);
    executor = new ScheduledThreadPoolExecutor(1);

    try {
        SET_READER_CONFIG config = createSetReaderConfig();
        config.setMessageID(new UnsignedInteger(messageID++));

        SET_READER_CONFIG_RESPONSE config_response = (SET_READER_CONFIG_RESPONSE) connection.transact(config);

        // modified by limg00n

        //---------------
        StatusCode sc = config_response.getLLRPStatus().getStatusCode();
        if (sc.intValue() != StatusCode.M_Success) {
            if (config_response.getLLRPStatus().getStatusCode().toInteger() != 0) {
                try {
                    logger.error("Problem with SET_READER_CONFIG: \n" + config_response.toXMLString());
                } catch (InvalidLLRPMessageException e) {
                    logger.warn("Cannot print XML for " + "SET_READER_CONFIG_RESPONSE");
                }
            }
        }

        if (!processing.compareAndSet(false, true)) {
            logger.warn("Executor was already active! ");
        }
        submit(getTimeoutCommand(), 10, TimeUnit.SECONDS);
        setStatus(SessionStatus.PROCESSING);

    } catch (TimeoutException e) {
        logger.error(e.getMessage());
        disconnect();
    } catch (ClassCastException ex) {
        logger.error(ex.getMessage());
        disconnect();
    }

}