Java Code Examples for com.mysql.cj.exceptions.WrongArgumentException

The following examples show how to use com.mysql.cj.exceptions.WrongArgumentException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lams   Source File: NoticeFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public Notice createFromMessage(XMessage message) {
    Frame notice = (Frame) message.getMessage();
    switch (notice.getType()) {
        case Notice.XProtocolNoticeFrameType_WARNING:
            com.mysql.cj.x.protobuf.MysqlxNotice.Warning warn = parseNotice((notice).getPayload(), com.mysql.cj.x.protobuf.MysqlxNotice.Warning.class);
            return new Notice(warn.getLevel().getNumber(), Integer.toUnsignedLong(warn.getCode()), warn.getMsg());

        case Notice.XProtocolNoticeFrameType_SESS_VAR_CHANGED:
            SessionVariableChanged svmsg = parseNotice(notice.getPayload(), SessionVariableChanged.class);
            return new Notice(svmsg.getParam(), svmsg.getValue());

        case Notice.XProtocolNoticeFrameType_SESS_STATE_CHANGED:
            SessionStateChanged ssmsg = parseNotice(notice.getPayload(), SessionStateChanged.class);
            return new Notice(ssmsg.getParam().getNumber(), ssmsg.getValueList());

        default:
            // TODO log error normally instead of sysout
            new WrongArgumentException("Got an unknown notice: " + notice).printStackTrace();
            break;
    }
    return null;
}
 
Example 2
Source Project: lams   Source File: SyncMessageReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public XMessage readMessage(Optional<XMessage> reuse, int expectedType) throws IOException {
    try {
        Class<? extends GeneratedMessage> messageClass = MessageConstants.getMessageClassForType(readHeader().getMessageType());
        Class<? extends GeneratedMessage> expectedClass = MessageConstants.getMessageClassForType(expectedType);

        // ensure that parsed message class matches incoming tag
        if (expectedClass != messageClass) {
            throw new WrongArgumentException("Unexpected message class. Expected '" + expectedClass.getSimpleName() + "' but actually received '"
                    + messageClass.getSimpleName() + "'");
        }

        return new XMessage(readAndParse(messageClass));
    } catch (IOException e) {
        throw new XProtocolError(e.getMessage(), e);
    }
}
 
Example 3
Source Project: lams   Source File: XProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void readAuthenticateOk() {
    try {
        XMessageHeader header;
        while ((header = this.reader.readHeader()).getMessageType() == ServerMessages.Type.NOTICE_VALUE) {
            Notice notice = this.noticeFactory.createFromMessage(this.reader.readMessage(null, header));
            if (notice.getType() == Notice.XProtocolNoticeFrameType_SESS_STATE_CHANGED) {
                switch (notice.getParamType()) {
                    case Notice.SessionStateChanged_CLIENT_ID_ASSIGNED:
                        this.getServerSession().setThreadId(notice.getValue().getVUnsignedInt());
                        break;
                    case Notice.SessionStateChanged_ACCOUNT_EXPIRED:
                        // TODO
                    default:
                        throw new WrongArgumentException("Unknown SessionStateChanged notice received during authentication: " + notice.getParamType());
                }
            } else {
                throw new WrongArgumentException("Unknown notice received during authentication: " + notice);
            }
        }
        this.reader.readMessage(null, ServerMessages.Type.SESS_AUTHENTICATE_OK_VALUE);
    } catch (IOException e) {
        throw new XProtocolError(e.getMessage(), e);
    }
}
 
Example 4
public Boolean createFromMessage(XMessage message) {
    //GeneratedMessage msg = (GeneratedMessage) message.getMessage();
    @SuppressWarnings("unchecked")
    Class<? extends GeneratedMessage> msgClass = (Class<? extends GeneratedMessage>) message.getMessage().getClass();
    if (Frame.class.equals(msgClass)) {
        this.builder.addNotice(this.noticeFactory.createFromMessage(message));
        return false; /* done reading? */
    } else if (StmtExecuteOk.class.equals(msgClass)) {
        this.future.complete(this.builder.build());
        return true; /* done reading? */
    } else if (Error.class.equals(msgClass)) {
        this.future.completeExceptionally(new XProtocolError(Error.class.cast(message.getMessage())));
        return true; /* done reading? */
    } else if (FetchDone.class.equals(msgClass)) {
        return false; /* done reading? */
    }
    this.future.completeExceptionally(new WrongArgumentException("Unhandled msg class (" + msgClass + ") + msg=" + message.getMessage()));
    return true; /* done reading? */
}
 
Example 5
/**
 * Add plugin to authentication plugins map if it is not disabled by
 * "disabledAuthenticationPlugins" property, check is it a default plugin.
 * 
 * @param plugin
 *            Instance of AuthenticationPlugin
 * @return True if plugin is default, false if plugin is not default.
 * @throws WrongArgumentException
 *             if plugin is default but disabled.
 */
private boolean addAuthenticationPlugin(AuthenticationPlugin<NativePacketPayload> plugin) {
    boolean isDefault = false;
    String pluginClassName = plugin.getClass().getName();
    String pluginProtocolName = plugin.getProtocolPluginName();
    boolean disabledByClassName = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginClassName);
    boolean disabledByMechanism = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginProtocolName);

    if (disabledByClassName || disabledByMechanism) {
        // if disabled then check is it default
        if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("AuthenticationProvider.BadDisabledAuthenticationPlugin",
                            new Object[] { disabledByClassName ? pluginClassName : pluginProtocolName }),
                    getExceptionInterceptor());
        }
    } else {
        this.authenticationPlugins.put(pluginProtocolName, plugin);
        if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
            this.clientDefaultAuthenticationPluginName = pluginProtocolName;
            isDefault = true;
        }
    }
    return isDefault;
}
 
Example 6
/**
 * Get authentication plugin instance from authentication plugins map by
 * pluginName key. If such plugin is found it's {@link AuthenticationPlugin#isReusable()} method
 * is checked, when it's false this method returns a new instance of plugin
 * and the same instance otherwise.
 * 
 * If plugin is not found method returns null, in such case the subsequent behavior
 * of handshake process depends on type of last packet received from server:
 * if it was Auth Challenge Packet then handshake will proceed with default plugin,
 * if it was Auth Method Switch Request Packet then handshake will be interrupted with exception.
 * 
 * @param pluginName
 *            mysql protocol plugin names, for example "mysql_native_password" and "mysql_old_password" for built-in plugins
 * @return null if plugin is not found or authentication plugin instance initialized with current connection properties
 */
@SuppressWarnings("unchecked")
private AuthenticationPlugin<NativePacketPayload> getAuthenticationPlugin(String pluginName) {

    AuthenticationPlugin<NativePacketPayload> plugin = this.authenticationPlugins.get(pluginName);

    if (plugin != null && !plugin.isReusable()) {
        try {
            plugin = plugin.getClass().newInstance();
            plugin.init(this.protocol);
        } catch (Throwable t) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { plugin.getClass().getName() }), t,
                    getExceptionInterceptor());
        }
    }

    return plugin;
}
 
Example 7
Source Project: lams   Source File: NativePacketPayload.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read len bytes from internal buffer starting from current position decoding them into String using the specified character encoding.
 * 
 * @param type
 * @param encoding
 *            if null then platform default encoding is used
 * @param len
 * @return
 */
public String readString(StringLengthDataType type, String encoding, int len) {
    String res = null;
    switch (type) {
        case STRING_FIXED:
        case STRING_VAR:
            if ((this.position + len) > this.payloadLength) {
                throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Buffer.1"));
            }

            res = StringUtils.toString(this.byteBuffer, this.position, len, encoding);
            this.position += len;
            break;

    }
    return res;
}
 
Example 8
Source Project: lams   Source File: ServerPreparedQuery.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sends stream-type data parameters to the server.
 * 
 * <pre>
 *  Long data handling:
 * 
 *  - Server gets the long data in pieces with command type 'COM_LONG_DATA'.
 *  - The packet received will have the format:
 *    [COM_LONG_DATA:     1][STMT_ID:4][parameter_number:2][type:2][data]
 *  - Checks if the type is specified by client, and if yes reads the type,
 *    and  stores the data in that format.
 *  - It is up to the client to check for read data ended. The server does not
 *    care; and also server does not notify to the client that it got the
 *    data  or not; if there is any error; then during execute; the error
 *    will  be returned
 * </pre>
 * 
 * @param parameterIndex
 * @param longData
 * 
 */
private void serverLongData(int parameterIndex, ServerPreparedQueryBindValue longData) {
    synchronized (this) {
        NativePacketPayload packet = this.session.getSharedSendPacket();

        Object value = longData.value;

        if (value instanceof byte[]) {
            this.session.sendCommand(this.commandBuilder.buildComStmtSendLongData(packet, this.serverStatementId, parameterIndex, (byte[]) value), true, 0);
        } else if (value instanceof InputStream) {
            storeStream(parameterIndex, packet, (InputStream) value);
        } else if (value instanceof java.sql.Blob) {
            try {
                storeStream(parameterIndex, packet, ((java.sql.Blob) value).getBinaryStream());
            } catch (Throwable t) {
                throw ExceptionFactory.createException(t.getMessage(), this.session.getExceptionInterceptor());
            }
        } else if (value instanceof Reader) {
            storeReader(parameterIndex, packet, (Reader) value);
        } else {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("ServerPreparedStatement.18") + value.getClass().getName() + "'", this.session.getExceptionInterceptor());
        }
    }
}
 
Example 9
Source Project: lams   Source File: ResultSetFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public ResultSetImpl createFromProtocolEntity(ProtocolEntity protocolEntity) {
    try {
        if (protocolEntity instanceof OkPacket) {
            return new ResultSetImpl((OkPacket) protocolEntity, this.conn, this.stmt);

        } else if (protocolEntity instanceof ResultsetRows) {
            int resultSetConcurrency = getResultSetConcurrency().getIntValue();
            int resultSetType = getResultSetType().getIntValue();

            return createFromResultsetRows(resultSetConcurrency, resultSetType, (ResultsetRows) protocolEntity);

        }
        throw ExceptionFactory.createException(WrongArgumentException.class, "Unknown ProtocolEntity class " + protocolEntity);

    } catch (SQLException ex) {
        throw ExceptionFactory.createException(ex.getMessage(), ex);
    }
}
 
Example 10
Source Project: lams   Source File: Util.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static <T> List<T> loadClasses(String extensionClassNames, String errorMessageKey, ExceptionInterceptor exceptionInterceptor) {

        List<T> instances = new LinkedList<>();

        List<String> interceptorsToCreate = StringUtils.split(extensionClassNames, ",", true);

        String className = null;

        try {
            for (int i = 0, s = interceptorsToCreate.size(); i < s; i++) {
                className = interceptorsToCreate.get(i);
                @SuppressWarnings("unchecked")
                T instance = (T) Class.forName(className).newInstance();

                instances.add(instance);
            }

        } catch (Throwable t) {
            throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString(errorMessageKey, new Object[] { className }), t,
                    exceptionInterceptor);
        }

        return instances;
    }
 
Example 11
Source Project: lams   Source File: AbstractQueryBindings.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the value for the placeholder as a serialized Java object (used by various forms of setObject()
 * 
 * @param parameterIndex
 * @param parameterObj
 */
protected final void setSerializableObject(int parameterIndex, Object parameterObj) {
    try {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
        objectOut.writeObject(parameterObj);
        objectOut.flush();
        objectOut.close();
        bytesOut.flush();
        bytesOut.close();

        byte[] buf = bytesOut.toByteArray();
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(buf);
        setBinaryStream(parameterIndex, bytesIn, buf.length);
        this.bindValues[parameterIndex].setMysqlType(MysqlType.BINARY);
    } catch (Exception ex) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("PreparedStatement.54") + ex.getClass().getName(), ex,
                this.session.getExceptionInterceptor());
    }
}
 
Example 12
Source Project: lams   Source File: StringUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the byte[] representation of subset of the given char[] using the given encoding.
 * 
 * @param value
 *            chars
 * @param offset
 *            offset
 * @param length
 *            length
 * @param encoding
 *            java encoding
 * @return bytes
 */
public static byte[] getBytes(char[] value, int offset, int length, String encoding) {
    Charset cs;
    try {
        if (encoding == null) {
            cs = Charset.defaultCharset();
        } else {
            cs = Charset.forName(encoding);
        }
    } catch (UnsupportedCharsetException ex) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("StringUtils.0", new Object[] { encoding }), ex);
    }
    ByteBuffer buf = cs.encode(CharBuffer.wrap(value, offset, length));

    // can't simply .array() this to get the bytes especially with variable-length charsets the buffer is sometimes larger than the actual encoded data
    int encodedLen = buf.limit();
    byte[] asBytes = new byte[encodedLen];
    buf.get(asBytes, 0, encodedLen);

    return asBytes;
}
 
Example 13
Source Project: lams   Source File: ExprParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a document path member.
 * 
 * @return {@link DocumentPathItem}
 */
DocumentPathItem docPathMember() {
    consumeToken(TokenType.DOT);
    Token t = this.tokens.get(this.tokenPos);
    String memberName;
    if (currentTokenTypeEquals(TokenType.IDENT)) {
        // this shouldn't be allowed to be quoted with backticks, but the lexer allows it
        if (!t.value.equals(ExprUnparser.quoteIdentifier(t.value))) {
            throw new WrongArgumentException("'" + t.value + "' is not a valid JSON/ECMAScript identifier");
        }
        consumeToken(TokenType.IDENT);
        memberName = t.value;
    } else if (currentTokenTypeEquals(TokenType.LSTRING)) {
        consumeToken(TokenType.LSTRING);
        memberName = t.value;
    } else {
        throw new WrongArgumentException("Expected token type IDENT or LSTRING in JSON path at token pos " + this.tokenPos);
    }
    DocumentPathItem.Builder item = DocumentPathItem.newBuilder();
    item.setType(DocumentPathItem.Type.MEMBER);
    item.setValue(memberName);
    return item.build();
}
 
Example 14
Source Project: lams   Source File: ExprParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a document path array index.
 * 
 * @return {@link DocumentPathItem}
 */
DocumentPathItem docPathArrayLoc() {
    DocumentPathItem.Builder builder = DocumentPathItem.newBuilder();
    consumeToken(TokenType.LSQBRACKET);
    if (currentTokenTypeEquals(TokenType.STAR)) {
        consumeToken(TokenType.STAR);
        consumeToken(TokenType.RSQBRACKET);
        return builder.setType(DocumentPathItem.Type.ARRAY_INDEX_ASTERISK).build();
    } else if (currentTokenTypeEquals(TokenType.LNUM_INT)) {
        Integer v = Integer.valueOf(this.tokens.get(this.tokenPos).value);
        if (v < 0) {
            throw new WrongArgumentException("Array index cannot be negative at " + this.tokenPos);
        }
        consumeToken(TokenType.LNUM_INT);
        consumeToken(TokenType.RSQBRACKET);
        return builder.setType(DocumentPathItem.Type.ARRAY_INDEX).setIndex(v).build();
    } else {
        throw new WrongArgumentException("Expected token type STAR or LNUM_INT in JSON path array index at token pos " + this.tokenPos);
    }
}
 
Example 15
Source Project: lams   Source File: ExprParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a JSON-style document path, like WL#7909, but prefix by @. instead of $.
 * 
 * @return list of {@link DocumentPathItem} objects
 */
public List<DocumentPathItem> documentPath() {
    List<DocumentPathItem> items = new ArrayList<>();
    while (true) {
        if (currentTokenTypeEquals(TokenType.DOT)) {
            items.add(docPathMember());
        } else if (currentTokenTypeEquals(TokenType.DOTSTAR)) {
            consumeToken(TokenType.DOTSTAR);
            items.add(DocumentPathItem.newBuilder().setType(DocumentPathItem.Type.MEMBER_ASTERISK).build());
        } else if (currentTokenTypeEquals(TokenType.LSQBRACKET)) {
            items.add(docPathArrayLoc());
        } else if (currentTokenTypeEquals(TokenType.DOUBLESTAR)) {
            consumeToken(TokenType.DOUBLESTAR);
            items.add(DocumentPathItem.newBuilder().setType(DocumentPathItem.Type.DOUBLE_ASTERISK).build());
        } else {
            break;
        }
    }
    if (items.size() > 0 && items.get(items.size() - 1).getType() == DocumentPathItem.Type.DOUBLE_ASTERISK) {
        throw new WrongArgumentException("JSON path may not end in '**' at " + this.tokenPos);
    }
    return items;
}
 
Example 16
Source Project: lams   Source File: ConnectionUrlParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses a host:port pair and returns the two elements in a {@link Pair}
 * 
 * @param hostInfo
 *            the host:pair to parse
 * @return a {@link Pair} containing the host and port information or null if the host information can't be parsed
 */
public static Pair<String, Integer> parseHostPortPair(String hostInfo) {
    if (isNullOrEmpty(hostInfo)) {
        return null;
    }
    Matcher matcher = GENERIC_HOST_PTRN.matcher(hostInfo);
    if (matcher.matches()) {
        String host = matcher.group("host");
        String portAsString = decode(safeTrim(matcher.group("port")));
        Integer portAsInteger = -1;
        if (!isNullOrEmpty(portAsString)) {
            try {
                portAsInteger = Integer.parseInt(portAsString);
            } catch (NumberFormatException e) {
                throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("ConnectionString.3", new Object[] { hostInfo }),
                        e);
            }
        }
        return new Pair<>(host, portAsInteger);
    }
    throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("ConnectionString.3", new Object[] { hostInfo }));
}
 
Example 17
Source Project: lams   Source File: ConnectionUrlParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Takes a two-matching-groups (respectively named "key" and "value") pattern which is successively tested against the given string and produces a key/value
 * map with the matched values. The given pattern must ensure that there are no leftovers between successive tests, i.e., the end of the previous match must
 * coincide with the beginning of the next.
 * 
 * @param pattern
 *            the regular expression pattern to match against to
 * @param input
 *            the input string
 * @return a key/value map containing the matched values
 */
private Map<String, String> processKeyValuePattern(Pattern pattern, String input) {
    Matcher matcher = pattern.matcher(input);
    int p = 0;
    Map<String, String> kvMap = new HashMap<>();
    while (matcher.find()) {
        if (matcher.start() != p) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("ConnectionString.4", new Object[] { input.substring(p) }));
        }
        String key = decode(safeTrim(matcher.group("key")));
        String value = decode(safeTrim(matcher.group("value")));
        if (!isNullOrEmpty(key)) {
            kvMap.put(key, value);
        } else if (!isNullOrEmpty(value)) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("ConnectionString.4", new Object[] { input.substring(p) }));
        }
        p = matcher.end();
    }
    if (p != input.length()) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("ConnectionString.4", new Object[] { input.substring(p) }));
    }
    return kvMap;
}
 
Example 18
void setValue(int intValue, String valueAsString, ExceptionInterceptor exceptionInterceptor) {
    if (getPropertyDefinition().isRangeBased()) {
        if ((intValue < getPropertyDefinition().getLowerBound()) || (intValue > getPropertyDefinition().getUpperBound())) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    "The connection property '" + getPropertyDefinition().getName() + "' only accepts integer values in the range of "
                            + getPropertyDefinition().getLowerBound() + " - " + getPropertyDefinition().getUpperBound() + ", the value '"
                            + (valueAsString == null ? intValue : valueAsString) + "' exceeds this range.",
                    exceptionInterceptor);
        }
    }

    this.value = Integer.valueOf(intValue);
    this.valueAsString = valueAsString == null ? String.valueOf(intValue) : valueAsString;
    this.wasExplicitlySet = true;
    invokeListeners();
}
 
Example 19
Source Project: lams   Source File: DefaultPropertySet.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> ModifiableProperty<T> getModifiableProperty(String name) {
    RuntimeProperty<?> prop = this.PROPERTY_NAME_TO_RUNTIME_PROPERTY.get(name);

    if (prop != null) {
        if (ModifiableProperty.class.isAssignableFrom(prop.getClass())) {
            try {
                return (ModifiableProperty<T>) this.PROPERTY_NAME_TO_RUNTIME_PROPERTY.get(name);

            } catch (ClassCastException ex) {
                // TODO improve message
                throw ExceptionFactory.createException(WrongArgumentException.class, ex.getMessage(), ex);
            }
        }
        throw ExceptionFactory.createException(PropertyNotModifiableException.class,
                Messages.getString("ConnectionProperties.dynamicChangeIsNotAllowed", new Object[] { "'" + prop.getPropertyDefinition().getName() + "'" }));
    }

    throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("ConnectionProperties.notFound", new Object[] { name }));

}
 
Example 20
Source Project: quarkus   Source File: MySQLJDBCReflections.java    License: Apache License 2.0 5 votes vote down vote up
@BuildStep
void registerExceptionsForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJCommunicationsException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, CJConnectionFeatureNotAvailableException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJOperationNotSupportedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJTimeoutException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJPacketTooBigException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, AssertionFailedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJOperationNotSupportedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ClosedOnExpiredPasswordException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ConnectionIsClosedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataConversionException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataReadException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataTruncationException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DeadlockTimeoutRollbackMarker.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, FeatureNotAvailableException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, InvalidConnectionAttributeException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, NumberOutOfRange.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, OperationCancelledException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, PasswordExpiredException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, PropertyNotModifiableException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, RSAException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, SSLParamsException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, StatementIsClosedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, StreamingNotifiable.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, UnableToConnectException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, UnsupportedConnectionStringException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, WrongArgumentException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, "com.mysql.cj.jdbc.MysqlXAException"));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, StandardLoadBalanceExceptionChecker.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, NdbLoadBalanceExceptionChecker.class.getName()));
}
 
Example 21
public void addNotice(Notice notice) {
    if (notice.getType() == Notice.XProtocolNoticeFrameType_WARNING) {
        this.warnings.add(notice);
    } else if (notice.getType() == Notice.XProtocolNoticeFrameType_SESS_STATE_CHANGED) {
        switch (notice.getParamType()) {
            case Notice.SessionStateChanged_GENERATED_INSERT_ID:
                // TODO: handle > 2^63-1?
                this.lastInsertId = notice.getValue().getVUnsignedInt();
                break;
            case Notice.SessionStateChanged_ROWS_AFFECTED:
                // TODO: handle > 2^63-1?
                this.rowsAffected = notice.getValue().getVUnsignedInt();
                break;
            case Notice.SessionStateChanged_PRODUCED_MESSAGE:
                // TODO do something with notices. expose them to client
                //System.err.println("Ignoring NOTICE message: " + msg.getValue().getVString().getValue().toStringUtf8());
                break;
            case Notice.SessionStateChanged_GENERATED_DOCUMENT_IDS:
                this.generatedIds = notice.getValueList().stream().map(v -> v.getVOctets().getValue().toStringUtf8()).collect(Collectors.toList());
                break;
            case Notice.SessionStateChanged_CURRENT_SCHEMA:
            case Notice.SessionStateChanged_ACCOUNT_EXPIRED:
            case Notice.SessionStateChanged_ROWS_FOUND:
            case Notice.SessionStateChanged_ROWS_MATCHED:
            case Notice.SessionStateChanged_TRX_COMMITTED:
            case Notice.SessionStateChanged_TRX_ROLLEDBACK:
                // TODO: propagate state
            default:
                // TODO: log warning normally instead of sysout
                new WrongArgumentException("unhandled SessionStateChanged notice! " + notice).printStackTrace();
        }
    } else {
        // TODO log error normally instead of sysout
        new WrongArgumentException("Got an unknown notice: " + notice).printStackTrace();
    }
}
 
Example 22
Source Project: lams   Source File: MessageConstants.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup the "ClientMessages" type tag for a protobuf message class.
 * 
 * @param msgClass
 *            message class extending {@link MessageLite}
 * @return type tag for this message class
 */
public static int getTypeForMessageClass(Class<? extends MessageLite> msgClass) {
    Integer tag = MESSAGE_CLASS_TO_CLIENT_MESSAGE_TYPE.get(msgClass);
    if (tag == null) {
        throw new WrongArgumentException("No mapping to ClientMessages for message class " + msgClass.getSimpleName());
    }
    return tag;
}
 
Example 23
Source Project: lams   Source File: FieldFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
private MysqlType findMysqlType(FieldType type, int contentType, int flags, int collationIndex) {
    switch (type) {
        case SINT:
            return MysqlType.BIGINT;
        case UINT:
            return MysqlType.BIGINT_UNSIGNED;
        case FLOAT:
            return 0 < (flags & XPROTOCOL_COLUMN_FLAGS_FLOAT_UNSIGNED) ? MysqlType.FLOAT_UNSIGNED : MysqlType.FLOAT;
        case DOUBLE:
            return 0 < (flags & XPROTOCOL_COLUMN_FLAGS_DOUBLE_UNSIGNED) ? MysqlType.DOUBLE_UNSIGNED : MysqlType.DOUBLE;
        case DECIMAL:
            return 0 < (flags & XPROTOCOL_COLUMN_FLAGS_DECIMAL_UNSIGNED) ? MysqlType.DECIMAL_UNSIGNED : MysqlType.DECIMAL;
        case BYTES:
            switch (contentType) {
                case XPROTOCOL_COLUMN_BYTES_CONTENT_TYPE_GEOMETRY:
                    return MysqlType.GEOMETRY;
                case XPROTOCOL_COLUMN_BYTES_CONTENT_TYPE_JSON:
                    return MysqlType.JSON;
                default:
                    if (collationIndex == 33) {
                        return MysqlType.VARBINARY;
                    }
                    return MysqlType.VARCHAR;
            }
        case TIME:
            return MysqlType.TIME;
        case DATETIME:
            return MysqlType.DATETIME;
        case SET:
            return MysqlType.SET;
        case ENUM:
            return MysqlType.ENUM;
        case BIT:
            return MysqlType.BIT;
        // TODO: longlong
    }
    throw new WrongArgumentException("TODO: unknown field type: " + type);
}
 
Example 24
Source Project: lams   Source File: FieldFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Map a X Protocol type code from `ColumnMetaData.FieldType' to a MySQL type constant. These are the only types that will be present in
 * {@link XProtocolRow}
 * results.
 *
 * @param type
 *            the type as the ColumnMetaData.FieldType
 * @param contentType
 *            the inner type
 * @return A <b>FIELD_TYPE</b> constant from {@link MysqlType} corresponding to the combination of input parameters.
 */
private int xProtocolTypeToMysqlType(FieldType type, int contentType) {
    switch (type) {
        case SINT:
            // TODO: figure out ranges in detail and test them
            return MysqlType.FIELD_TYPE_LONGLONG;
        case UINT:
            return MysqlType.FIELD_TYPE_LONGLONG;
        case FLOAT:
            return MysqlType.FIELD_TYPE_FLOAT;
        case DOUBLE:
            return MysqlType.FIELD_TYPE_DOUBLE;
        case DECIMAL:
            return MysqlType.FIELD_TYPE_NEWDECIMAL;
        case BYTES:
            switch (contentType) {
                case XPROTOCOL_COLUMN_BYTES_CONTENT_TYPE_GEOMETRY:
                    return MysqlType.FIELD_TYPE_GEOMETRY;
                case XPROTOCOL_COLUMN_BYTES_CONTENT_TYPE_JSON:
                    return MysqlType.FIELD_TYPE_JSON;
                default:
                    return MysqlType.FIELD_TYPE_VARCHAR;
            }
        case TIME:
            return MysqlType.FIELD_TYPE_TIME;
        case DATETIME:
            // may be a timestamp or just a date if time values are missing. metadata doesn't distinguish between the two
            return MysqlType.FIELD_TYPE_DATETIME;
        case SET:
            return MysqlType.FIELD_TYPE_SET;
        case ENUM:
            return MysqlType.FIELD_TYPE_ENUM;
        case BIT:
            return MysqlType.FIELD_TYPE_BIT;
        // TODO: longlong
    }
    throw new WrongArgumentException("TODO: unknown field type: " + type);
}
 
Example 25
@Override
public Integer parseObject(String value, ExceptionInterceptor exceptionInterceptor) {
    try {
        // Parse decimals, too
        int intValue = (int) (Double.valueOf(value).doubleValue() * this.multiplier);

        return intValue;

    } catch (NumberFormatException nfe) {
        throw ExceptionFactory.createException(WrongArgumentException.class,
                "The connection property '" + getName() + "' only accepts integer values. The value '" + value + "' can not be converted to an integer.",
                exceptionInterceptor);
    }
}
 
Example 26
Source Project: lams   Source File: ResultsetFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resultset createFromProtocolEntity(ProtocolEntity protocolEntity) {
    if (protocolEntity instanceof OkPacket) {
        return new NativeResultset((OkPacket) protocolEntity);

    } else if (protocolEntity instanceof ResultsetRows) {
        return new NativeResultset((ResultsetRows) protocolEntity);

    }
    throw ExceptionFactory.createException(WrongArgumentException.class, "Unknown ProtocolEntity class " + protocolEntity);
}
 
Example 27
@Override
public ColumnDefinition createFromFields(Field[] fields) {
    if (this.columnDefinitionFromCache != null) {
        if (fields.length != this.columnCount) {
            throw ExceptionFactory.createException(WrongArgumentException.class, "Wrong number of ColumnDefinition fields.");
        }
        Field[] f = this.columnDefinitionFromCache.getFields();
        for (int i = 0; i < fields.length; i++) {
            fields[i].setFlags(f[i].getFlags());
        }
    }
    return new DefaultColumnDefinition(fields);
}
 
Example 28
Source Project: lams   Source File: NativeServerSession.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String getEncodingForIndex(int charsetIndex) {
    String javaEncoding = null;

    String characterEncoding = this.propertySet.<String> getReadableProperty(PropertyDefinitions.PNAME_characterEncoding).getValue();

    if (this.propertySet.getBooleanReadableProperty(PropertyDefinitions.PNAME_useOldUTF8Behavior).getValue()) {
        return characterEncoding;
    }

    if (charsetIndex != NativeConstants.NO_CHARSET_INFO) {
        try {
            // getting charset name from dynamic maps in connection; we do it before checking against static maps because custom charset on server can be mapped
            // to index from our static map key's diapason 
            if (this.indexToCustomMysqlCharset != null) {
                String cs = this.indexToCustomMysqlCharset.get(charsetIndex);
                if (cs != null) {
                    javaEncoding = CharsetMapping.getJavaEncodingForMysqlCharset(cs, characterEncoding);
                }
            }
            // checking against static maps if no custom charset found
            if (javaEncoding == null) {
                javaEncoding = CharsetMapping.getJavaEncodingForCollationIndex(charsetIndex, characterEncoding);
            }

        } catch (ArrayIndexOutOfBoundsException outOfBoundsEx) {
            throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Connection.11", new Object[] { charsetIndex }));
        }

        // Punt
        if (javaEncoding == null) {
            javaEncoding = characterEncoding;
        }
    } else {
        javaEncoding = characterEncoding;
    }

    return javaEncoding;
}
 
Example 29
Source Project: lams   Source File: NativePacketPayload.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the actual length of payload written to buffer.
 * It can be smaller or equal to underlying buffer size.
 * 
 * @param bufLengthToSet
 */
public void setPayloadLength(int bufLengthToSet) {
    if (bufLengthToSet > this.byteBuffer.length) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Buffer.0"));
    }
    this.payloadLength = bufLengthToSet;
}
 
Example 30
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setSocketTimeout(int milliseconds) {
    try {
        Socket soc = this.socketConnection.getMysqlSocket();
        if (soc != null) {
            soc.setSoTimeout(milliseconds);
        }
    } catch (SocketException e) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Protocol.8"), e, getExceptionInterceptor());
    }
}