Example usage for java.net HttpURLConnection HTTP_CONFLICT

List of usage examples for java.net HttpURLConnection HTTP_CONFLICT

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_CONFLICT.

Prototype

int HTTP_CONFLICT

To view the source code for java.net HttpURLConnection HTTP_CONFLICT.

Click Source Link

Document

HTTP Status-Code 409: Conflict.

Usage

From source file:com.utest.webservice.interceptors.UtestRestFaultOutInterceptor.java

public String buildResponse(final Message message) {
    final StringBuffer sb = new StringBuffer();
    final Fault fault = (Fault) message.getContent(Exception.class);
    final String accept = (String) message.getExchange().getInMessage().get(Message.ACCEPT_CONTENT_TYPE);
    int type = TYPE_TEXT;
    int responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
    if (accept.contains(MediaType.APPLICATION_XML)) {
        type = TYPE_XML;/*from w w w  . j av  a 2  s. co m*/
        message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_XML);
    } else if (accept.contains(MediaType.APPLICATION_JSON)) {
        type = TYPE_JSON;
        message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    } else {
        message.put(Message.CONTENT_TYPE, MediaType.TEXT_PLAIN);
    }
    sb.append(getStart(type));
    if (fault.getCause() instanceof ValidationException) {
        final ValidationException ve = (ValidationException) fault.getCause();
        for (final String errmsg : ve.getMessageKeys()) {
            sb.append(createError(type, fault.getCause(), errmsg));
        }
    } else {
        sb.append(createError(type, fault.getCause(), fault.getCause().getMessage()));
    }

    if ((fault.getCause() instanceof org.apache.cxf.interceptor.security.AccessDeniedException)
            || (fault.getCause() instanceof org.springframework.security.access.AccessDeniedException)) {
        responseCode = HttpURLConnection.HTTP_FORBIDDEN;// Access deny
    } else if (fault.getCause() instanceof NotFoundException) {
        responseCode = HttpURLConnection.HTTP_NOT_FOUND;// Not found
    } else if ((fault.getCause() instanceof StaleObjectStateException)
            || (fault.getCause() instanceof StaleStateException)) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof EmailInUseException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof ScreenNameInUseException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof InvalidParentChildEnvironmentException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DuplicateTestCaseStepException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DuplicateNameException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DeletingActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof DeletingUsedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ActivatingIncompleteEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof UnsupportedEnvironmentSelectionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ApprovingIncompleteEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ActivatingNotApprovedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ChangingActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof IncludingMultileVersionsOfSameEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof AssigningMultileVersionsOfSameEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof IncludingNotActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof TestCaseExecutionBlockedException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof TestCaseExecutionWithoutRestartException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof InvalidParentChildEnvironmentException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof UnsupportedTeamSelectionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof NoTeamDefinitionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof InvalidTeamMemberException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof TestCycleClosedException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    }
    // this is here to catch all business exceptions if this interceptor
    // wasn't updated properly
    else if (fault.getCause() instanceof DomainException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    }

    message.put(Message.RESPONSE_CODE, responseCode);
    sb.append(getEnd(type));
    return sb.toString();
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient29.java

@Override
public ChangeDetail rebase(String reviewId, int patchSetId, IProgressMonitor monitor) throws GerritException {
    final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId);
    final String uri = "/a/changes/" + id.getParentKey().get() + "/revisions/" + id.get() + "/rebase"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    executePostRestRequest(uri, new ChangeInfo28(), ChangeInfo28.class, new ErrorHandler() {
        @Override/*from  w ww  . jav  a  2 s  . c  om*/
        public void handleError(HttpMethodBase method) throws GerritException {
            String errorMsg = getResponseBodyAsString(method);
            if (isConflict(method)) {
                throw new GerritException(errorMsg);
            }
        }

        private String getResponseBodyAsString(HttpMethodBase method) {
            try {
                return method.getResponseBodyAsString();
            } catch (IOException e) {
                return null;
            }
        }

        private boolean isConflict(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT;
        }
    }, monitor);
    return getChangeDetail(id.getParentKey().get(), monitor);
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testConflictGetTTL() throws IOException {
    try {//from   w  w w . j a  va  2 s.c  om
        streamClient.getTTL(TestUtils.CONFLICT_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_CONFLICT, e.getStatusCode());
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient28.java

@Override
public ChangeDetail cherryPick(String reviewId, int patchSetId, final String message, final String destBranch,
        IProgressMonitor monitor) throws GerritException {
    final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId);
    String url = "/changes/" + id.getParentKey() + "/revisions/" + id.get() + "/cherrypick"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
    CherryPickInput input = new CherryPickInput(message, destBranch);
    ChangeInfo result = executePostRestRequest(url, input, ChangeInfo.class, new ErrorHandler() {
        @Override// w  w  w . j  a  v a2 s . c  o m
        public void handleError(HttpMethodBase method) throws GerritException {
            String errorMsg = getResponseBodyAsString(method);
            if (isNotPermitted(method, errorMsg)) {
                errorMsg = NLS.bind("Cannot cherry pick: {0}", errorMsg); //$NON-NLS-1$
            } else if (isConflict(method)) {
                errorMsg = NLS.bind("Request Conflict: {0}", errorMsg); //$NON-NLS-1$
            } else if (isBadRequest(method)) {
                errorMsg = NLS.bind("Bad Request: {0}", errorMsg); //$NON-NLS-1$
            }
            throw new GerritException(errorMsg);
        }

        private String getResponseBodyAsString(HttpMethodBase method) {
            try {
                return method.getResponseBodyAsString();
            } catch (IOException e) {
                return null;
            }
        }

        private boolean isNotPermitted(HttpMethodBase method, String msg) {
            return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN
                    && msg.toLowerCase().startsWith("cherry pick not permitted"); //$NON-NLS-1$
        }

        private boolean isConflict(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT;
        }

        private boolean isBadRequest(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST;
        }
    }, monitor);

    return getChangeDetail(result.getNumber(), monitor);
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK.//from  w  w w.  java2  s.c  om
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java

/** {@inheritDoc} */
@Override/*from w  w w . j  av a2s.  co m*/
public JobInfoResponse submitJob(JobInfoRequest jir) {
    logger.info("called");

    JobInfoResponse response;
    JobInfoElement jInfo = jir.getJobInfo();

    // validate parameters
    try {
        validateJobParams(jInfo);
    } catch (CloudServiceException e) {
        response = new JobInfoResponse(e);
        return response;
    }

    // ensure that job won't overload system
    // synchronize until an entry is created and INIT-ed in DB
    // throttling related parameters
    int maxRunningJobs = conf.getInt("netflix.genie.server.max.running.jobs", 0);
    int jobForwardThreshold = conf.getInt("netflix.genie.server.forward.jobs.threshold", 0);
    int maxIdleHostThreshold = conf.getInt("netflix.genie.server.max.idle.host.threshold", 0);
    int idleHostThresholdDelta = conf.getInt("netflix.genie.server.idle.host.threshold.delta", 0);
    synchronized (this) {
        try {
            int numRunningJobs = JobCountManager.getNumInstanceJobs();
            logger.info("Number of running jobs: " + numRunningJobs);

            // find an instance with fewer than (numRunningJobs -
            // idleHostThresholdDelta)
            int idleHostThreshold = numRunningJobs - idleHostThresholdDelta;
            // if numRunningJobs is already >= maxRunningJobs, forward
            // aggressively
            // but cap it at the max
            if ((idleHostThreshold > maxIdleHostThreshold) || (numRunningJobs >= maxRunningJobs)) {
                idleHostThreshold = maxIdleHostThreshold;
            }

            // check to see if job should be forwarded - only forward it
            // once. the assumption is that jobForwardThreshold < maxRunningJobs
            // (set in properties file)
            if ((numRunningJobs >= jobForwardThreshold) && (!jInfo.isForwarded())) {
                logger.info(
                        "Number of running jobs greater than forwarding threshold - trying to auto-forward");
                String idleHost = JobCountManager.getIdleInstance(idleHostThreshold);
                if (!idleHost.equals(NetUtil.getHostName())) {
                    jInfo.setForwarded(true);
                    stats.incrGenieForwardedJobs();
                    response = forwardJobRequest(
                            "http://" + idleHost + ":" + serverPort + "/" + jobResourcePrefix, jir);
                    return response;
                } // else, no idle hosts found - run here if capacity exists
            }

            if (numRunningJobs >= maxRunningJobs) {
                // if we get here, job can't be forwarded to an idle
                // instance anymore and current node is overloaded
                response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_UNAVAILABLE,
                        "Number of running jobs greater than system limit (" + maxRunningJobs
                                + ") - try another instance or try again later"));
                return response;
            }

            // if job can be launched, update the URIs
            buildJobURIs(jInfo);
        } catch (CloudServiceException e) {
            response = new JobInfoResponse(e);
            logger.error(response.getErrorMsg(), e);
            return response;
        }

        // init state in DB - return if job already exists
        try {
            pm.createEntity(jInfo);
        } catch (RollbackException e) {
            logger.error("Can't create entity in the database", e);
            if (e.getCause() instanceof EntityExistsException) {
                logger.error(e.getCause().getMessage());
                // most likely entity already exists - return useful message
                response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_CONFLICT,
                        "Job already exists for id: " + jInfo.getJobID()));
                return response;
            } else {
                // unknown exception - send it back
                response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        "Received exception: " + e.getCause()));
                return response;
            }
        }
    } // end synchronize

    // increment number of submitted jobs
    stats.incrGenieJobSubmissions();

    // try to run the job - return success or error
    try {
        JobManagerFactory.getJobManager(jInfo.getJobType()).launch(jInfo);

        // update entity in DB
        jInfo.setUpdateTime(System.currentTimeMillis());
        pm.updateEntity(jInfo);

        // verification
        jInfo = pm.getEntity(jInfo.getJobID(), JobInfoElement.class);

        // return successful response
        response = new JobInfoResponse();
        response.setMessage("Successfully launched job: " + jInfo.getJobID());
        response.setJob(jInfo);
        return response;
    } catch (Exception e) {
        logger.error("Failed to submit job: ", e);
        // update db
        jInfo.setJobStatus(JobStatus.FAILED, e.getMessage());
        jInfo.setUpdateTime(System.currentTimeMillis());
        pm.updateEntity(jInfo);
        // increment counter for failed jobs
        stats.incrGenieFailedJobs();
        // if it is a known exception, handle differently
        if (e instanceof CloudServiceException) {
            response = new JobInfoResponse((CloudServiceException) e);
        } else {
            response = new JobInfoResponse(
                    new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));
        }
        return response;
    }
}

From source file:org.eclipse.hono.client.impl.HonoClientImpl.java

/**
 * {@inheritDoc}//w w w . j  a  va 2  s .  c om
 */
@Override
public final Future<HonoClient> connect(final ProtonClientOptions options,
        final Handler<ProtonConnection> disconnectHandler) {

    final Future<HonoClient> result = Future.future();
    if (shuttingDown.get()) {
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "client is already shut down"));
    } else {
        connect(options, result.completer(), disconnectHandler);
    }
    return result;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

/**
 * Adds a tenant./* w w  w . j a va2  s  .c o m*/
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to register for the tenant.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> add(final String tenantId, final JsonObject tenantSpec) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantSpec);

    if (tenants.containsKey(tenantId)) {
        return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
    } else {
        try {
            final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
            tenant.setTenantId(tenantId);
            final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
            if (conflictingTenant != null) {
                // we are trying to use the same CA as an already existing tenant
                return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
            } else {
                tenants.put(tenantId, tenant);
                dirty = true;
                return TenantResult.from(HttpURLConnection.HTTP_CREATED);
            }
        } catch (IllegalArgumentException e) {
            return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }
}

From source file:org.eclipse.hono.client.impl.HonoClientImpl.java

private void connect(final ProtonClientOptions options,
        final Handler<AsyncResult<HonoClient>> connectionHandler,
        final Handler<ProtonConnection> disconnectHandler) {

    context.runOnContext(connect -> {

        if (isConnectedInternal()) {
            LOG.debug("already connected to server [{}:{}]", connectionFactory.getHost(),
                    connectionFactory.getPort());
            connectionHandler.handle(Future.succeededFuture(this));
        } else if (connecting.compareAndSet(false, true)) {

            if (options == null) {
                // by default, try to re-connect forever
                clientOptions = new ProtonClientOptions().setConnectTimeout(200).setReconnectAttempts(-1)
                        .setReconnectInterval(Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
            } else {
                clientOptions = options;
            }/*from w w  w . ja va  2 s .c o  m*/

            connectionFactory.connect(clientOptions,
                    remoteClose -> onRemoteClose(remoteClose, disconnectHandler),
                    failedConnection -> onRemoteDisconnect(failedConnection, disconnectHandler), conAttempt -> {
                        connecting.compareAndSet(true, false);
                        if (conAttempt.failed()) {
                            if (conAttempt.cause() instanceof SecurityException) {
                                // SASL handshake has failed
                                connectionHandler.handle(Future.failedFuture(
                                        new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                                                "failed to authenticate with server")));
                            } else {
                                reconnect(conAttempt.cause(), connectionHandler, disconnectHandler);
                            }
                        } else {
                            // make sure we try to re-connect as often as we tried to connect initially
                            reconnectAttempts = new AtomicInteger(0);
                            final ProtonConnection newConnection = conAttempt.result();
                            if (shuttingDown.get()) {
                                // if client was shut down in the meantime, we need to immediately
                                // close again the newly created connection
                                newConnection.closeHandler(null);
                                newConnection.disconnectHandler(null);
                                newConnection.close();
                                connectionHandler.handle(Future.failedFuture(new ClientErrorException(
                                        HttpURLConnection.HTTP_CONFLICT, "client is already shut down")));
                            } else {
                                setConnection(newConnection);
                                connectionHandler.handle(Future.succeededFuture(this));
                            }
                        }
                    });
        } else {
            LOG.debug("already trying to connect to server ...");
            connectionHandler.handle(Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "already connecting to server")));
        }
    });
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testConflictSetTTL() throws IOException {
    try {/*from w w w  .j  av  a 2  s .c o m*/
        streamClient.setTTL(TestUtils.CONFLICT_STREAM_NAME, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_CONFLICT, e.getStatusCode());
    }
}