Java Code Examples for javax.servlet.http.HttpServletResponse#SC_CONFLICT

The following examples show how to use javax.servlet.http.HttpServletResponse#SC_CONFLICT . 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: hadoop   File: TransferFsImage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Requests that the NameNode download an image from this node.  Allows for
 * optional external cancelation.
 *
 * @param fsName the http address for the remote NN
 * @param conf Configuration
 * @param storage the storage directory to transfer the image from
 * @param nnf the NameNodeFile type of the image
 * @param txid the transaction ID of the image to be uploaded
 * @param canceler optional canceler to check for abort of upload
 * @throws IOException if there is an I/O error or cancellation
 */
public static void uploadImageFromStorage(URL fsName, Configuration conf,
    NNStorage storage, NameNodeFile nnf, long txid, Canceler canceler)
    throws IOException {
  URL url = new URL(fsName, ImageServlet.PATH_SPEC);
  long startTime = Time.monotonicNow();
  try {
    uploadImage(url, conf, storage, nnf, txid, canceler);
  } catch (HttpPutFailedException e) {
    if (e.getResponseCode() == HttpServletResponse.SC_CONFLICT) {
      // this is OK - this means that a previous attempt to upload
      // this checkpoint succeeded even though we thought it failed.
      LOG.info("Image upload with txid " + txid + 
          " conflicted with a previous image upload to the " +
          "same NameNode. Continuing...", e);
      return;
    } else {
      throw e;
    }
  }
  double xferSec = Math.max(
      ((float) (Time.monotonicNow() - startTime)) / 1000.0, 0.001);
  LOG.info("Uploaded image with txid " + txid + " to namenode at " + fsName
      + " in " + xferSec + " seconds");
}
 
Example 2
Source Project: big-c   File: TransferFsImage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Requests that the NameNode download an image from this node.  Allows for
 * optional external cancelation.
 *
 * @param fsName the http address for the remote NN
 * @param conf Configuration
 * @param storage the storage directory to transfer the image from
 * @param nnf the NameNodeFile type of the image
 * @param txid the transaction ID of the image to be uploaded
 * @param canceler optional canceler to check for abort of upload
 * @throws IOException if there is an I/O error or cancellation
 */
public static void uploadImageFromStorage(URL fsName, Configuration conf,
    NNStorage storage, NameNodeFile nnf, long txid, Canceler canceler)
    throws IOException {
  URL url = new URL(fsName, ImageServlet.PATH_SPEC);
  long startTime = Time.monotonicNow();
  try {
    uploadImage(url, conf, storage, nnf, txid, canceler);
  } catch (HttpPutFailedException e) {
    if (e.getResponseCode() == HttpServletResponse.SC_CONFLICT) {
      // this is OK - this means that a previous attempt to upload
      // this checkpoint succeeded even though we thought it failed.
      LOG.info("Image upload with txid " + txid + 
          " conflicted with a previous image upload to the " +
          "same NameNode. Continuing...", e);
      return;
    } else {
      throw e;
    }
  }
  double xferSec = Math.max(
      ((float) (Time.monotonicNow() - startTime)) / 1000.0, 0.001);
  LOG.info("Uploaded image with txid " + txid + " to namenode at " + fsName
      + " in " + xferSec + " seconds");
}
 
Example 3
@Test
public void getAsString() throws Exception {
    ResponsePrinter printer = new ResponsePrinter(new RawResponse(HttpServletResponse.SC_CONFLICT, "Conflict",
            Arrays.asList(new ApiHeader("Header1", "value1"), new ApiHeader("Authorization", "token")),
            new ByteArrayInputStream(("{\n" +
                    "\t\"tkoast\":\"raskpor\",\n" +
                    "\t\"skoipra\":\"smroiar\"\n" +
                    "}").getBytes())));
    assertThat(printer.getAsString()).isEqualTo("HTTP/1.1 409 Conflict\r\n" +
            "Header1: value1\r\n" +
            "Authorization: token\r\n" +
            "\r\n" +
            "{\n" +
            "\t\"tkoast\":\"raskpor\",\n" +
            "\t\"skoipra\":\"smroiar\"\n" +
            "}");

}
 
Example 4
private boolean handleDelete(HttpServletRequest req, HttpServletResponse resp, SiteInfo site) throws CoreException {
	UserInfo user = OrionConfiguration.getMetaStore().readUser(getUserName(req));
	ISiteHostingService hostingService = getHostingService();
	IHostedSite runningSite = hostingService.get(site, user);
	if (runningSite != null) {
		String msg = NLS.bind("Site configuration is running at {0}. Must be stopped before it can be deleted", runningSite.getHost());
		throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, msg, null));
	}
	site.delete(user);
	return true;
}
 
Example 5
Source Project: pulsar   File: ProducerHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static int getErrorCode(Exception e) {
    if (e instanceof IllegalArgumentException) {
        return HttpServletResponse.SC_BAD_REQUEST;
    } else if (e instanceof ProducerBusyException) {
        return HttpServletResponse.SC_CONFLICT;
    } else if (e instanceof ProducerBlockedQuotaExceededError || e instanceof ProducerBlockedQuotaExceededException) {
        return HttpServletResponse.SC_SERVICE_UNAVAILABLE;
    } else {
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
}
 
Example 6
Source Project: pulsar   File: ConsumerHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static int getErrorCode(Exception e) {
    if (e instanceof IllegalArgumentException) {
        return HttpServletResponse.SC_BAD_REQUEST;
    } else if (e instanceof ConsumerBusyException) {
        return HttpServletResponse.SC_CONFLICT;
    } else {
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
}
 
Example 7
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>();
    
    // Current user
    String userID = AuthenticationUtil.getFullyAuthenticatedUser();
    if (userID == null)
    {
        throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script ["
                    + req.getServiceMatch().getWebScript().getDescription()
                    + "] requires user authentication.");
    }

    NodeRef nodeRefToBeRestored = parseRequestForNodeRef(req);
    if (nodeRefToBeRestored == null)
    {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "nodeRef not recognised. Could not restore.");
    }
    
    // check if the current user has the permission to restore the node
    validatePermission(nodeRefToBeRestored, userID);
    
    RestoreNodeReport report = nodeArchiveService.restoreArchivedNode(nodeRefToBeRestored);

    // Handling of some error scenarios
    if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INVALID_ARCHIVE_NODE))
    {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find archive node: " + nodeRefToBeRestored);
    }
    else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_PERMISSION))
    {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Unable to restore archive node: " + nodeRefToBeRestored);
    }
    else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_DUPLICATE_CHILD_NODE_NAME))
    {
        throw new WebScriptException(HttpServletResponse.SC_CONFLICT, "Unable to restore archive node: " + nodeRefToBeRestored +". Duplicate child node name");
    }
    else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INVALID_PARENT) ||
             report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INTEGRITY) ||
             report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_OTHER))
    {
        throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to restore archive node: " + nodeRefToBeRestored);
    }
    
    model.put("restoreNodeReport", report);
    return model;
}
 
Example 8
private static RestException fromStatusRuntimeException(StatusRuntimeException e) {
    int statusCode;
    switch (e.getStatus().getCode()) {
        case OK:
            statusCode = HttpServletResponse.SC_OK;
            break;
        case INVALID_ARGUMENT:
            statusCode = HttpServletResponse.SC_BAD_REQUEST;
            break;
        case DEADLINE_EXCEEDED:
            statusCode = HttpServletResponse.SC_REQUEST_TIMEOUT;
            break;
        case NOT_FOUND:
            statusCode = HttpServletResponse.SC_NOT_FOUND;
            break;
        case ALREADY_EXISTS:
            statusCode = HttpServletResponse.SC_CONFLICT;
            break;
        case PERMISSION_DENIED:
            statusCode = HttpServletResponse.SC_FORBIDDEN;
            break;
        case RESOURCE_EXHAUSTED:
            statusCode = TOO_MANY_REQUESTS;
            break;
        case FAILED_PRECONDITION:
            statusCode = HttpServletResponse.SC_CONFLICT;
            break;
        case UNIMPLEMENTED:
            statusCode = HttpServletResponse.SC_NOT_IMPLEMENTED;
            break;
        case UNAVAILABLE:
            statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
            break;
        case UNAUTHENTICATED:
            statusCode = HttpServletResponse.SC_UNAUTHORIZED;
            break;
        default:
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    return RestException.newBuilder(statusCode, e.getMessage())
            .withCause(e)
            .build();
}
 
Example 9
public UploadOffsetMismatchException(String message) {
    super(HttpServletResponse.SC_CONFLICT, message);
}
 
Example 10
private static ManagementException createConflictManagementException(final Exception e)
{
    return new ManagementException(HttpServletResponse.SC_CONFLICT, e.getMessage(), e, null);
}
 
Example 11
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
		Exception exception) {
	logger.debug("ProtocolExceptionResolver.resolveException() called");

	Map<String, Object> model = new HashMap<>();

	int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
	String errMsg = exception.getMessage();

	if (exception instanceof HTTPException) {
		HTTPException httpExc = (HTTPException) exception;
		statusCode = httpExc.getStatusCode();

		if (exception instanceof ClientHTTPException) {
			logger.info("Client sent bad request ( " + statusCode + ")", exception);
		} else {
			logger.error("Error while handling request (" + statusCode + ")", exception);
		}
	} else {
		logger.error("Error while handling request", exception);
	}

	int depth = 10;
	Throwable temp = exception;
	while (!(temp instanceof ValidationException)) {
		if (depth-- == 0) {
			break;
		}
		if (temp == null) {
			break;
		}
		temp = temp.getCause();
	}

	if (temp instanceof ValidationException) {
		// This is currently just a simple fix that causes the validation report to be printed.
		// This should not be the final solution.
		Model validationReportModel = ((ValidationException) temp).validationReportAsModel();

		StringWriter stringWriter = new StringWriter();

		// We choose NQUADS because we want to support streaming in the future, and because there could be a use for
		// different graphs in the future
		Rio.write(validationReportModel, stringWriter, RDFFormat.NQUADS);

		statusCode = HttpServletResponse.SC_CONFLICT;
		errMsg = stringWriter.toString();

		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "application/shacl-validation-report+n-quads");
		model.put(SimpleResponseView.CUSTOM_HEADERS_KEY, headers);
	}

	model.put(SimpleResponseView.SC_KEY, statusCode);
	model.put(SimpleResponseView.CONTENT_KEY, errMsg);

	return new ModelAndView(SimpleResponseView.getInstance(), model);
}
 
Example 12
Source Project: nomulus   File: HttpException.java    License: Apache License 2.0 4 votes vote down vote up
public ConflictException(String message) {
  super(HttpServletResponse.SC_CONFLICT, message, null);
}
 
Example 13
@Override
public Void call() throws Exception {

   // Pre-condition check while holding locks.
   {

      // Resolve the namespace.  See BLZG-2023, BLZG-2041.
      // Note: We have a lock on the unisolated view of the namespace using the concurrency manager.
      final boolean exists = getIndexManager().getResourceLocator().locate(namespace, ITx.UNISOLATED) != null;

      if (exists) {
         /*
          * The namespace already exists.
          * 
          * Note: The response code is defined as 409 (Conflict) since 1.3.2.
          */
         throw new HttpOperationException(HttpServletResponse.SC_CONFLICT,
               BigdataServlet.MIME_TEXT_PLAIN, "EXISTS: " + namespace);
      }

   }

   // Create namespace.
   super.call();

   /*
    * Note: The response code is defined as 201 (Created) since 1.3.2.
    */

   /**
    * Generate the absolute location of the new resource.
    * 
    * @see <a href="http://trac.bigdata.com/ticket/1187"> CREATE DATA SET
    *      does not report Location header </a>
    */
   final String locationURI;
   {
      // Obtain the reconstructed request URI.
      final StringBuffer sb = req.getRequestURL();
      if (sb.charAt(sb.length() - 1) != '/') {
         // Add trailing '/' iff not present.
         sb.append('/');
      }
      // append the name of the newly created namespace.
      sb.append(namespace);
      /*
       * append /sparql to get the SPARQL end point. This end point may be
       * used for query, update, service description, etc.
       */
      sb.append("/sparql");
      locationURI = sb.toString();
   }

   buildResponse(HttpServletResponse.SC_CREATED,
         MultiTenancyServlet.MIME_TEXT_PLAIN, "CREATED: " + namespace,
         new NV("Location", locationURI)
         );

   return null;

}
 
Example 14
/**
 * A helper method which handles returning a 409 HTTP error status.
 * @param request The request being handled.
 * @param response The response associated with the request.
 * @param path Path mapped to the handled request. Used to display the error message.
 * @return <code>true</code> iff the 409 has been sent, <code>false</code> otherwise.
 */
protected boolean handleConflictingResource(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
	String msg = NLS.bind("Failed to handle request for {0}", path); //$NON-NLS-1$
	ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, msg, null);
	return statusHandler.handleRequest(request, response, status);
}