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:com.snaplogic.snaps.firstdata.Create.java

@Override
protected void process(Document document, String viewname) {
    Object requestObj;/*from   w  ww  . j  ava 2  s.c  om*/
    Object data;
    if ((data = document.get()) != null) {
        /*
         * Process the input data if and only if it is of Map
         */
        if (data instanceof Map) {
            String claszPath = getGMFReqClassType();
            Object map = Map.class.cast(data).get(getGMFReqClassName());
            Map<String, Object> inputMap = Map.class.cast(map);
            requestObj = getObject(claszPath, inputMap);
            if (inputMap.containsKey(ADDTL_AMT_GRP)) {
                try {
                    List<Map<String, Object>> inputList = List.class.cast(inputMap.get(ADDTL_AMT_GRP));
                    if (inputList != null) {
                        requestObj = prepareListObj(requestObj, claszPath, ADDTL_AMT_GRP, inputList);
                    }
                } catch (ClassCastException e) {
                    Map<String, Object> inputPair = Map.class.cast(inputMap.get(ADDTL_AMT_GRP));
                    requestObj = prepareListObj(requestObj, claszPath, ADDTL_AMT_GRP, inputPair);
                }
            }
            if (inputMap.containsKey(PROD_CODE_DET_GRP)) {
                try {
                    List<Map<String, Object>> inputList = List.class.cast(inputMap.get(PROD_CODE_DET_GRP));
                    if (inputList != null) {
                        requestObj = prepareListObj(requestObj, claszPath, PROD_CODE_DET_GRP, inputList);
                    }
                } catch (ClassCastException e) {
                    Map<String, Object> inputPair = Map.class.cast(inputMap.get(PROD_CODE_DET_GRP));
                    requestObj = prepareListObj(requestObj, claszPath, PROD_CODE_DET_GRP, inputPair);
                }
            }

            String xmlData = null;
            try {
                /* Using Reflection and JAXB to prepare SOAP request XML */
                Class<?> gmfmv = Class.forName(GMF_MESSAGE_VARIANTS);
                Object gmfmvObj = gmfmv.newInstance();
                Method gmfMethod = gmfmv.getMethod(String.format(SETTER, getGMFVarient(resourceType)),
                        getClassType(claszPath));
                gmfMethod.invoke(gmfmvObj, requestObj);
                /* converting simple java objects into XML format using JAXB */
                xmlData = getGMFXMLRequestData((GMFMessageVariants) gmfmvObj);
                xmlData = xmlData.replaceAll(GMF_MESSAGE_VARIANTS_TAG, GMF_TAG);
                xmlData = xmlData.replaceAll(NAMESPACE_NS1, StringUtils.EMPTY);
                xmlData = xmlData.replaceAll(NAMESPACE_NS2, StringUtils.EMPTY);
                log.debug(xmlData);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                writeToErrorView(e.getMessage(), REQUEST_FAILED, ERROR_RESOLUTION, e);
                return;
            }
            AccountBean bean = account.connect();
            try {
                /*
                 * Create the instance of the RequestType that is a class generated from the
                 * Rapid connect Transaction Service WSDL file [rc.wsdl]
                 */
                RequestType requestType = new RequestType();
                /* Set client timeout value of request object. */
                requestType.setClientTimeout(new BigInteger(String.valueOf(bean.getTimeOut())));
                /*
                 * Create the instance of the ReqClientIDType that is a class generated from the
                 * Rapid connect Transaction Service WSDL file [rc.wsdl]
                 */
                ReqClientIDType reqClientIDType = new ReqClientIDType();
                reqClientIDType.setApp(bean.getAppID());
                reqClientIDType.setAuth(bean.getAuthString());
                String clientRef = getClientRef(requestObj, claszPath);
                reqClientIDType.setClientRef(clientRef);
                reqClientIDType.setDID(bean.getDatawireId());
                /* Assign ReqClientID value to the requesttype object */
                requestType.setReqClientID(reqClientIDType);
                /*
                 * Create the instance of the TransactionType that is a class generated from the
                 * Rapid connect Transaction Service WSDL file [rc.wsdl]
                 */
                TransactionType transactionType = new TransactionType();
                /*
                 * Create the instance of the PayloadType that is a class generated from the
                 * Rapid connect Transaction Service WSDL file [rc.wsdl]
                 */
                PayloadType payloadType = new PayloadType();
                payloadType.setEncoding(CDATA);
                payloadType.setValue(xmlData); // actual xml request
                transactionType.setPayload(payloadType);
                transactionType.setServiceID(String.valueOf(bean.getServiceID()));
                /* Set transaction type */
                requestType.setTransaction(transactionType);
                /* Set version number of the request */
                requestType.setVersion(VERSION);
                /* The response to be returned. */
                String gmfResponse = null;
                /*
                 * Create the instance of the RcService that is a class generated from the Rapid
                 * connect Transaction Service WSDL file [rc.wsdl]
                 */
                URL wsdlUrl = new URL(bean.getServiceWSDLURL());
                RcService.setWsdlURL(wsdlUrl);
                RcService rcService = new RcService();
                /*
                 * Create the instance of the RcPortType that is a class generated from the
                 * Rapid connect Transaction Service WSDL file [rc.wsdl]
                 */
                RcPortType port = rcService.getRcServicePort();
                /* The URL that will receive the XML request data. */
                /* Bind the URL using Binding Provider */
                ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                        bean.getServiceURL());
                /* Perform actual send operation for the request. */
                ResponseType responseType = port.rcTransaction(requestType);
                /* Parse the response received from the URL */
                StatusType statusType;
                if (responseType != null && (statusType = responseType.getStatus()) != null) {
                    String statuCode = statusType.getStatusCode();
                    if (statuCode != null && statuCode.equals(STATUS_OK)) {
                        TransactionResponseType trType = responseType.getTransactionResponse();
                        PayloadType pType;
                        if (trType != null && (pType = trType.getPayload()) != null) {
                            String encoding = pType.getEncoding();
                            if (encoding != null && encoding.equals(CDATA)) {
                                /*
                                 * Extract pay load - the response from data wire for cdata
                                 * encoding.
                                 */
                                gmfResponse = pType.getValue();
                            } else if (encoding.equalsIgnoreCase(XML_ESCAPE)) {
                                /*
                                 * Extract pay load - the response from data wire for xml_escape
                                 * encoding.
                                 */
                                gmfResponse = pType.getValue().replaceAll(GT, GT_SYM).replaceAll(LT, LT_SYM)
                                        .replaceAll(AMP, AMP_SYM);
                            }
                            outputViews.write(documentUtility.newDocument(getJsonFromXML(gmfResponse)));
                            counter.inc();
                        } else {
                            writeToErrorView(NULL_TRANSACTION_RESPONSE,
                                    responseType.getStatus().getStatusCode(), VALIDATE_INPUT_DATA,
                                    responseType.getStatus().getValue());
                        }
                    } else {
                        writeToErrorView(INVALID_RESPONSE, responseType.getStatus().getStatusCode(),
                                VALIDATE_INPUT_DATA, responseType.getStatus().getValue());
                    }
                } else {
                    writeToErrorView(EMPTY_RESPONSE, IMPROPER_INPUT, VALIDATE_INPUT_DATA, NULL_OBJECT);
                }
            } catch (Exception ex) {
                writeToErrorView(ERRORMSG, ex.getMessage(), ERROR_RESOLUTION, ex);
            }
        } else {
            writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION);
        }
    } else {
        writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION);
    }
}

From source file:com.snaplogic.snaps.firstdata.Transaction.java

@Override
public void execute() throws ExecutionException {
    Map<String, InputView> inputViewMap = inputViews.getAll();
    InputView payloadInputView = inputViewMap.get(DEFAULT_INPUT_VIEW_1);
    InputView authInputView = inputViewMap.get(DEFAULT_INPUT_VIEW_0);
    PeekingDocumentIterator payloadInputViewIterator = null;
    Document payloadInputDoc = null;
    if (payloadInputView != null) {
        payloadInputViewIterator = new PeekingDocumentIterator(inputViews.getDocumentsFrom(payloadInputView),
                DEFAULT_INPUT_VIEW_1);//ww  w . ja  v  a2  s  .  c  o  m
        if (payloadInputViewIterator != null && payloadInputViewIterator.hasNext()) {
            payloadInputDoc = payloadInputViewIterator.next();
        }
    }
    Object requestObj;
    Object inputData;
    if ((inputData = payloadInputDoc.get()) != null) {
        /*
         * Process the input data if and only if it is of Map
         */
        if (inputData instanceof Map) {
            String claszPath = getGMFReqClassType();
            Object map = Map.class.cast(inputData).get(getGMFReqClassName());
            Map<String, Object> inputMap = Map.class.cast(map);
            requestObj = getObject(claszPath, inputMap);
            if (inputMap.containsKey(ADDTL_AMT_GRP)) {
                try {
                    List<Map<String, Object>> inputList = List.class.cast(inputMap.get(ADDTL_AMT_GRP));
                    if (inputList != null) {
                        requestObj = prepareListObj(requestObj, claszPath, ADDTL_AMT_GRP, inputList);
                    }
                } catch (ClassCastException e) {
                    Map<String, Object> inputPair = Map.class.cast(inputMap.get(ADDTL_AMT_GRP));
                    requestObj = prepareListObj(requestObj, claszPath, ADDTL_AMT_GRP, inputPair);
                }
            }
            if (inputMap.containsKey(PROD_CODE_DET_GRP)) {
                try {
                    List<Map<String, Object>> inputList = List.class.cast(inputMap.get(PROD_CODE_DET_GRP));
                    if (inputList != null) {
                        requestObj = prepareListObj(requestObj, claszPath, PROD_CODE_DET_GRP, inputList);
                    }
                } catch (ClassCastException e) {
                    Map<String, Object> inputPair = Map.class.cast(inputMap.get(PROD_CODE_DET_GRP));
                    requestObj = prepareListObj(requestObj, claszPath, PROD_CODE_DET_GRP, inputPair);
                }
            }

            String xmlData = null;
            try {
                /* Using Reflection and JAXB to prepare SOAP request XML */
                Class<?> gmfmv = Class.forName(GMF_MESSAGE_VARIANTS);
                Object gmfmvObj = gmfmv.newInstance();
                Method gmfMethod = gmfmv.getMethod(String.format(SETTER, getGMFVarient(resourceType)),
                        getClassType(claszPath));
                gmfMethod.invoke(gmfmvObj, requestObj);
                /* converting simple java objects into XML format using JAXB */
                xmlData = getGMFXMLRequestData((GMFMessageVariants) gmfmvObj);
                xmlData = xmlData.replaceAll(GMF_MESSAGE_VARIANTS_TAG, GMF_TAG);
                xmlData = xmlData.replaceAll(NAMESPACE_NS1, NAMESPACE_S1);
                xmlData = xmlData.replaceAll(NAMESPACE_NS2, NAMESPACE_S2);
                log.debug(xmlData);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                writeToErrorView(e.getMessage(), REQUEST_FAILED, ERROR_RESOLUTION, e);
                return;
            }

            PeekingDocumentIterator authInputViewIterator = null;
            Document document = null;
            Map<String, Object> requestData = null;
            if (authInputView != null) {
                authInputViewIterator = new PeekingDocumentIterator(inputViews.getDocumentsFrom(authInputView),
                        DEFAULT_INPUT_VIEW_0);
                if (authInputViewIterator != null && authInputViewIterator.hasNext()) {
                    document = authInputViewIterator.next();
                    if ((requestData = (Map<String, Object>) document.get()) != null) {
                        Map dataSet = new HashMap();
                        dataSet.put("Encoding", "cdata");
                        dataSet.put("value", xmlData);
                        Map payload = new HashMap();
                        payload.put("Payload", dataSet);
                        requestData.put("Transaction", payload);
                    }
                    document.set(requestData);
                }
            }

            String envelope = null;
            String strippedEnvelope = null;
            try {
                envelope = editorProperty.eval(document);
                log.info(DISPATCHING_SOAP_REQUEST, envelope);
                SOAPMessage soapResponse = invocationService.call(clientBuilder, envelope);
                if (soapResponse == null) {
                    return;
                }
                Object data = invocationService.serialize(soapResponse);
                if (data != null) {
                    outputViews.write(documentUtility.newDocument(data), document);
                    counter.inc();
                }
            } catch (XMLStreamException e) {
                throw new ExecutionException(e, XML_SERIALIZATION_FAILED).withResolutionAsDefect();
            } catch (Exception e) {
                Throwable rootCause = Throwables.getRootCause(e);
                String reason = rootCause.getMessage();
                Map<String, Object> errorMap = Maps.newHashMap();
                errorMap.put(KEY_ERROR, reason);
                SnapDataException dataException = new SnapDataException(documentUtility.newDocument(errorMap),
                        EXCEPTION_OCCURRED).withReason(reason).withResolution(SOAP_EXCEPTION_RESOLUTION);
                if (envelope != null) {
                    errorMap.put(KEY_ENVELOPE, parseXML2JSON(envelope, xmlUtils));
                }
                if (strippedEnvelope != null) {
                    errorMap.put(KEY_STRIPPED_ENVELOPE, parseXML2JSON(strippedEnvelope, xmlUtils));
                }
                errorViews.write(dataException, document);
            }
        }
    }
}

From source file:mondrian.rolap.RolapConnection.java

/**
 * Creates a RolapConnection./* ww w  .  j  a va 2s .com*/
 *
 * <p>Only {@link RolapSchemaPool#get} calls this with
 * schema != null (to create a schema's internal connection).
 * Other uses retrieve a schema from the cache based upon
 * the <code>Catalog</code> property.
 *
 * @param server Server instance this connection belongs to
 * @param connectInfo Connection properties; keywords are described in
 *   {@link RolapConnectionProperties}.
 * @param schema Schema for the connection. Must be null unless this is to
 *   be an internal connection.
 * @param dataSource If not null an external DataSource to be used
 *        by Mondrian
 */
RolapConnection(MondrianServer server, Util.PropertyList connectInfo, RolapSchema schema,
        DataSource dataSource) {
    super();
    assert server != null;
    this.server = server;
    this.id = ID_GENERATOR.getAndIncrement();

    assert connectInfo != null;
    String provider = connectInfo.get(RolapConnectionProperties.Provider.name(), "mondrian");
    Util.assertTrue(provider.equalsIgnoreCase("mondrian"));
    this.connectInfo = connectInfo;
    this.catalogUrl = connectInfo.get(RolapConnectionProperties.Catalog.name());
    final String jdbcUser = connectInfo.get(RolapConnectionProperties.JdbcUser.name());
    final String jdbcConnectString = connectInfo.get(RolapConnectionProperties.Jdbc.name());
    final String strDataSource = connectInfo.get(RolapConnectionProperties.DataSource.name());
    StringBuilder buf = new StringBuilder();
    this.dataSource = createDataSource(dataSource, connectInfo, buf);
    Role role = null;

    // Register this connection before we register its internal statement.
    server.addConnection(this);

    if (schema == null) {
        // If RolapSchema.Pool.get were to call this with schema == null,
        // we would loop.
        Statement bootstrapStatement = createInternalStatement(false);
        final Locus locus = new Locus(new Execution(bootstrapStatement, 0), null, "Initializing connection");
        Locus.push(locus);
        try {
            if (dataSource == null) {
                // If there is no external data source is passed in, we
                // expect the properties Jdbc, JdbcUser, DataSource to be
                // set, as they are used to generate the schema cache key.
                final String connectionKey = jdbcConnectString + getJdbcProperties(connectInfo).toString();

                schema = RolapSchemaPool.instance().get(catalogUrl, connectionKey, jdbcUser, strDataSource,
                        connectInfo);
            } else {
                schema = RolapSchemaPool.instance().get(catalogUrl, dataSource, connectInfo);
            }
        } finally {
            Locus.pop(locus);
            bootstrapStatement.close();
        }
        internalStatement = schema.getInternalConnection().getInternalStatement();
        String roleNameList = connectInfo.get(RolapConnectionProperties.Role.name());
        if (roleNameList != null) {
            List<String> roleNames = Util.parseCommaList(roleNameList);
            List<Role> roleList = new ArrayList<Role>();
            for (String roleName : roleNames) {
                final LockBox.Entry entry = server.getLockBox().get(roleName);
                Role role1;
                if (entry != null) {
                    try {
                        role1 = (Role) entry.getValue();
                    } catch (ClassCastException e) {
                        role1 = null;
                    }
                } else {
                    role1 = schema.lookupRole(roleName);
                }
                if (role1 == null) {
                    throw Util.newError("Role '" + roleName + "' not found");
                }
                roleList.add(role1);
            }
            switch (roleList.size()) {
            case 0:
                // If they specify 'Role=;', the list of names will be
                // empty, and the effect will be as if they did specify
                // Role at all.
                role = null;
                break;
            case 1:
                role = roleList.get(0);
                break;
            default:
                role = RoleImpl.union(roleList);
                break;
            }
        }
    } else {
        this.internalStatement = createInternalStatement(true);

        // We are creating an internal connection. Now is a great time to
        // make sure that the JDBC credentials are valid, for this
        // connection and for external connections built on top of this.
        Connection conn = null;
        java.sql.Statement statement = null;
        try {
            conn = this.dataSource.getConnection();
            Dialect dialect = DialectManager.createDialect(this.dataSource, conn);
            if (dialect.getDatabaseProduct() == Dialect.DatabaseProduct.DERBY) {
                // Derby requires a little extra prodding to do the
                // validation to detect an error.
                statement = conn.createStatement();
                statement.executeQuery("select * from bogustable");
            }
        } catch (SQLException e) {
            if (e.getMessage().equals("Table/View 'BOGUSTABLE' does not exist.")) {
                // Ignore. This exception comes from Derby when the
                // connection is valid. If the connection were invalid, we
                // would receive an error such as "Schema 'BOGUSUSER' does
                // not exist"
            } else {
                throw Util.newError(e, "Error while creating SQL connection: " + buf);
            }
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    if (role == null) {
        role = schema.getDefaultRole();
    }

    // Set the locale.
    String localeString = connectInfo.get(RolapConnectionProperties.Locale.name());
    if (localeString != null) {
        this.locale = Util.parseLocale(localeString);
        assert locale != null;
    }

    this.schema = schema;
    setRole(role);
}

From source file:org.apache.axis2.context.MessageContext.java

/**
 * During deserialization, the executionChain will be
 * re-constituted before the SelfManagedData is restored.
 * This means the handler instances are already available.
 * This method lets us find the handler instance from the
 * executionChain so we can call each one's
 * deserializeSelfManagedData method./*from  w w  w .  j  a v a 2s .com*/
 *
 * @param it            The iterator from the executionChain object
 * @param classname     The class name
 * @param qNameAsString The QName in string form
 * @return SelfManagedDataManager handler
 */
private SelfManagedDataManager deserialize_getHandlerFromExecutionChain(Iterator<Handler> it, String classname,
        String qNameAsString) {
    SelfManagedDataManager handler_toreturn = null;

    try {
        while ((it.hasNext()) && (handler_toreturn == null)) {
            Handler handler = (Handler) it.next();

            if (handler instanceof Phase) {
                handler_toreturn = deserialize_getHandlerFromExecutionChain(
                        ((Phase) handler).getHandlers().iterator(), classname, qNameAsString);
            } else if ((handler.getClass().getName().equals(classname))
                    && (handler.getName().equals(qNameAsString))) {
                handler_toreturn = (SelfManagedDataManager) handler;
            }
        }
        return handler_toreturn;
    } catch (ClassCastException e) {
        // Doesn't seem likely to happen, but just in case...
        // A handler classname in the executionChain matched up with our parameter
        // classname, but the existing class in the executionChain is a different
        // implementation than the one we saved during serializeSelfManagedData.
        // NOTE: the exception gets absorbed!

        if (DEBUG_ENABLED && log.isTraceEnabled()) {
            log.trace("MessageContext:deserialize_getHandlerFromExecutionChain(): ClassCastException thrown: "
                    + e.getMessage(), e);
        }
        return null;
    }
}

From source file:ca.sqlpower.enterprise.JSONResponseHandler.java

public JSONMessage handleResponse(Reader reader, int status) {
    if (status == 404) {
        throw new RuntimeException("Server resource is not available.");
    }//www .j ava  2 s. c  o  m
    if (status == 403) {
        throw new AccessDeniedException("Insufficient priviledges");
    }

    JSONTokener tokener = new JSONTokener(reader);
    try {
        JSONObject message;
        try {
            message = (JSONObject) tokener.nextValue();
        } catch (ClassCastException ex) {
            StringBuffer sb = new StringBuffer();
            sb.append("Internal server error. Server responded with the following.\n");
            try {
                int charAsInt = reader.read();
                while (charAsInt != -1) {
                    sb.append((char) charAsInt);
                    charAsInt = reader.read();
                }
                logger.error(sb.toString());
            } catch (IOException e) {
                logger.error("Failed to parse the root exception. The following was received " + sb.toString());
            }
            throw new RuntimeException(
                    "Server error " + status + ". See logs or server logs for more details.");
        }

        // Does the response contain data? If so, return it. Communication
        // with the resource has been successful.
        if (message.getString("responseKind").equals("data")) {
            return new JSONMessage(message.getString("data"), status);
        } else {
            // Has the request been unsuccessful?
            if (message.getString("responseKind").equals("unsuccessful")) {
                return new JSONMessage(message.getString("data"), status);
            } else {
                // Does the response contain an exception? If so, reconstruct, and then
                // re-throw it. There has been an exception on the server.
                if (message.getString("responseKind").equals("exceptionStackTrace")) {

                    JSONArray stackTraceStrings = new JSONArray(message.getString("data"));
                    StringBuffer stackTraceMessage = new StringBuffer();

                    if (stackTraceStrings.length() > 0) {
                        String firstLine = stackTraceStrings.getString(0);
                        String userMessage = null;
                        if (firstLine.contains(FriendlyRuntimeSPPersistenceException.class.getName())) {
                            userMessage = firstLine.substring(
                                    firstLine.indexOf(FriendlyRuntimeSPPersistenceException.class.getName())
                                            + FriendlyRuntimeSPPersistenceException.class.getName().length()
                                            + 2);
                        } else if (firstLine.contains(FriendlySPPersistenceException.class.getName())) {
                            userMessage = firstLine
                                    .substring(firstLine.indexOf(FriendlySPPersistenceException.class.getName())
                                            + FriendlySPPersistenceException.class.getName().length() + 2);
                        }

                        if (userMessage != null) {
                            for (int i = 0; i < stackTraceStrings.length(); i++) {
                                stackTraceMessage.append("\n").append(stackTraceStrings.get(i));
                            }
                            logger.info(stackTraceMessage.toString());

                            throw new FriendlyRuntimeSPPersistenceException(userMessage);
                        }
                    }

                    for (int i = 0; i < stackTraceStrings.length(); i++) {
                        stackTraceMessage.append("\n").append(stackTraceStrings.get(i));
                    }

                    throw new SPPersistenceException(null, stackTraceMessage.toString());

                } else {
                    // This exception represents a(n epic) client-server miscommunication
                    throw new Exception("Unable to parse response ");
                }
            }
        }
    } catch (JSONException ex) {
        StringBuffer sb = new StringBuffer();
        sb.append("Internal server error. Server responded with the following.\n");
        try {
            int charAsInt = reader.read();
            while (charAsInt != -1) {
                sb.append(charAsInt);
                charAsInt = reader.read();
            }
            logger.error(sb.toString());
        } catch (IOException e) {
            logger.error("Failed to parse the root exception. The following was received " + sb.toString());
        }
        throw new RuntimeException("Server error. See logs or server logs for more details.");
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        String message = ex.getMessage();
        if (message.contains("\n")) {
            String[] messages = message.split("\n");
            for (String serverMsg : messages) {
                if (serverMsg.trim().length() > 0) {
                    message = serverMsg.trim();
                    break;
                }
            }
        }
        throw new RuntimeException("Server returned status " + status + "\n" + message, ex);
    }
}

From source file:ru.valle.btc.MainActivity.java

private void tryToGenerateSpendingTransaction() {
    final ArrayList<UnspentOutputInfo> unspentOutputs = verifiedUnspentOutputsForTx;
    final String outputAddress = verifiedRecipientAddressForTx;
    final long requestedAmountToSend = verifiedAmountToSendForTx;
    final KeyPair keyPair = verifiedKeyPairForTx;
    final boolean inputsComesFromJson = verifiedUnspentOutputsComesFromJson;
    final int predefinedConfirmationsCount = verifiedConfirmationsCount;

    spendTxDescriptionView.setVisibility(View.GONE);
    spendTxWarningView.setVisibility(View.GONE);
    spendTxEdit.setText("");
    spendTxEdit.setVisibility(View.GONE);
    sendTxInBrowserButton.setVisibility(View.GONE);
    findViewById(R.id.spend_tx_required_age_for_free_tx).setVisibility(View.GONE);
    //        https://blockchain.info/pushtx

    if (unspentOutputs != null && !unspentOutputs.isEmpty() && !TextUtils.isEmpty(outputAddress)
            && keyPair != null && requestedAmountToSend >= SEND_MAX && requestedAmountToSend != 0
            && !TextUtils.isEmpty(keyPair.address)) {
        cancelAllRunningTasks();//from w  w  w. ja  va 2 s  . c  o  m
        generateTransactionTask = new AsyncTask<Void, Void, GenerateTransactionResult>() {

            @Override
            protected GenerateTransactionResult doInBackground(Void... voids) {
                final Transaction spendTx;
                try {
                    long availableAmount = 0;
                    for (UnspentOutputInfo unspentOutputInfo : unspentOutputs) {
                        availableAmount += unspentOutputInfo.value;
                    }
                    long amount;
                    if (availableAmount == requestedAmountToSend || requestedAmountToSend == SEND_MAX) {
                        //transfer maximum possible amount
                        amount = -1;
                    } else {
                        amount = requestedAmountToSend;
                    }
                    long extraFee;
                    SharedPreferences preferences = PreferenceManager
                            .getDefaultSharedPreferences(MainActivity.this);
                    try {
                        extraFee = preferences.getLong(PreferencesActivity.PREF_EXTRA_FEE,
                                FeePreference.PREF_EXTRA_FEE_DEFAULT);
                    } catch (ClassCastException e) {
                        preferences.edit().remove(PreferencesActivity.PREF_EXTRA_FEE)
                                .putLong(PreferencesActivity.PREF_EXTRA_FEE,
                                        FeePreference.PREF_EXTRA_FEE_DEFAULT)
                                .commit();
                        extraFee = FeePreference.PREF_EXTRA_FEE_DEFAULT;
                    }
                    spendTx = BTCUtils.createTransaction(unspentOutputs, outputAddress, keyPair.address, amount,
                            extraFee, keyPair.publicKey, keyPair.privateKey);

                    //6. double check that generated transaction is valid
                    Transaction.Script[] relatedScripts = new Transaction.Script[spendTx.inputs.length];
                    for (int i = 0; i < spendTx.inputs.length; i++) {
                        Transaction.Input input = spendTx.inputs[i];
                        for (UnspentOutputInfo unspentOutput : unspentOutputs) {
                            if (Arrays.equals(unspentOutput.txHash, input.outPoint.hash)
                                    && unspentOutput.outputIndex == input.outPoint.index) {
                                relatedScripts[i] = unspentOutput.script;
                                break;
                            }
                        }
                    }
                    BTCUtils.verify(relatedScripts, spendTx);
                } catch (BitcoinException e) {
                    switch (e.errorCode) {
                    case BitcoinException.ERR_INSUFFICIENT_FUNDS:
                        return new GenerateTransactionResult(getString(R.string.error_not_enough_funds),
                                GenerateTransactionResult.ERROR_SOURCE_AMOUNT_FIELD);
                    case BitcoinException.ERR_FEE_IS_TOO_BIG:
                        return new GenerateTransactionResult(getString(R.string.generated_tx_have_too_big_fee),
                                GenerateTransactionResult.ERROR_SOURCE_INPUT_TX_FIELD);
                    case BitcoinException.ERR_MEANINGLESS_OPERATION://input, output and change addresses are same.
                        return new GenerateTransactionResult(getString(R.string.output_address_same_as_input),
                                GenerateTransactionResult.ERROR_SOURCE_ADDRESS_FIELD);
                    //                            case BitcoinException.ERR_INCORRECT_PASSWORD
                    //                            case BitcoinException.ERR_WRONG_TYPE:
                    //                            case BitcoinException.ERR_FEE_IS_LESS_THEN_ZERO
                    //                            case BitcoinException.ERR_CHANGE_IS_LESS_THEN_ZERO
                    //                            case BitcoinException.ERR_AMOUNT_TO_SEND_IS_LESS_THEN_ZERO
                    default:
                        return new GenerateTransactionResult(
                                getString(R.string.error_failed_to_create_transaction) + ": " + e.getMessage(),
                                GenerateTransactionResult.ERROR_SOURCE_UNKNOWN);
                    }
                } catch (Exception e) {
                    return new GenerateTransactionResult(
                            getString(R.string.error_failed_to_create_transaction) + ": " + e,
                            GenerateTransactionResult.ERROR_SOURCE_UNKNOWN);
                }

                long inValue = 0;
                for (Transaction.Input input : spendTx.inputs) {
                    for (UnspentOutputInfo unspentOutput : unspentOutputs) {
                        if (Arrays.equals(unspentOutput.txHash, input.outPoint.hash)
                                && unspentOutput.outputIndex == input.outPoint.index) {
                            inValue += unspentOutput.value;
                        }
                    }
                }
                long outValue = 0;
                for (Transaction.Output output : spendTx.outputs) {
                    outValue += output.value;
                }
                long fee = inValue - outValue;
                return new GenerateTransactionResult(spendTx, fee);
            }

            @Override
            protected void onPostExecute(GenerateTransactionResult result) {
                super.onPostExecute(result);
                generateTransactionTask = null;
                if (result != null) {
                    final TextView rawTxToSpendErr = (TextView) findViewById(R.id.err_raw_tx);
                    if (result.tx != null) {
                        String amountStr = null;
                        Transaction.Script out = null;
                        try {
                            out = Transaction.Script.buildOutput(outputAddress);
                        } catch (BitcoinException ignore) {
                        }
                        if (result.tx.outputs[0].script.equals(out)) {
                            amountStr = BTCUtils.formatValue(result.tx.outputs[0].value);
                        }
                        if (amountStr == null) {
                            rawTxToSpendErr.setText(R.string.error_unknown);
                        } else {
                            String descStr;
                            String feeStr = BTCUtils.formatValue(result.fee);
                            String changeStr;
                            if (result.tx.outputs.length == 1) {
                                changeStr = null;
                                descStr = getString(R.string.spend_tx_description, amountStr, keyPair.address,
                                        outputAddress, feeStr);
                            } else if (result.tx.outputs.length == 2) {
                                changeStr = BTCUtils.formatValue(result.tx.outputs[1].value);
                                descStr = getString(R.string.spend_tx_with_change_description, amountStr,
                                        keyPair.address, outputAddress, feeStr, changeStr);
                            } else {
                                throw new RuntimeException();
                            }
                            SpannableStringBuilder descBuilder = new SpannableStringBuilder(descStr);

                            int spanBegin = descStr.indexOf(keyPair.address);
                            if (spanBegin >= 0) {//from
                                ForegroundColorSpan addressColorSpan = new ForegroundColorSpan(
                                        getColor(MainActivity.this, R.color.dark_orange));
                                descBuilder.setSpan(addressColorSpan, spanBegin,
                                        spanBegin + keyPair.address.length(),
                                        SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                            if (spanBegin >= 0) {
                                spanBegin = descStr.indexOf(keyPair.address, spanBegin + 1);
                                if (spanBegin >= 0) {//change
                                    ForegroundColorSpan addressColorSpan = new ForegroundColorSpan(
                                            getColor(MainActivity.this, R.color.dark_orange));
                                    descBuilder.setSpan(addressColorSpan, spanBegin,
                                            spanBegin + keyPair.address.length(),
                                            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                                }
                            }
                            spanBegin = descStr.indexOf(outputAddress);
                            if (spanBegin >= 0) {//dest
                                ForegroundColorSpan addressColorSpan = new ForegroundColorSpan(
                                        getColor(MainActivity.this, R.color.dark_green));
                                descBuilder.setSpan(addressColorSpan, spanBegin,
                                        spanBegin + outputAddress.length(),
                                        SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                            final String nbspBtc = "\u00a0BTC";
                            spanBegin = descStr.indexOf(amountStr + nbspBtc);
                            if (spanBegin >= 0) {
                                descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin,
                                        spanBegin + amountStr.length() + nbspBtc.length(),
                                        SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                            spanBegin = descStr.indexOf(feeStr + nbspBtc, spanBegin);
                            if (spanBegin >= 0) {
                                descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin,
                                        spanBegin + feeStr.length() + nbspBtc.length(),
                                        SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                            if (changeStr != null) {
                                spanBegin = descStr.indexOf(changeStr + nbspBtc, spanBegin);
                                if (spanBegin >= 0) {
                                    descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin,
                                            spanBegin + changeStr.length() + nbspBtc.length(),
                                            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                                }
                            }
                            spendTxDescriptionView.setText(descBuilder);
                            spendTxDescriptionView.setVisibility(View.VISIBLE);
                            spendTxWarningView.setVisibility(View.VISIBLE);
                            spendTxEdit.setText(BTCUtils.toHex(result.tx.getBytes()));
                            spendTxEdit.setVisibility(View.VISIBLE);
                            sendTxInBrowserButton.setVisibility(View.VISIBLE);

                            TextView maxAgeView = (TextView) findViewById(
                                    R.id.spend_tx_required_age_for_free_tx);
                            CheckBox maxAgeCheckBox = (CheckBox) findViewById(
                                    R.id.spend_tx_required_age_for_free_tx_checkbox);
                            if (!inputsComesFromJson) {
                                if (!showNotEligibleForNoFeeBecauseOfBasicConstrains(maxAgeView, result.tx)) {
                                    final int confirmations = (int) (BTCUtils.MIN_PRIORITY_FOR_NO_FEE
                                            * result.tx.getBytes().length / unspentOutputs.get(0).value);
                                    float daysFloat = confirmations / BTCUtils.EXPECTED_BLOCKS_PER_DAY;
                                    String timePeriodStr;
                                    if (daysFloat <= 1) {
                                        int hours = (int) Math.round(Math.ceil(daysFloat / 24));
                                        timePeriodStr = getResources().getQuantityString(R.plurals.hours, hours,
                                                hours);
                                    } else {
                                        int days = (int) Math.round(Math.ceil(daysFloat));
                                        timePeriodStr = getResources().getQuantityString(R.plurals.days, days,
                                                days);
                                    }
                                    maxAgeCheckBox.setText(getString(R.string.input_tx_is_old_enough,
                                            getResources().getQuantityString(R.plurals.confirmations,
                                                    confirmations, confirmations),
                                            timePeriodStr));
                                    maxAgeCheckBox.setVisibility(View.VISIBLE);
                                    maxAgeCheckBox.setOnCheckedChangeListener(null);
                                    maxAgeCheckBox.setChecked(predefinedConfirmationsCount > 0);
                                    maxAgeCheckBox.setOnCheckedChangeListener(
                                            new CompoundButton.OnCheckedChangeListener() {
                                                @Override
                                                public void onCheckedChanged(CompoundButton buttonView,
                                                        boolean isChecked) {
                                                    verifiedConfirmationsCount = isChecked ? confirmations : -1;
                                                    onUnspentOutputsInfoChanged();
                                                }
                                            });
                                } else {
                                    maxAgeCheckBox.setVisibility(View.GONE);
                                }
                            } else {
                                showNotEligibleForNoFeeBecauseOfBasicConstrains(maxAgeView, result.tx);
                            }
                        }
                    } else if (result.errorSource == GenerateTransactionResult.ERROR_SOURCE_INPUT_TX_FIELD) {
                        rawTxToSpendErr.setText(result.errorMessage);
                    } else if (result.errorSource == GenerateTransactionResult.ERROR_SOURCE_ADDRESS_FIELD
                            || result.errorSource == GenerateTransactionResult.HINT_FOR_ADDRESS_FIELD) {
                        ((TextView) findViewById(R.id.err_recipient_address)).setText(result.errorMessage);
                    } else if (!TextUtils.isEmpty(result.errorMessage)
                            && result.errorSource == GenerateTransactionResult.ERROR_SOURCE_UNKNOWN) {
                        new AlertDialog.Builder(MainActivity.this).setMessage(result.errorMessage)
                                .setPositiveButton(android.R.string.ok, null).show();
                    }

                    ((TextView) findViewById(R.id.err_amount))
                            .setText(result.errorSource == GenerateTransactionResult.ERROR_SOURCE_AMOUNT_FIELD
                                    ? result.errorMessage
                                    : "");
                }
            }

            private boolean showNotEligibleForNoFeeBecauseOfBasicConstrains(TextView maxAgeView,
                    Transaction tx) {
                long minOutput = Long.MAX_VALUE;
                for (Transaction.Output output : tx.outputs) {
                    minOutput = Math.min(output.value, minOutput);
                }
                int txLen = tx.getBytes().length;
                if (txLen >= BTCUtils.MAX_TX_LEN_FOR_NO_FEE) {
                    maxAgeView.setText(
                            getResources().getQuantityText(R.plurals.tx_size_too_big_to_be_free, txLen));
                    maxAgeView.setVisibility(View.VISIBLE);
                    return true;
                } else if (minOutput < BTCUtils.MIN_MIN_OUTPUT_VALUE_FOR_NO_FEE) {
                    maxAgeView
                            .setText(getString(R.string.tx_output_is_too_small, BTCUtils.formatValue(minOutput),
                                    BTCUtils.formatValue(BTCUtils.MIN_MIN_OUTPUT_VALUE_FOR_NO_FEE)));
                    maxAgeView.setVisibility(View.VISIBLE);
                    return true;
                }
                maxAgeView.setVisibility(View.GONE);
                return false;
            }
        }.execute();
    }
}

From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java

/**
 * performs table extraction on the HOCR file provided ,accepts input xml with HOCR page and document type classification along
 * with HOCR pages on whuich extraction is to be performed
 * //w  ww.  j a v  a2 s .  c om
 * @param req
 * @param resp
 * @return
 * @throws ValidationException
 * @throws InternalServerException
 */
public Batch.Documents processtableExtractionHOCR(final HttpServletRequest req, final HttpServletResponse resp)
        throws ValidationException, InternalServerException {
    LOGGER.info("Start processing web service for table extraction....");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String xmlFileName = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    Batch.Documents documents = null;
    InputStream instream = null;
    int responseCode = 0;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        try {
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            boolean isFileHOCR = false;
            boolean isFilePlainXML = false;
            if (fileMap.size() >= WebServiceConstants.MINIMUM_FILE_COUNT_FOR_TABLE_EXTRACTION) {
                for (final String inputFileName : fileMap.keySet()) {
                    try {
                        isFileHOCR = inputFileName.trim().endsWith(WebServiceConstants.HOCR_EXTENSION);
                        isFilePlainXML = inputFileName.toLowerCase()
                                .endsWith(FileType.XML.getExtensionWithDot());
                        if (!(isFileHOCR || isFilePlainXML)) {
                            respStr = WebServiceConstants.INVALID_FILES_TABLE_EXTRACTION;
                            responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                            createAndThrowValidationException(null, responseCode, respStr);
                        }
                        if (!isFileHOCR) {
                            xmlFileName = inputFileName;
                        }
                        final MultipartFile multiPartFile = multiPartRequest.getFile(inputFileName);
                        instream = multiPartFile.getInputStream();
                        WebServiceUtil.copyFile(workingDir, inputFileName, instream);
                    } catch (FileNotFoundException fileNotFoundException) {
                        respStr = WebServiceConstants.ERROR;
                        responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                    }
                }
                LOGGER.info("XML file name is" + xmlFileName);
                final File xmlFile = new File(
                        EphesoftStringUtil.concatenate(workingDir, File.separator, xmlFileName));
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                final Source source = XMLUtil.createSourceFromStream(inputStream);
                String response = WebServiceUtil.EMPTY_STRING;
                ExtractTableParam extractTableParams = (ExtractTableParam) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                List<com.ephesoft.dcma.batch.schema.ExtractTableParam.Documents.Document> docList = extractTableParams
                        .getDocuments().getDocument();
                final String batchClassIdentifier = extractTableParams.getBatchClassId();
                Map<DocumentType, List<HocrPages>> documentHOCRMap = new HashMap<DocumentType, List<HocrPages>>();
                if (EphesoftStringUtil.isNullOrEmpty(batchClassIdentifier)) {
                    responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                    respStr = WebServiceConstants.UNDEFINED_BATCH_IDENTIFIER;
                    createAndThrowValidationException(null, responseCode, respStr);
                }
                final BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier);
                if (null == batchClass) {
                    response = WebServiceUtil.BATCH_NOT_EXISTS;
                }
                if (EphesoftStringUtil.isNullOrEmpty(response)) {
                    String tableExtractionSwitch = WebServiceConstants.EMPTY_STRING;
                    try {
                        tableExtractionSwitch = batchClassPPService.getPropertyValue(batchClassIdentifier,
                                WebServiceConstants.TABLE_EXTRACTION_PLUGIN,
                                TableExtractionProperties.TABLE_EXTRACTION_SWITCH);
                    } catch (NullPointerException nullPointerException) {
                        responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                        respStr = EphesoftStringUtil.concatenate(
                                WebServiceConstants.UNDEFINED_TABLE_EXTRACTION_SWITCH, batchClassIdentifier);
                        createAndThrowConfigurationException(responseCode, respStr);
                    }
                    if (WebServiceUtil.OFF_STRING.equals(tableExtractionSwitch)) {
                        respStr = EphesoftStringUtil.concatenate(
                                WebServiceConstants.TABLE_EXTRACCTION_SWITCH_OFF_MESSAGE, batchClassIdentifier);
                        responseCode = WebServiceConstants.TABLE_EXTRACTION_SWITCH_OFF_CODE;
                        createAndThrowConfigurationException(responseCode, respStr);
                    }
                    final List<DocumentType> docTypeList = batchClass.getDocumentTypes();
                    List<String> docTypesName = obtainDocumentNameList(docTypeList);
                    documentHOCRMap = generateDocumentMapHOCR(docList, workingDir, docTypesName,
                            batchClassIdentifier);
                    if (documentHOCRMap.isEmpty()) {
                        respStr = WebServiceConstants.INVALID_MAPPING_DOCUMENT_HOCR_PAGES;
                        responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                        createAndThrowValidationException(null, responseCode, respStr);
                    }
                    final int gapBetweenColumnWords = tableFinderService.getGapBetweenColumnWords();
                    documents = tableExtraction.processDocPageForTableExtractionWebService(
                            gapBetweenColumnWords, documentHOCRMap, docTypeList, docTypesName);
                } else {
                    respStr = response;
                    responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                    createAndThrowValidationException(null, responseCode, respStr);
                }

            } else {
                respStr = WebServiceConstants.TABLE_EXTRACTION_MINIMUM_PARAMETERS_REQUIRED_ERROR_MESSAGE;
                responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                createAndThrowValidationException(null, responseCode, respStr);
            }
        } catch (ClassCastException classCastException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Not an Object of extract table Params",
                    classCastException.getMessage()));
            respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
        } catch (DCMABusinessException dcmaBusinessException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Invalid HOCR xml file uploaded",
                    dcmaBusinessException.getMessage()));
            respStr = WebServiceConstants.INVALID_HOCR_FILE_UPLOAD_MESSAGE;
            responseCode = WebServiceConstants.INVALID_HOCR_FILE_UPLOADED_CODE;
        } catch (org.springframework.oxm.UnmarshallingFailureException unmarshallingFailureException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Not an Object of extract table Params",
                    unmarshallingFailureException.getMessage()));
            respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
        } catch (Exception exception) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error generated is ", exception.getMessage()));
            if (EphesoftStringUtil.isNullOrEmpty(respStr)) {
                respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST;
                responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
            }
        } finally {
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        if (EphesoftStringUtil.isNullOrEmpty(respStr)) {
            respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST;
            responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
        }
    }
    validateResponse(responseCode, respStr);
    return documents;
}

From source file:org.red5.server.stream.ClientBroadcastStream.java

/**
 * Dispatches event/*from   w w w.  java  2  s.  c o  m*/
 * 
 * @param event
 *            Event to dispatch
 */
public void dispatchEvent(IEvent event) {
    if (event instanceof IRTMPEvent && !closed) {
        switch (event.getType()) {
        case STREAM_CONTROL:
        case STREAM_DATA:
            // create the event
            IRTMPEvent rtmpEvent;
            try {
                rtmpEvent = (IRTMPEvent) event;
            } catch (ClassCastException e) {
                log.error("Class cast exception in event dispatch", e);
                return;
            }
            int eventTime = -1;
            if (log.isTraceEnabled()) {
                // If this is first packet save its timestamp; expect it is
                // absolute? no matter: it's never used!
                if (firstPacketTime == -1) {
                    firstPacketTime = rtmpEvent.getTimestamp();
                    log.trace(String.format("CBS=@%08x: rtmpEvent=%s creation=%s firstPacketTime=%d",
                            System.identityHashCode(this), rtmpEvent.getClass().getSimpleName(), creationTime,
                            firstPacketTime));
                } else {
                    log.trace(
                            String.format("CBS=@%08x: rtmpEvent=%s creation=%s firstPacketTime=%d timestamp=%d",
                                    System.identityHashCode(this), rtmpEvent.getClass().getSimpleName(),
                                    creationTime, firstPacketTime, rtmpEvent.getTimestamp()));
                }
            }
            //get the buffer only once per call
            IoBuffer buf = null;
            if (rtmpEvent instanceof IStreamData && (buf = ((IStreamData<?>) rtmpEvent).getData()) != null) {
                bytesReceived += buf.limit();
            }
            // get stream codec
            IStreamCodecInfo codecInfo = getCodecInfo();
            StreamCodecInfo info = null;
            if (codecInfo instanceof StreamCodecInfo) {
                info = (StreamCodecInfo) codecInfo;
            }
            //log.trace("Stream codec info: {}", info);
            if (rtmpEvent instanceof AudioData) {
                IAudioStreamCodec audioStreamCodec = null;
                if (checkAudioCodec) {
                    // dont try to read codec info from 0 length audio packets
                    if (buf.limit() > 0) {
                        audioStreamCodec = AudioCodecFactory.getAudioCodec(buf);
                        if (info != null) {
                            info.setAudioCodec(audioStreamCodec);
                        }
                        checkAudioCodec = false;
                    }
                } else if (codecInfo != null) {
                    audioStreamCodec = codecInfo.getAudioCodec();
                }
                if (audioStreamCodec != null) {
                    audioStreamCodec.addData(buf);
                }
                if (info != null) {
                    info.setHasAudio(true);
                }
                eventTime = rtmpEvent.getTimestamp();
                log.trace("Audio: {}", eventTime);
            } else if (rtmpEvent instanceof VideoData) {
                IVideoStreamCodec videoStreamCodec = null;
                if (checkVideoCodec) {
                    videoStreamCodec = VideoCodecFactory.getVideoCodec(buf);
                    if (info != null) {
                        info.setVideoCodec(videoStreamCodec);
                    }
                    checkVideoCodec = false;
                } else if (codecInfo != null) {
                    videoStreamCodec = codecInfo.getVideoCodec();
                }
                if (videoStreamCodec != null) {
                    videoStreamCodec.addData(buf);
                }
                if (info != null) {
                    info.setHasVideo(true);
                }
                eventTime = rtmpEvent.getTimestamp();
                log.trace("Video: {}", eventTime);
            } else if (rtmpEvent instanceof Invoke) {
                Invoke invokeEvent = (Invoke) rtmpEvent;
                log.debug("Invoke action: {}", invokeEvent.getAction());
                eventTime = rtmpEvent.getTimestamp();
                // event / stream listeners will not be notified of invokes
                return;
            } else if (rtmpEvent instanceof Notify) {
                Notify notifyEvent = (Notify) rtmpEvent;
                log.debug("Notify action: {}", notifyEvent.getAction());
                if (notifyEvent.getAction() != null && notifyEvent.getAction().equals("onMetaData")) {
                    // store the metadata
                    try {
                        log.debug("Setting metadata");
                        metaData = notifyEvent.duplicate();
                    } catch (Exception e) {
                        log.warn("Metadata could not be duplicated for this stream", e);
                    }
                }
                eventTime = rtmpEvent.getTimestamp();
            }
            // update last event time
            if (eventTime > latestTimeStamp) {
                latestTimeStamp = eventTime;
            }
            // notify event listeners
            checkSendNotifications(event);
            // note this timestamp is set in event/body but not in the associated header
            try {
                // route to live
                if (livePipe != null) {
                    // create new RTMP message, initialize it and push through pipe
                    RTMPMessage msg = RTMPMessage.build(rtmpEvent, eventTime);
                    livePipe.pushMessage(msg);
                } else {
                    log.debug("Live pipe was null, message was not pushed");
                }
            } catch (IOException err) {
                stop();
            }
            // notify listeners about received packet
            if (rtmpEvent instanceof IStreamPacket) {
                for (IStreamListener listener : getStreamListeners()) {
                    try {
                        listener.packetReceived(this, (IStreamPacket) rtmpEvent);
                    } catch (Exception e) {
                        log.error("Error while notifying listener {}", listener, e);
                        if (listener instanceof RecordingListener) {
                            sendRecordFailedNotify(e.getMessage());
                        }
                    }
                }
            }
            break;
        default:
            // ignored event
            log.debug("Ignoring event: {}", event.getType());
        }
    } else {
        log.debug("Event was of wrong type or stream is closed ({})", closed);
    }
}