Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  * Copyright (c) 2013, Cloudera, Inc. All Rights Reserved.
  * Cloudera, Inc. licenses this file to you under the Apache License,
  * Version 2.0 (the "License"). You may not use this file except in
  * compliance with the License. You may obtain a copy of the License at
 * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the
 * License.
package com.cloudera.oryx.kmeans.serving.web;

Responds to a GET request to /distanceToNearest/[datum], or a POST to /distanceToNearest containing the datum on one line. The input is one data point to cluster, delimited, like "1,-4,3.0". The response body contains the distance to the nearest cluster, on one line.

Sean Owen
public final class DistanceToNearestServlet extends AbstractKMeansServlet {
  protected void doGet(HttpServletRequest request,
                       HttpServletResponse responsethrows IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(."No path");
    doDistanceToNearest(pathInfo.substring(1), response);
  protected void doPost(HttpServletRequest request,
                        HttpServletResponse responsethrows IOException {
    String line = request.getReader().readLine();
    if (line == null) {
      response.sendError(."No body");
  private void doDistanceToNearest(String lineHttpServletResponse responsethrows IOException {
    if (generation == null) {
                         "API method unavailable until model has been built and loaded");
    String[] tokens = DelimitedDataUtils.decode(line);
    RealVector vector = generation.toVector(tokens);
    if (vector == null) {
      response.sendError(."Wrong column count");
    double distance = findClosest(generationvector).getSquaredDistance();
  static Distance findClosest(Generation generationRealVector parsedVector) {
    Centers centroids = generation.getCentroids();
    Preconditions.checkState(centroids.size() > 0);
    return centroids.getDistance(parsedVector);
New to GrepCode? Check out our FAQ X