Java Code Examples for org.elasticsearch.ExceptionsHelper#convertToElastic()

The following examples show how to use org.elasticsearch.ExceptionsHelper#convertToElastic() . 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: TransportFieldStatsTransportAction.java    From Elasticsearch with Apache License 2.0 7 votes vote down vote up
@Override
protected FieldStatsShardResponse shardOperation(FieldStatsShardRequest request) {
    ShardId shardId = request.shardId();
    Map<String, FieldStats> fieldStats = new HashMap<>();
    IndexService indexServices = indicesService.indexServiceSafe(shardId.getIndex());
    MapperService mapperService = indexServices.mapperService();
    IndexShard shard = indexServices.shardSafe(shardId.id());
    try (Engine.Searcher searcher = shard.acquireSearcher("fieldstats")) {
        for (String field : request.getFields()) {
            MappedFieldType fieldType = mapperService.fullName(field);
            if (fieldType != null) {
                IndexReader reader = searcher.reader();
                Terms terms = MultiFields.getTerms(reader, field);
                if (terms != null) {
                    fieldStats.put(field, fieldType.stats(terms, reader.maxDoc()));
                }
            } else {
                throw new IllegalArgumentException("field [" + field + "] doesn't exist");
            }
        }
    } catch (IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
    return new FieldStatsShardResponse(shardId, fieldStats);
}
 
Example 2
Source File: MatchedQueriesFetchSubPhase.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void hitExecute(SearchContext context, HitContext hitContext) {
    List<String> matchedQueries = new ArrayList<>(2);

    try {
        addMatchedQueries(hitContext, context.parsedQuery().namedFilters(), matchedQueries);

        if (context.parsedPostFilter() != null) {
            addMatchedQueries(hitContext, context.parsedPostFilter().namedFilters(), matchedQueries);
        }
    } catch (IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    } finally {
        SearchContext.current().clearReleasables(Lifetime.COLLECTION);
    }

    hitContext.hit().matchedQueries(matchedQueries.toArray(new String[matchedQueries.size()]));
}
 
Example 3
Source File: ValidatingDispatcher.java    From deprecated-security-ssl with Apache License 2.0 6 votes vote down vote up
protected void checkRequest(final RestRequest request, final RestChannel channel) {
    
    if(SSLRequestHelper.containsBadHeader(threadContext, "_opendistro_security_ssl_")) {
        final ElasticsearchException exception = ExceptionUtils.createBadHeaderException();
        errorHandler.logError(exception, request, 1);
        throw exception;
    }
    
    try {
        if(SSLRequestHelper.getSSLInfo(settings, configPath, request, null) == null) {
            logger.error("Not an SSL request");
            throw new ElasticsearchSecurityException("Not an SSL request", RestStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (SSLPeerUnverifiedException e) {
        logger.error("No client certificates found but such are needed (Security 8).");
        errorHandler.logError(e, request, 0);
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example 4
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
protected void saveAnUpdateConfigs(final Client client, final RestRequest request, final CType cType,
								   final SecurityDynamicConfiguration<?> configuration, OnSucessActionListener<IndexResponse> actionListener) {
	final IndexRequest ir = new IndexRequest(this.opendistroIndex);

	//final String type = "_doc";
	final String id = cType.toLCString();

	configuration.removeStatic();

	try {
		client.index(ir.id(id)
						.setRefreshPolicy(RefreshPolicy.IMMEDIATE)
						.setIfSeqNo(configuration.getSeqNo())
						.setIfPrimaryTerm(configuration.getPrimaryTerm())
						.source(id, XContentHelper.toXContent(configuration, XContentType.JSON, false)),
				new ConfigUpdatingActionListener<IndexResponse>(client, actionListener));
	} catch (IOException e) {
		throw ExceptionsHelper.convertToElastic(e);
	}
}
 
Example 5
Source File: AuditMessage.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public String toPrettyString() {
    try {
        return Strings.toString(JsonXContent.contentBuilder().prettyPrint().map(getAsMap()));
    } catch (final IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example 6
Source File: PropertyUtil.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 5 votes vote down vote up
@SuppressForbidden(reason = "sysout needed here cause krb debug also goes to sysout")
public static void initKerberosProps(final Settings settings, Path conf) {
    if (conf == null) {
        final Environment env = new Environment(settings);
        conf = env.configFile();
    }
    PropertyUtil.setSystemProperty(KrbConstants.USE_SUBJECT_CREDS_ONLY_PROP, "false", false);
    //PropertyUtil.setSystemProperty(KrbConstants.USE_SUBJECT_CREDS_ONLY_PROP, "true", false); //TODO make strict
    try {
        PropertyUtil.setSystemPropertyToRelativeFile(KrbConstants.KRB5_CONF_PROP, conf,
                settings.get(SettingConstants.KRB5_FILE_PATH, "/etc/krb5.conf"), false, true);
    } catch (final FileNotFoundException e) {
        ExceptionsHelper.convertToElastic(e);
    }

    final boolean krbDebug = settings.getAsBoolean(SettingConstants.KRB_DEBUG, false);

    if (krbDebug) {
        System.out.println("Kerberos Realm debug is enabled");
        log.error("NOT AN ERROR: Kerberos Realm debug is enabled");
        JaasKrbUtil.ENABLE_DEBUG = true;
        System.setProperty("sun.security.krb5.debug", "true");
        System.setProperty("java.security.debug", "all");
        System.setProperty("java.security.auth.debug", "all");
        System.setProperty("sun.security.spnego.debug", "true");
    } else {
        log.info("Kerberos Realm debug is disabled");
    }

    log.info(KrbConstants.KRB5_CONF_PROP + ": {}", System.getProperty(KrbConstants.KRB5_CONF_PROP));

}
 
Example 7
Source File: ConfigurationLoader.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
private Settings toSettings(final BytesReference ref, final String type) {
    if (ref == null || ref.length() == 0) {
        return null;
    }
    
    XContentParser parser = null;

    try {
        parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, ref, XContentType.JSON);
        parser.nextToken();
        parser.nextToken();
     
        if(!type.equals((parser.currentName()))) {
            return null;
        }
        
        parser.nextToken();
        
        return Settings.builder().put(new JsonSettingsLoader(true).load(parser.binaryValue())).build();
    } catch (final IOException e) {
        throw ExceptionsHelper.convertToElastic(e);
    } finally {
        if(parser != null) {
            parser.close();
        }
    }
}
 
Example 8
Source File: BitsetFilterCache.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public BitSet getBitSet(LeafReaderContext context) throws IOException {
    try {
        return getAndLoadIfNotPresent(query, context);
    } catch (ExecutionException e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example 9
Source File: InnerHitsContext.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public TopDocs topDocs(SearchContext context, FetchSubPhase.HitContext hitContext) throws IOException {
    Query rawParentFilter;
    if (parentObjectMapper == null) {
        rawParentFilter = Queries.newNonNestedFilter();
    } else {
        rawParentFilter = parentObjectMapper.nestedTypeFilter();
    }
    BitSetProducer parentFilter = context.bitsetFilterCache().getBitSetProducer(rawParentFilter);
    Query childFilter = childObjectMapper.nestedTypeFilter();
    Query q = Queries.filtered(query.query(), new NestedChildrenQuery(parentFilter, childFilter, hitContext));

    if (size() == 0) {
        return new TopDocs(context.searcher().count(q), Lucene.EMPTY_SCORE_DOCS, 0);
    } else {
        int topN = Math.min(from() + size(), context.searcher().getIndexReader().maxDoc());
        TopDocsCollector topDocsCollector;
        if (sort() != null) {
            try {
                topDocsCollector = TopFieldCollector.create(sort(), topN, true, trackScores(), trackScores());
            } catch (IOException e) {
                throw ExceptionsHelper.convertToElastic(e);
            }
        } else {
            topDocsCollector = TopScoreDocCollector.create(topN);
        }
        try {
            context.searcher().search(q, topDocsCollector);
        } finally {
            clearReleasables(Lifetime.COLLECTION);
        }
        return topDocsCollector.topDocs(from(), size());
    }
}
 
Example 10
Source File: OpenDistroSecuritySSLNettyTransport.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
    SSLEngine engine = null;
    try {
        if (hostnameVerificationEnabled) {
            final InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
            String hostname = null;
            if (hostnameVerificationResovleHostName) {
                hostname = inetSocketAddress.getHostName();
            } else {
                hostname = inetSocketAddress.getHostString();
            }

            if(log.isDebugEnabled()) {
                log.debug("Hostname of peer is {} ({}/{}) with hostnameVerificationResovleHostName: {}", hostname, inetSocketAddress.getHostName(), inetSocketAddress.getHostString(), hostnameVerificationResovleHostName);
            }
            
            engine = odks.createClientTransportSSLEngine(hostname, inetSocketAddress.getPort());
        } else {
            engine = odks.createClientTransportSSLEngine(null, -1);
        }
    } catch (final SSLException e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
    final SslHandler sslHandler = new SslHandler(engine);
    ctx.pipeline().replace(this, "ssl_client", sslHandler);
    super.connect(ctx, remoteAddress, localAddress, promise);
}
 
Example 11
Source File: AuditMessage.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
	try {
		return Strings.toString(JsonXContent.contentBuilder().map(getAsMap()));
	} catch (final IOException e) {
	    throw ExceptionsHelper.convertToElastic(e);
	}
}
 
Example 12
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static <T> T serializeToXContentToPojo(String jsonContent, Class<T> clazz) {
    try {
        return DefaultObjectMapper.readValue(jsonContent, clazz);
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

}
 
Example 13
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static <T> T serializeToXContentToPojo(ToXContent jsonContent, Class<T> clazz) {
    try {

        if (jsonContent instanceof BytesReference) {
            return serializeToXContentToPojo(((BytesReference) jsonContent).utf8ToString(), clazz);
        }

        final BytesReference bytes = XContentHelper.toXContent(jsonContent, XContentType.JSON, false);
        return DefaultObjectMapper.readValue(bytes.utf8ToString(), clazz);
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

}
 
Example 14
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static JsonNode convertJsonToJackson(ToXContent jsonContent, boolean omitDefaults) {
    try {
        Map<String, String> pm = new HashMap<>(1);
        pm.put("omit_defaults", String.valueOf(omitDefaults));
        ToXContent.MapParams params = new ToXContent.MapParams(pm);

        final BytesReference bytes = XContentHelper.toXContent(jsonContent, XContentType.JSON, params, false);
        return DefaultObjectMapper.readTree(bytes.utf8ToString());
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

}
 
Example 15
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static JsonNode convertJsonToJackson(BytesReference jsonContent) {
    try {
        return DefaultObjectMapper.readTree(jsonContent.utf8ToString());
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

}
 
Example 16
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> convertJsonToxToStructuredMap(String jsonContent) {
    try (XContentParser parser = XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, OpenDistroSecurityDeprecationHandler.INSTANCE, jsonContent)) {
        return parser.map();
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }
}
 
Example 17
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> convertJsonToxToStructuredMap(ToXContent jsonContent) {
    Map<String, Object> map = null;
    try {
        final BytesReference bytes = XContentHelper.toXContent(jsonContent, XContentType.JSON, false);
        map = XContentHelper.convertToMap(bytes, false, XContentType.JSON).v2();
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

    return map;
}
 
Example 18
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected void response(RestChannel channel, RestStatus status, String message) {

		try {
			final XContentBuilder builder = channel.newBuilder();
			builder.startObject();
			builder.field("status", status.name());
			builder.field("message", message);
			builder.endObject();
			channel.sendResponse(new BytesRestResponse(status, builder));
		} catch (IOException e) {
			throw ExceptionsHelper.convertToElastic(e);
		}
	}
 
Example 19
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected static XContentBuilder convertToJson(RestChannel channel, ToXContent toxContent) {
	try {
		XContentBuilder builder = channel.newBuilder();
		toxContent.toXContent(builder, ToXContent.EMPTY_PARAMS);
		return builder;
	} catch (IOException e) {
		throw ExceptionsHelper.convertToElastic(e);
	}
}
 
Example 20
Source File: TopHitsParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
    SubSearchContext subSearchContext = new SubSearchContext(context);
    XContentParser.Token token;
    String currentFieldName = null;
    try {
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if ("sort".equals(currentFieldName)) {
                sortParseElement.parse(parser, subSearchContext);
            } else if ("_source".equals(currentFieldName)) {
                sourceParseElement.parse(parser, subSearchContext);
            } else if ("fields".equals(currentFieldName)) {
                fieldsParseElement.parse(parser, subSearchContext);
            } else if (token.isValue()) {
                switch (currentFieldName) {
                    case "from":
                        subSearchContext.from(parser.intValue());
                        break;
                    case "size":
                        subSearchContext.size(parser.intValue());
                        break;
                    case "track_scores":
                    case "trackScores":
                        subSearchContext.trackScores(parser.booleanValue());
                        break;
                    case "version":
                        subSearchContext.version(parser.booleanValue());
                        break;
                    case "explain":
                        subSearchContext.explain(parser.booleanValue());
                        break;
                    default:
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                            + currentFieldName + "].", parser.getTokenLocation());
                }
            } else if (token == XContentParser.Token.START_OBJECT) {
                switch (currentFieldName) {
                    case "highlight":
                        highlighterParseElement.parse(parser, subSearchContext);
                        break;
                    case "scriptFields":
                    case "script_fields":
                        scriptFieldsParseElement.parse(parser, subSearchContext);
                        break;
                    default:
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                            + currentFieldName + "].", parser.getTokenLocation());
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                switch (currentFieldName) {
                    case "fielddataFields":
                    case "fielddata_fields":
                        fieldDataFieldsParseElement.parse(parser, subSearchContext);
                        break;
                    default:
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                            + currentFieldName + "].", parser.getTokenLocation());
                }
            } else {
                throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                        parser.getTokenLocation());
            }
        }
    } catch (Exception e) {
        throw ExceptionsHelper.convertToElastic(e);
    }
    return new TopHitsAggregator.Factory(aggregationName, fetchPhase, subSearchContext);
}