Search in sources :

Example 51 with StandardException

use of org.apache.derby.shared.common.error.StandardException in project derby by apache.

the class DRDAConnThread method buildSqlerrmc.

/**
 * Create error message or message argements to return to client.
 * The SQLERRMC will normally be passed back  to the server in a call
 * to the SYSIBM.SQLCAMESSAGE but for severe exceptions the stored procedure
 * call cannot be made. So for Severe messages we will just send the message text.
 *
 * This method will also truncate the value according the client capacity.
 * CCC can only handle 70 characters.
 *
 * Server sends the sqlerrmc using UTF8 encoding to the client.
 * To get the message, client sends back information to the server
 * calling SYSIBM.SQLCAMESSAGE (see Sqlca.getMessage).  Several parameters
 * are sent to this procedure including the locale, the sqlerrmc that the
 * client received from the server.
 * On server side, the procedure SQLCAMESSAGE in SystemProcedures then calls
 * the MessageService.getLocalizedMessage to retrieve the localized error message.
 * In MessageService.getLocalizedMessage the sqlerrmc that is passed in,
 * is parsed to retrieve the message id. The value it uses to parse the MessageId
 * is char value of 20, otherwise it uses the entire sqlerrmc as the message id.
 * This messageId is then used to retrieve the localized message if present, to
 * the client.
 *
 * @param se  SQLException to build SQLERRMC
 *
 * @return  String which is either the message arguments to be passed to
 *          SYSIBM.SQLCAMESSAGE or just message text for severe errors.
 */
private String buildSqlerrmc(SQLException se) {
    boolean severe = (se.getErrorCode() >= ExceptionSeverity.SESSION_SEVERITY);
    String sqlerrmc;
    // get exception which carries Derby messageID and args, per DERBY-1178
    StandardException ferry = StandardException.getArgumentFerry(se);
    if (se instanceof DataTruncation) {
        // Encode DataTruncation in a special way.
        sqlerrmc = buildDataTruncationSqlerrmc((DataTruncation) se);
    } else if (ferry != null && !severe) {
        // All other non-severe Derby exceptions are encoded here.
        sqlerrmc = buildTokenizedSqlerrmc(se);
    } else {
        // If this is not a Derby exception or is a severe excecption where
        // we have no hope of succussfully calling the SYSIBM.SQLCAMESSAGE send
        // preformatted message using the server locale
        sqlerrmc = buildPreformattedSqlerrmc(se);
    }
    // Truncate the sqlerrmc to a length that the client can support.
    int maxlen = (sqlerrmc == null) ? -1 : Math.min(sqlerrmc.length(), appRequester.supportedMessageParamLength());
    if ((maxlen >= 0) && (sqlerrmc.length() > maxlen)) {
        // have to truncate so the client can handle it.
        sqlerrmc = sqlerrmc.substring(0, maxlen);
    }
    return sqlerrmc;
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) DataTruncation(java.sql.DataTruncation)

Example 52 with StandardException

use of org.apache.derby.shared.common.error.StandardException in project derby by apache.

the class DRDAConnThread method validateSecMecUSRSSBPWD.

/**
 *  Validate SECMEC_USRSSBPWD (Strong Password Substitute) can be used as
 *  DRDA security mechanism.
 *
 *  Here we check that the target server can support SECMEC_USRSSBPWD
 *  security mechanism based on the environment, application
 *  requester's identity (PRDID) and connection URL.
 *
 *  IMPORTANT NOTE:
 *  --------------
 *  SECMEC_USRSSBPWD is ONLY supported by the target server if:
 *      - current authentication provider is Derby BUILTIN or
 *        NONE. (database / system level) (Phase I)
 *      - database-level password must have been encrypted with the
 *        SHA-1 based authentication scheme
 *      - Application requester is 'DNC' (Derby Network Client)
 *        (Phase I)
 *
 *  @return security check code - 0 if everything O.K.
 */
private int validateSecMecUSRSSBPWD() throws DRDAProtocolException {
    AuthenticationService authenticationService = null;
    org.apache.derby.iapi.db.Database databaseObj = null;
    String srvrlslv = appRequester.srvrlslv;
    // SECMEC_USRSSBPWD cannot be supported for this connection.
    if ((srvrlslv == null) || (srvrlslv.length() == 0) || (srvrlslv.length() < CodePoint.PRDID_MAX) || (srvrlslv.indexOf(DRDAConstants.DERBY_DRDA_CLIENT_ID) == -1)) {
        // Not Supported
        return CodePoint.SECCHKCD_NOTSUPPORTED;
    }
    // Client product version is extracted from the srvrlslv field.
    // srvrlslv has the format <PRDID>/<ALTERNATE VERSION FORMAT>
    // typically, a known Derby client has a four part version number
    // with a pattern such as DNC10020/10.2.0.3 alpha. If the alternate
    // version format is not specified, clientProductVersion_ will just
    // be set to the srvrlslvl. Final fallback will be the product id.
    // 
    // SECMEC_USRSSBPWD is only supported by the Derby engine and network
    // server code starting at version major '10' and minor '02'. Hence,
    // as this is the same for the derby client driver, we need to ensure
    // our DNC client is at version and release level of 10.2 at least.
    // We set the client version in the application requester and check
    // if it is at the level we require at a minimum.
    appRequester.setClientVersion(srvrlslv.substring(0, (int) CodePoint.PRDID_MAX));
    if (appRequester.supportsSecMecUSRSSBPWD() == false) {
        // Not Supported
        return CodePoint.SECCHKCD_NOTSUPPORTED;
    }
    String dbName = database.getShortDbName();
    // 'DNC' client)
    if ((dbName == null) || (dbName.length() == 0)) {
        // No database specified in the connection URL attributes
        // 
        // In this case, we get the authentication service handle from the
        // local driver, as the requester may simply be trying to shutdown
        // the engine.
        authenticationService = ((InternalDriver) NetworkServerControlImpl.getDriver()).getAuthenticationService();
    } else {
        // returns null and no Derby database has been booted.
        if (getMonitor() != null) {
            databaseObj = (org.apache.derby.iapi.db.Database) findService(Property.DATABASE_MODULE, dbName);
        }
        if (databaseObj == null) {
            // If database is not found, try connecting to it.
            database.makeDummyConnection();
            // now try to find it again
            databaseObj = (org.apache.derby.iapi.db.Database) findService(Property.DATABASE_MODULE, dbName);
        }
        // it.
        try {
            if (databaseObj != null) {
                authenticationService = databaseObj.getAuthenticationService();
            }
        } catch (StandardException se) {
            println2Log(null, session.drdaID, se.getMessage());
            // Local security service non-retryable error.
            return CodePoint.SECCHKCD_0A;
        }
    }
    // Now we check if the authentication provider is NONE or BUILTIN
    if (authenticationService != null) {
        String authClassName = authenticationService.getClass().getName();
        if (!authClassName.equals(AUTHENTICATION_PROVIDER_BUILTIN_CLASS) && !authClassName.equals(AUTHENTICATION_PROVIDER_NONE_CLASS)) {
            // Not Supported
            return CodePoint.SECCHKCD_NOTSUPPORTED;
        }
    }
    // SECMEC_USRSSBPWD target initialization
    try {
        myTargetSeed = DecryptionManager.generateSeed();
        database.secTokenOut = myTargetSeed;
    } catch (SQLException se) {
        println2Log(null, session.drdaID, se.getMessage());
        // Local security service non-retryable error.
        return CodePoint.SECCHKCD_0A;
    }
    // SECMEC_USRSSBPWD is supported
    return 0;
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) SQLException(java.sql.SQLException) AuthenticationService(org.apache.derby.iapi.jdbc.AuthenticationService)

Example 53 with StandardException

use of org.apache.derby.shared.common.error.StandardException in project derby by apache.

the class ClassInspector method findPublicField.

/**
 * Find a public field  for a class.
 *	   This follows the semantics of the java compiler for locating a field.
 *	   This means if a field fieldName exists in the class with package, private or
 *	   protected then an error is raised. Even if the field hides a field fieldName
 *	   in a super-class/super--interface. See the JVM spec on fields.
 *
 * @param receiverType	The class name of the receiver
 * @param fieldName		The name of the field
 * @param staticField	Find a static field
 *
 * @return	A Member representing the matching field.
 * @exception StandardException	Class or field does not exist or is not public or a security exception.
 *
 * @see	Member
 * @see Modifier
 */
public Member findPublicField(String receiverType, String fieldName, boolean staticField) throws StandardException {
    Exception e = null;
    try {
        Class<?> receiverClass = getClass(receiverType);
        if (receiverClass == null)
            return null;
        if (receiverClass.isArray() || receiverClass.isPrimitive()) {
            // arrays don't have fields (the fake field 'length' is not returned here)
            return null;
        }
        int modifier = staticField ? (Modifier.PUBLIC | Modifier.STATIC) : Modifier.PUBLIC;
        // Look for a public field first
        Field publicField = receiverClass.getField(fieldName);
        if ((publicField.getModifiers() & modifier) == modifier) {
            /*
					If the class is an interface then we avoid looking for a declared field
					that can hide a super-class's public field and not be accessable. This is because
					a interface's fields are always public. This avoids a security check.
				*/
            if (receiverClass.isInterface() || (publicField.getDeclaringClass().equals(receiverClass)))
                return publicField;
            try {
                Field declaredField = receiverClass.getDeclaredField(fieldName);
                if (SanityManager.DEBUG) {
                    if ((declaredField.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC)
                        SanityManager.THROWASSERT("declared field not expected to be public here " + declaredField);
                }
            } catch (NoSuchFieldException nsfe) {
                // no field hides the public field in the super class
                return publicField;
            }
        }
    } catch (ClassNotFoundException cnfe) {
        e = cnfe;
    } catch (NoSuchFieldException nsfep) {
        e = nsfep;
    } catch (SecurityException se) {
        e = se;
    }
    throw StandardException.newException(staticField ? SQLState.LANG_NO_STATIC_FIELD_FOUND : SQLState.LANG_NO_FIELD_FOUND, e, fieldName, receiverType);
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException)

Example 54 with StandardException

use of org.apache.derby.shared.common.error.StandardException in project derby by apache.

the class SQLChar method rawGetClobLength.

private int rawGetClobLength() throws SQLException {
    long maxLength = Integer.MAX_VALUE;
    long length = _clobValue.length();
    if (length > Integer.MAX_VALUE) {
        StandardException se = StandardException.newException(SQLState.BLOB_TOO_LARGE_FOR_CLIENT, Long.toString(length), Long.toString(maxLength));
        throw new SQLException(se.getMessage());
    }
    return (int) length;
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) SQLException(java.sql.SQLException)

Example 55 with StandardException

use of org.apache.derby.shared.common.error.StandardException in project derby by apache.

the class SQLChar method setWidth.

// /////////////////////////////////////////////////////////////
// 
// VariableSizeDataValue INTERFACE
// 
// /////////////////////////////////////////////////////////////
/**
 * Set the width of the to the desired value.  Used
 * when CASTing.  Ideally we'd recycle normalize(), but
 * the behavior is different (we issue a warning instead
 * of an error, and we aren't interested in nullability).
 *
 * @param desiredWidth  the desired length
 * @param desiredScale  the desired scale (ignored)
 * @param errorOnTrunc  throw an error on truncation
 *
 * @exception StandardException     Thrown when errorOnTrunc
 *      is true and when a shrink will truncate non-white
 *      spaces.
 */
public void setWidth(int desiredWidth, // Ignored
int desiredScale, boolean errorOnTrunc) throws StandardException {
    int sourceWidth;
    /*
        ** If the input is NULL, nothing to do.
        */
    if ((_clobValue == null) && (getString() == null)) {
        return;
    }
    sourceWidth = getLength();
    /*
        ** If the input is shorter than the desired type, construct a new
        ** SQLChar padded with blanks to the right length.  Only
        ** do this if we have a SQLChar -- SQLVarchars don't
        ** pad.
        */
    if (sourceWidth < desiredWidth) {
        if (!(this instanceof SQLVarchar)) {
            StringBuffer strbuf;
            strbuf = new StringBuffer(getString());
            for (; sourceWidth < desiredWidth; sourceWidth++) {
                strbuf.append(' ');
            }
            setValue(new String(strbuf));
        }
    } else if (sourceWidth > desiredWidth && desiredWidth > 0) {
        /*
            ** Check whether any non-blank characters will be truncated.
            */
        try {
            hasNonBlankChars(getString(), desiredWidth, sourceWidth);
        } catch (StandardException se) {
            if (errorOnTrunc) {
                throw se;
            }
            // Generate a truncation warning, as specified in SQL:2003,
            // part 2, 6.12 <cast specification>, general rules 10)c)2)
            // and 11)c)2).
            // Data size and transfer size need to be in bytes per
            // DataTruncation javadoc.
            String source = getString();
            int transferSize = getUTF8Length(source, 0, desiredWidth);
            int dataSize = transferSize + getUTF8Length(source, desiredWidth, source.length());
            DataTruncation warning = new DataTruncation(// column index is unknown
            -1, // parameter
            false, // read
            true, dataSize, transferSize);
            warning.initCause(se);
            StatementContext statementContext = (StatementContext) DataValueFactoryImpl.getContext(ContextId.LANG_STATEMENT);
            statementContext.getActivation().getResultSet().addWarning(warning);
        }
        /*
            ** Truncate to the desired width.
            */
        setValue(getString().substring(0, desiredWidth));
    }
    return;
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) DataTruncation(java.sql.DataTruncation) StatementContext(org.apache.derby.iapi.sql.conn.StatementContext)

Aggregations

StandardException (org.apache.derby.shared.common.error.StandardException)276 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)43 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)37 IOException (java.io.IOException)32 Properties (java.util.Properties)29 RawTransaction (org.apache.derby.iapi.store.raw.xact.RawTransaction)27 TransactionController (org.apache.derby.iapi.store.access.TransactionController)26 ContextManager (org.apache.derby.iapi.services.context.ContextManager)22 RawContainerHandle (org.apache.derby.iapi.store.raw.data.RawContainerHandle)20 SQLException (java.sql.SQLException)17 FormatableBitSet (org.apache.derby.iapi.services.io.FormatableBitSet)17 DataDictionary (org.apache.derby.iapi.sql.dictionary.DataDictionary)16 ConglomerateController (org.apache.derby.iapi.store.access.ConglomerateController)12 RowLocation (org.apache.derby.iapi.types.RowLocation)11 SQLLongint (org.apache.derby.iapi.types.SQLLongint)11 StorageFile (org.apache.derby.io.StorageFile)10 TableDescriptor (org.apache.derby.iapi.sql.dictionary.TableDescriptor)9 ScanController (org.apache.derby.iapi.store.access.ScanController)9 File (java.io.File)8 LogInstant (org.apache.derby.iapi.store.raw.log.LogInstant)8