use of org.elasticsearch.common.xcontent.XContentBuilder in project crate by crate.
the class FailedShardsExceptionTest method testShardFailureReasonIsNull.
@Test
public void testShardFailureReasonIsNull() throws Exception {
FailedShardsException exception = new FailedShardsException(new ShardOperationFailedException[] { new ShardOperationFailedException() {
@Override
public String index() {
return null;
}
@Override
public int shardId() {
return 0;
}
@Override
public String reason() {
return null;
}
@Override
public RestStatus status() {
return null;
}
@Override
public void readFrom(StreamInput in) throws IOException {
}
@Override
public void writeTo(StreamOutput out) throws IOException {
}
@Override
public Throwable getCause() {
return null;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return null;
}
}, null });
assertThat(exception.getMessage(), is("query failed on shards 0 ( null )"));
}
use of org.elasticsearch.common.xcontent.XContentBuilder in project crate by crate.
the class TransportShardUpsertAction method prepareUpdate.
/**
* Prepares an update request by converting it into an index request.
* <p/>
* TODO: detect a NOOP and return an update response if true
*/
@SuppressWarnings("unchecked")
private SourceAndVersion prepareUpdate(DocTableInfo tableInfo, ShardUpsertRequest request, ShardUpsertRequest.Item item, IndexShard indexShard) throws ElasticsearchException {
final GetResult getResult = indexShard.getService().get(request.type(), item.id(), new String[] { RoutingFieldMapper.NAME, ParentFieldMapper.NAME, TTLFieldMapper.NAME }, true, Versions.MATCH_ANY, VersionType.INTERNAL, FetchSourceContext.FETCH_SOURCE, false);
if (!getResult.isExists()) {
throw new DocumentMissingException(request.shardId(), request.type(), item.id());
}
if (getResult.internalSourceRef() == null) {
// no source, we can't do nothing, through a failure...
throw new DocumentSourceMissingException(request.shardId(), request.type(), item.id());
}
if (item.version() != Versions.MATCH_ANY && item.version() != getResult.getVersion()) {
throw new VersionConflictEngineException(indexShard.shardId(), Constants.DEFAULT_MAPPING_TYPE, item.id(), getResult.getVersion(), item.version());
}
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
final Map<String, Object> updatedSourceAsMap;
final XContentType updateSourceContentType = sourceAndContent.v1();
updatedSourceAsMap = sourceAndContent.v2();
SymbolToFieldExtractorContext ctx = new SymbolToFieldExtractorContext(functions, item.insertValues());
Map<String, Object> pathsToUpdate = new LinkedHashMap<>();
Map<String, Object> updatedGeneratedColumns = new LinkedHashMap<>();
for (int i = 0; i < request.updateColumns().length; i++) {
/*
* NOTE: mapping isn't applied. So if an Insert was done using the ES Rest Endpoint
* the data might be returned in the wrong format (date as string instead of long)
*/
String columnPath = request.updateColumns()[i];
Object value = SYMBOL_TO_FIELD_EXTRACTOR.convert(item.updateAssignments()[i], ctx).apply(getResult);
Reference reference = tableInfo.getReference(ColumnIdent.fromPath(columnPath));
if (reference != null) {
/*
* it is possible to insert NULL into column that does not exist yet.
* if there is no column reference, we must not validate!
*/
ConstraintsValidator.validate(value, reference);
}
if (reference instanceof GeneratedReference) {
updatedGeneratedColumns.put(columnPath, value);
} else {
pathsToUpdate.put(columnPath, value);
}
}
// For updates we always have to enforce the validation of constraints on shards.
// Currently the validation is done only for generated columns.
processGeneratedColumns(tableInfo, pathsToUpdate, updatedGeneratedColumns, true, getResult);
updateSourceByPaths(updatedSourceAsMap, pathsToUpdate);
try {
XContentBuilder builder = XContentFactory.contentBuilder(updateSourceContentType);
builder.map(updatedSourceAsMap);
return new SourceAndVersion(builder.bytes(), getResult.getVersion());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + updatedSourceAsMap + "]", e);
}
}
use of org.elasticsearch.common.xcontent.XContentBuilder in project crate by crate.
the class FulltextAnalyzerResolver method encodeSettings.
public static BytesReference encodeSettings(Settings settings) {
try {
BytesStreamOutput bso = new BytesStreamOutput();
XContentBuilder builder = XContentFactory.jsonBuilder(bso);
builder.startObject();
for (Map.Entry<String, String> entry : settings.getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
builder.flush();
return bso.bytes();
} catch (IOException e) {
// this is a memory stream so no real I/O happens and a IOException can't really happen at runtime
throw Throwables.propagate(e);
}
}
use of org.elasticsearch.common.xcontent.XContentBuilder in project crate by crate.
the class RestSQLAction method executeBulkRequest.
private void executeBulkRequest(SQLXContentSourceContext context, final RestRequest request, final RestChannel channel) {
SQLOperations.Session session = sqlOperations.createSession(request.header(REQUEST_HEADER_SCHEMA), toOptions(request), DEFAULT_SOFT_LIMIT);
try {
final long startTime = System.nanoTime();
session.parse(UNNAMED, context.stmt(), Collections.<DataType>emptyList());
Object[][] bulkArgs = context.bulkArgs();
final RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[bulkArgs.length];
if (results.length == 0) {
session.bind(UNNAMED, UNNAMED, Collections.emptyList(), null);
session.execute(UNNAMED, 0, new BaseResultReceiver());
} else {
for (int i = 0; i < bulkArgs.length; i++) {
session.bind(UNNAMED, UNNAMED, Arrays.asList(bulkArgs[i]), null);
ResultReceiver resultReceiver = new RestBulkRowCountReceiver(results, i);
session.execute(UNNAMED, 0, resultReceiver);
}
}
List<Field> outputColumns = session.describe('P', UNNAMED);
if (outputColumns != null) {
throw new UnsupportedOperationException("Bulk operations for statements that return result sets is not supported");
}
session.sync().whenComplete((Object result, Throwable t) -> {
if (t == null) {
try {
XContentBuilder builder = ResultToXContentBuilder.builder(channel).cols(Collections.<Field>emptyList()).duration(startTime).bulkRows(results).build();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
errorResponse(channel, e);
}
} else {
errorResponse(channel, t);
}
});
} catch (Throwable t) {
errorResponse(channel, t);
}
}
use of org.elasticsearch.common.xcontent.XContentBuilder in project crate by crate.
the class JsonType method encodeAsUTF8Text.
@Override
protected byte[] encodeAsUTF8Text(@Nonnull Object value) {
try {
XContentBuilder builder = JsonXContent.contentBuilder();
if (value.getClass().isArray()) {
Object[] values = ((Object[]) value);
builder.startArray();
for (Object o : values) {
builder.value(o);
}
builder.endArray();
} else {
builder.map((Map) value);
}
builder.close();
BytesReference bytes = builder.bytes();
return bytes.toBytes();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
Aggregations