com.alicloud.openservices.tablestore.ClientException Java Examples

The following examples show how to use com.alicloud.openservices.tablestore.ClientException. 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 File: ParamCheckerTest.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrimaryKeyColumnSizeExceed() {
    PrimaryKey primaryKey = PrimaryKeyBuilder.createPrimaryKeyBuilder()
            .addPrimaryKeyColumn("pk0", PrimaryKeyValue.fromLong(0))
            .addPrimaryKeyColumn("pk1", PrimaryKeyValue.fromString(getString(1025)))
            .addPrimaryKeyColumn("pk2", PrimaryKeyValue.fromBinary(new byte[]{0x0, 0x1, 0x2}))
            .build();
    RowPutChange rowChange = new RowPutChange(tableName, primaryKey);

    rowChange.addColumn("col0", ColumnValue.fromString(getString(100)));

    try {
        ParamChecker.checkRowChange(getTableMeta(), rowChange, getWriterConfig());
        fail("Expect exception happened.");
    } catch (ClientException e) {
        assertEquals(e.getMessage(), "The size of primary key column 'pk1' has exceeded the max length:1024.");
    }
}
 
Example #2
Source File: ParamCheckerTest.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testRowSizeExceed() {
    PrimaryKey primaryKey = PrimaryKeyBuilder.createPrimaryKeyBuilder()
            .addPrimaryKeyColumn("pk0", PrimaryKeyValue.fromLong(0))
            .addPrimaryKeyColumn("pk1", PrimaryKeyValue.fromString("abc"))
            .addPrimaryKeyColumn("pk2", PrimaryKeyValue.fromBinary(new byte[]{0x0, 0x1, 0x2}))
            .build();
    RowPutChange rowChange = new RowPutChange(tableName, primaryKey);

    rowChange.addColumn("col0", ColumnValue.fromString(getString(1024)));
    rowChange.addColumn("col1", ColumnValue.fromString(getString(1024)));
    rowChange.addColumn("col2", ColumnValue.fromString(getString(1024)));
    rowChange.addColumn("col3", ColumnValue.fromString(getString(1024)));

    try {
        ParamChecker.checkRowChange(getTableMeta(), rowChange, getWriterConfig());
        fail("Expect exception happened.");
    } catch (ClientException e) {
        assertEquals(e.getMessage(), "The row size exceeds the max batch size: 4096.");
    }
}
 
Example #3
Source File: SearchProtocolBuilder.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static Search.SearchRequest buildSearchRequest(SearchRequest request) {
    Search.SearchRequest.Builder builder = Search.SearchRequest.newBuilder();
    builder.setTableName(request.getTableName());
    builder.setIndexName(request.getIndexName());
    if (request.getColumnsToGet() != null) {
        builder.setColumnsToGet(buildColumnsToGet(request.getColumnsToGet()));
    }
    builder.setSearchQuery(buildSearchQuery(request.getSearchQuery()).toByteString());
    if (request.getRoutingValues() != null) {
        List<ByteString> routingValues = new ArrayList<ByteString>();
        for (PrimaryKey pk : request.getRoutingValues()) {
            try {
                routingValues.add(ByteString.copyFrom(PlainBufferBuilder.buildPrimaryKeyWithHeader(pk)));
            } catch (IOException e) {
                throw new ClientException("build plain buffer fail", e);
            }
        }
        builder.addAllRoutingValues(routingValues);
    }
    return builder.build();
}
 
Example #4
Source File: RequestSigner.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void sign(RequestMessage request) throws ClientException {
    request.addHeader(Constants.OTS_HEADER_ACCESS_KEY_ID, credentials.getAccessKeyId());
    if ((credentials.getSecurityToken() != null) && !credentials.getSecurityToken().isEmpty()) {
        request.addHeader(Constants.OTS_HEADER_STS_TOKEN, credentials.getSecurityToken());
    }
    try {
        String signature = getSignature(
            request.getActionUri().getAction(),
            request.getRequest().getMethod(),
            request.getRequest().getAllHeaders());
        request.addHeader(Constants.OTS_HEADER_SIGNATURE, signature);
    } catch (UnsupportedEncodingException e) {
        throw new ClientException("无法计算签名:" + e.getMessage());
    }
}
 
Example #5
Source File: Point.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 序列化类对象的public字段为filed,类字段只支持String, Double, Float, Long, Integer, Boolean
 */
public Builder from(Object object){
    try {
        Class c = object.getClass();
        for (Field field : c.getFields()) {
            com.alicloud.openservices.tablestore.timestream.model.annotation.Field colAnnotation =
                    field.getAnnotation(com.alicloud.openservices.tablestore.timestream.model.annotation.Field.class);
            if (colAnnotation != null) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                addField(colAnnotation.name(), field.get(object));
            }
        }
    } catch(IllegalAccessException e) {
        throw new ClientException(
                e.toString()
        );
    }
    return this;
}
 
Example #6
Source File: Utils.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static String getHashCode(String name, String tags) {
    StringBuffer md5StrBuff = new StringBuffer();
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(name.getBytes());
        md.update(tags.getBytes());
        byte[] byteArray = md.digest();
        for (int i = 0; i < byteArray.length; i++)
        {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
    } catch (Exception e) {
        throw new ClientException("Failed to get hash code: " + e.toString());
    }
    return md5StrBuff.toString().substring(0, 4);
}
 
Example #7
Source File: Utils.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static String serializeTags(Map<String, String> tags) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.disableHtmlEscaping().create();
    int tagSize = 0;
    if (tags.size() > TimestreamRestrict.TAG_COUNT) {
        throw new ClientException(String.format("The input tag count(%d) more than %d .", tags.size(), TimestreamRestrict.TAG_COUNT));
    }
    List<String> res = new ArrayList<String>();
    for (String key : tags.keySet()) {
        String tv = buildTagValue(key, tags.get(key));
        res.add(tv);
        tagSize += tv.length() - 1;
    }
    if (tagSize > TimestreamRestrict.TAG_LEN_BYTE) {
        throw new ClientException(String.format("The length(%d) of tag's name and value larger than %d.", tagSize, TimestreamRestrict.TAG_LEN_BYTE));
    }
    return gson.toJson(res);
}
 
Example #8
Source File: Utils.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static RowUpdateChange serializeTimestreamMetaToUpdate(String tableName, TimestreamMeta meta) {
    TimestreamIdentifier identifier = meta.getIdentifier();
    PrimaryKeyBuilder pkBuilder = convertIdentifierToPK(meta.getIdentifier());
    RowUpdateChange rowChange = new RowUpdateChange(tableName, pkBuilder.build());
    rowChange.put(
            new Column(
                    TableMetaGenerator.CN_TAMESTAMP_NAME,
                    ColumnValue.fromLong(meta.getUpdateTimeInUsec())));
    Map<String, ColumnValue> attributes = meta.getAttributes();
    for (String key : meta.getAttributes().keySet()) {
        if (key.equals(TableMetaGenerator.CN_TAMESTAMP_NAME)) {
            throw new ClientException("Key of attribute cannot be " + TableMetaGenerator.CN_TAMESTAMP_NAME + " .");
        }
        rowChange.put(key, attributes.get(key));
    }
    return rowChange;
}
 
Example #9
Source File: Utils.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static TimestreamMeta deserializeTimestreamMeta(Row row) {
    PrimaryKey pk = row.getPrimaryKey();
    TimestreamIdentifier identifier = deserializeTimestreamIdentifier(row);
    TimestreamMeta meta = new TimestreamMeta(identifier);
    for (Column col : row.getColumns()) {
        String colName = col.getName();
        if (row.getColumn(colName).size() > 1) {
            throw new ClientException("Multi version exist for column: " + colName + ".");
        }
        if (colName.equals(TableMetaGenerator.CN_TAMESTAMP_NAME)) {
            long ts = col.getValue().asLong();
            meta.setUpdateTime(ts, TimeUnit.MICROSECONDS);
        } else {
            meta.addAttribute(colName, col.getValue());
        }
    }
    return meta;
}
 
Example #10
Source File: HttpCredentialsFetcher.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceCredentials fetch() throws ClientException {
    URL url = buildUrl();
    HttpRequest request = new HttpRequest(url.toString());
    request.setMethod(MethodType.GET);
    request.setConnectTimeout(AuthUtils.DEFAULT_HTTP_SOCKET_TIMEOUT_IN_MILLISECONDS);
    request.setReadTimeout(AuthUtils.DEFAULT_HTTP_SOCKET_TIMEOUT_IN_MILLISECONDS);
    
    HttpResponse response = null;
    try {
        response = send(request);
    } catch (IOException e) {
        logger.error("CredentialsFetcher.fetch failed.", e);
        throw new ClientException("CredentialsFetcher.fetch exception: " + e);
    }
    
    return parse(response);
}
 
Example #11
Source File: SingleTimestreamFunctiontest.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorNoDataTable() throws Exception {
    String metaTableName = "singlets";
    TimestreamDBConfiguration config = new TimestreamDBConfiguration(metaTableName);
    AsyncClient asyncClient = new AsyncClient(
            conf.getEndpoint(),
            conf.getAccessId(),
            conf.getAccessKey(),
            conf.getInstance());
    TimestreamDB db = new TimestreamDBClient(asyncClient, config);

    Helper.safeClearDB(asyncClient);
    db.createMetaTable();
    String tableName = metaTableName + "_datatable_10";


    try {
        TimestreamDataTable dataTable = db.dataTable(tableName);
        Assert.fail();
    } catch (ClientException e) {
        Assert.assertTrue(e.getMessage().contains("Requested table does not exist.")); // OTS 自身有点问题,表不存在的时候会报 "Internal server error." 不符合预期
    }
}
 
Example #12
Source File: OTSProtocolParser.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static BatchGetRowResponse.RowResult parseBatchGetRowStatus(String tableName, OtsInternalApi.RowInBatchGetRowResponse status, int index) {
    if (status.getIsOk()) {
        Row row = null;
        if (!status.getRow().isEmpty()) {
            try {
                PlainBufferCodedInputStream inputStream = new PlainBufferCodedInputStream(new PlainBufferInputStream(status.getRow().asReadOnlyByteBuffer()));
                List<PlainBufferRow> rows = inputStream.readRowsWithHeader();
                if (rows.size() != 1) {
                    throw new IOException("Expect only returns one row. Row count: " + rows.size());
                }
                row = PlainBufferConversion.toRow(rows.get(0));
            } catch (Exception e) {
                throw new ClientException("Failed to parse row data.", e);
            }
        }
        ConsumedCapacity consumedCapacity = new ConsumedCapacity(parseCapacityUnit(status.getConsumed().getCapacityUnit()));
        if (status.hasNextToken()) {
            return new BatchGetRowResponse.RowResult(tableName, row, consumedCapacity, index, status.getNextToken().toByteArray());
        } else {
            return new BatchGetRowResponse.RowResult(tableName, row, consumedCapacity, index);
        }
    } else {
        com.alicloud.openservices.tablestore.model.Error error = new com.alicloud.openservices.tablestore.model.Error(status.getError().getCode(), status.getError().getMessage());
        return new BatchGetRowResponse.RowResult(tableName, error, index);
    }
}
 
Example #13
Source File: OTSProtocolParser.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static BatchWriteRowResponse.RowResult parseBatchWriteRowStatus(String tableName, OtsInternalApi.RowInBatchWriteRowResponse status, int index) {
Row row = null;
       if (status.getIsOk()) {
           ConsumedCapacity consumedCapacity = new ConsumedCapacity(parseCapacityUnit(status.getConsumed().getCapacityUnit()));
           
           if (status.hasRow() && !status.getRow().isEmpty()) {
               try {
                   PlainBufferCodedInputStream inputStream = new PlainBufferCodedInputStream(new PlainBufferInputStream(status.getRow().asReadOnlyByteBuffer()));
                   List<PlainBufferRow> rows = inputStream.readRowsWithHeader();
                   if (rows.size() != 1) {
                       throw new IOException("Expect only returns one row. Row count: " + rows.size());
                   }
                   row = PlainBufferConversion.toRow(rows.get(0));
               } catch (Exception e) {
                   throw new ClientException("Failed to parse row data.", e);
               }
           }
           return new BatchWriteRowResponse.RowResult(tableName, row, consumedCapacity, index);
       } else {
           com.alicloud.openservices.tablestore.model.Error error = new com.alicloud.openservices.tablestore.model.Error(status.getError().getCode(), status.getError().getMessage());
           return new BatchWriteRowResponse.RowResult(tableName, row, error, index);
       }
   }
 
Example #14
Source File: ResponseFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static GetRowResponse createGetRowResponse(ResponseContentWithMeta response,
                                                  OtsInternalApi.GetRowResponse getRowResponse) {
    ConsumedCapacity consumedCapacity = new ConsumedCapacity(
        OTSProtocolParser.parseCapacityUnit(getRowResponse.getConsumed().getCapacityUnit()));
    Row row = null;
    if (!getRowResponse.getRow().isEmpty()) {
        try {
            PlainBufferCodedInputStream inputStream = new PlainBufferCodedInputStream(
                new PlainBufferInputStream(getRowResponse.getRow().asReadOnlyByteBuffer()));
            List<PlainBufferRow> rows = inputStream.readRowsWithHeader();
            if (rows.size() != 1) {
                throw new IOException("Expect only returns one row. Row count: " + rows.size());
            }
            row = PlainBufferConversion.toRow(rows.get(0));
        } catch (Exception e) {
            throw new ClientException("Failed to parse row", e);
        }
    }
    GetRowResponse result = new GetRowResponse(response.getMeta(), row, consumedCapacity);
    if (getRowResponse.hasNextToken()) {
        result.setNextToken(getRowResponse.getNextToken().toByteArray());
    }
    return result;
}
 
Example #15
Source File: ResponseFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public static PutRowResponse createPutRowResponse(ResponseContentWithMeta response,
                                                  OtsInternalApi.PutRowResponse putRowResponse) {
    ConsumedCapacity consumedCapacity = new ConsumedCapacity(
        OTSProtocolParser.parseCapacityUnit(putRowResponse.getConsumed().getCapacityUnit()));
    Row row = null;
    if (!putRowResponse.getRow().isEmpty()) {
        try {
            PlainBufferCodedInputStream inputStream = new PlainBufferCodedInputStream(
                new PlainBufferInputStream(putRowResponse.getRow().asReadOnlyByteBuffer()));
            List<PlainBufferRow> rows = inputStream.readRowsWithHeader();
            if (rows.size() != 1) {
                throw new IOException("Expect only returns one row. Row count: " + rows.size());
            }
            row = PlainBufferConversion.toRow(rows.get(0));
        } catch (Exception e) {
            throw new ClientException("Failed to parse row", e);
        }
    }

    PutRowResponse result = new PutRowResponse(response.getMeta(), row, consumedCapacity);
    return result;
}
 
Example #16
Source File: GetRowColumnIteratorImpl.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public void fetchData() {
    getRowRequest.getRowQueryCriteria().setToken(token);
    GetRowResponse getRowResponse = null;
    try {
        getRowResponse = internalClient.getRowInternal(getRowRequest, null).get();
    } catch (Exception ex) {
        throw new ClientException(ex);
    }
    capacityUnit.setReadCapacityUnit(capacityUnit.getReadCapacityUnit() + getRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
    capacityUnit.setWriteCapacityUnit(capacityUnit.getWriteCapacityUnit() + getRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());
    Row row = getRowResponse.getRow();
    if (row != null) {
        if (primaryKey == null) {
            primaryKey = row.getPrimaryKey();
        }
        columnIterator = Arrays.asList(row.getColumns()).iterator();
    }
    if (getRowResponse.hasNextToken()) {
        token = getRowResponse.getNextToken();
    } else {
        complete = true;
    }
}
 
Example #17
Source File: TestTimelineException.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertException() {
    TableStoreException tableStoreException = new TableStoreException(
            "table not exist", new Exception(), "OTSObjectNotExist", "mockRequestId", 400
    );
    TimelineException e = Utils.convertException(tableStoreException);

    assertEquals("OTSObjectNotExist", e.getMessage());

    ClientException clientException = new ClientException();
    e = Utils.convertException(clientException);

    assertEquals("ClientError", e.getMessage());

    Exception exception = new Exception();
    e = Utils.convertException(exception);

    assertEquals("OtherError", e.getMessage());
}
 
Example #18
Source File: TestTimelineException.java    From tablestore-timeline with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testConvertException() {
    TableStoreException tableStoreException = new TableStoreException(
            "table not exist", new Exception(), "OTSObjectNotExist", "mockRequestId", 400
    );
    TimelineException e = Utils.convertException(tableStoreException);

    assertEquals("OTSObjectNotExist", e.getMessage());

    ClientException clientException = new ClientException();
    e = Utils.convertException(clientException);

    assertEquals("ClientError", e.getMessage());

    Exception exception = new Exception();
    e = Utils.convertException(exception);

    assertEquals("OtherError", e.getMessage());
}
 
Example #19
Source File: ParamCheckerTest.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTableNameInvalid() {
    PrimaryKey primaryKey = PrimaryKeyBuilder.createPrimaryKeyBuilder()
            .addPrimaryKeyColumn("pk0", PrimaryKeyValue.fromLong(0))
            .addPrimaryKeyColumn("pk1", PrimaryKeyValue.fromString("abc"))
            .addPrimaryKeyColumn("pk2", PrimaryKeyValue.fromBinary(new byte[]{0x0, 0x1, 0x2}))
            .build();
    RowPutChange rowChange = new RowPutChange("testTable1", primaryKey);
    rowChange.addColumn("col", ColumnValue.fromLong(1));

    try {
        ParamChecker.checkRowChange(getTableMeta(), rowChange, getWriterConfig());
        fail("Expect exception happened.");
    } catch (ClientException e) {
        assertEquals(e.getMessage(), "The row to write belongs to another table.");
    }
}
 
Example #20
Source File: ResponseFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static ReadRecordsResponse createReadRecordsResponse(
    ResponseContentWithMeta response, TunnelServiceApi.ReadRecordsResponse tunnelResponse) {
    ReadRecordsResponse resp = new ReadRecordsResponse(response.getMeta());
    resp.setMemoizedSerializedSize(tunnelResponse.getSerializedSize());
    if (tunnelResponse.hasNextToken()) {
        if (FINISH_TAG.equals(tunnelResponse.getNextToken())) {
            resp.setNextToken(null);
        } else {
            resp.setNextToken(tunnelResponse.getNextToken());
        }
    }

    List<StreamRecord> records = new ArrayList<StreamRecord>();

    for (TunnelServiceApi.Record record : tunnelResponse.getRecordsList()) {
        try {
            PlainBufferCodedInputStream inputStream = new PlainBufferCodedInputStream(
                new PlainBufferInputStream(record.getRecord().asReadOnlyByteBuffer())
            );
            List<PlainBufferRow> rows = inputStream.readRowsWithHeader();
            if (rows.size() != 1) {
                throw new IOException("Expect only returns one row, Row count: " + rows.size());
            }
            PlainBufferRow row = rows.get(0);
            records.add(PlainBufferConversion.toStreamRecord(row, record.getActionType()));
        } catch (Exception e) {
            throw new ClientException("Failed to parse row", e);
        }
    }

    resp.setRecords(records);
    return resp;
}
 
Example #21
Source File: TimeRangeUnittest.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRange() {
    long begin = (long)(Math.random() * 100000);
    long end = begin + 1;
    TimeRange timeRange1 = TimeRange.range(begin, end, TimeUnit.SECONDS);
    Assert.assertEquals(TimeUnit.SECONDS.toMicros(begin), timeRange1.getBeginTime());
    Assert.assertEquals(TimeUnit.SECONDS.toMicros(end), timeRange1.getEndTime());

    try {
        TimeRange.range(begin, begin, TimeUnit.SECONDS);
        Assert.fail();
    } catch (ClientException e) {
        // pass
    }
}
 
Example #22
Source File: MetaGetter.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 设置需要查询的attributes列名
 * @param columns
 * @return
 */
public MetaGetter selectAttributes(String... columns) {
    if (this.returnAll) {
        throw new ClientException("returnAll has been set.");
    }
    this.attrToGet = Arrays.asList(columns);
    return this;
}
 
Example #23
Source File: MetaGetter.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 设置查询完整的TimestreamMeta
 * @return
 */
public MetaGetter returnAll() {
    if (this.attrToGet != null) {
        throw new ClientException("Attributes to select has been set.");
    }
    this.returnAll = true;
    return this;
}
 
Example #24
Source File: TestInstanceProfileCredentialsProvider.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public URL buildUrl() throws ClientException {
    try {
        return new URL("http://127.0.0.1:9999/refreshToken/");
    } catch (MalformedURLException e) {
        throw new ClientException(e);
    }
}
 
Example #25
Source File: Utils.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static TimelineException convertException(Exception e) {
    if (e instanceof TableStoreException) {
        TableStoreException ex = (TableStoreException)e;
        return new TimelineException(ex.getErrorCode(), ex);
    } else if (e instanceof ClientException) {
        return new TimelineException("ClientError", e);
    } else {
        return new TimelineException("OtherError", e);
    }
}
 
Example #26
Source File: SingleColumnValueFilter.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public SingleColumnValueCondition toCondition() {
    SingleColumnValueCondition.CompareOperator filterOperator;
    switch (operator) {
        case EQUAL:
            filterOperator = SingleColumnValueCondition.CompareOperator.EQUAL;
            break;
        case NOT_EQUAL:
            filterOperator = SingleColumnValueCondition.CompareOperator.NOT_EQUAL;
            break;
        case GREATER_THAN:
            filterOperator = SingleColumnValueCondition.CompareOperator.GREATER_THAN;
            break;
        case GREATER_EQUAL:
            filterOperator = SingleColumnValueCondition.CompareOperator.GREATER_EQUAL;
            break;
        case LESS_THAN:
            filterOperator = SingleColumnValueCondition.CompareOperator.LESS_THAN;
            break;
        case LESS_EQUAL:
            filterOperator = SingleColumnValueCondition.CompareOperator.LESS_EQUAL;
            break;
        default:
            throw new ClientException("Unknown operator: " + operator.name());
    }

    SingleColumnValueCondition singleColumnValueCondition = new SingleColumnValueCondition(columnName, filterOperator, columnValue);
    singleColumnValueCondition.setLatestVersionsOnly(latestVersionsOnly);
    singleColumnValueCondition.setPassIfMissing(passIfMissing);
    return singleColumnValueCondition;
}
 
Example #27
Source File: CompositeColumnValueFilter.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public CompositeColumnValueCondition toCondition() {
    CompositeColumnValueCondition.LogicOperator logicOperator;
    switch (type) {
        case NOT:
            logicOperator = CompositeColumnValueCondition.LogicOperator.NOT;
            break;
        case AND:
            logicOperator = CompositeColumnValueCondition.LogicOperator.AND;
            break;
        case OR:
            logicOperator = CompositeColumnValueCondition.LogicOperator.OR;
            break;
        default:
            throw new ClientException("Unknown logicOperator: " + type.name());
    }
    CompositeColumnValueCondition compositeColumnValueCondition = new CompositeColumnValueCondition(logicOperator);
    for (Filter filter : getSubFilters()) {
        if (filter instanceof SingleColumnValueFilter) {
            compositeColumnValueCondition.addCondition(((SingleColumnValueFilter) filter).toCondition());
        } else if (filter instanceof CompositeColumnValueFilter) {
            compositeColumnValueCondition.addCondition(((CompositeColumnValueFilter) filter).toCondition());
        } else {
            throw new ClientException("Unknown filter type: " + filter.getFilterType());
        }
    }
    return compositeColumnValueCondition;
}
 
Example #28
Source File: Utils.java    From tablestore-timeline with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static TimelineException convertException(Exception e) {
    if (e instanceof TableStoreException) {
        TableStoreException ex = (TableStoreException)e;
        return new TimelineException(ex.getErrorCode(), ex);
    } else if (e instanceof ClientException) {
        return new TimelineException("ClientError", e);
    } else {
        return new TimelineException("OtherError", e);
    }
}
 
Example #29
Source File: RequestSigner.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public RequestSigner(String instanceName, ServiceCredentials credentials) {
    Preconditions.checkNotNull(instanceName);
    Preconditions.checkNotNull(credentials);

    this.credentials = credentials;
    this.accessKey = Bytes.toBytes(credentials.getAccessKeySecret());
    try {
        this.instanceName = instanceName.getBytes(Constants.HTTP_HEADER_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new ClientException("Unsupport encoding: " + Constants.HTTP_HEADER_ENCODING);
    }
}
 
Example #30
Source File: ResponseFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static DescribeTableResponse createDescribeTableResponse(ResponseContentWithMeta response,
                                                                OtsInternalApi.DescribeTableResponse
                                                                    describeTableResponse) {
    try {
        DescribeTableResponse result = new DescribeTableResponse(response.getMeta());
        result.setTableMeta(OTSProtocolParser.parseTableMeta(describeTableResponse.getTableMeta()));
        result.setTableOptions(OTSProtocolParser.parseTableOptions(describeTableResponse.getTableOptions()));
        result.setReservedThroughputDetails(OTSProtocolParser
                .parseReservedThroughputDetails(describeTableResponse.getReservedThroughputDetails()));
        if (describeTableResponse.hasStreamDetails()) {
            result.setStreamDetails(OTSProtocolParser.parseStreamDetails(describeTableResponse.getStreamDetails()));
        }

        List<PrimaryKey> shards = new ArrayList<PrimaryKey>();
        for (int i = 0; i < describeTableResponse.getShardSplitsCount(); ++i) {
            com.google.protobuf.ByteString bytes = describeTableResponse.getShardSplits(i);
            PlainBufferCodedInputStream coded = new PlainBufferCodedInputStream(
                new PlainBufferInputStream(bytes.asReadOnlyByteBuffer()));
            List<PlainBufferRow> rows = coded.readRowsWithHeader();
            if (rows.size() != 1) {
                throw new IOException("Expect only returns one row. Row count: " + rows.size());
            }
            Row row = PlainBufferConversion.toRow(rows.get(0));
            shards.add(row.getPrimaryKey());
        }
        result.setShardSplits(shards);
        for (int i = 0; i < describeTableResponse.getIndexMetasCount(); ++i) {
            result.addIndexMeta(OTSProtocolParser.parseIndexMeta(describeTableResponse.getIndexMetas(i)));
        }
        return result;
    } catch (Exception e) {
        throw new ClientException("Failed to parse describe table response.", e);
    }
}