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:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient29.java

private List<SubmitRecord> currentSubmitRecord(String uri, IProgressMonitor monitor) throws GerritException {
    List<SubmitRecord> submitRecordList = new ArrayList<SubmitRecord>();
    SubmitRecord[] submitRecordArray = executePostRestRequest(uri, new SubmitRecord(), SubmitRecord[].class,
            new ErrorHandler() {
                @Override//ww w . j a va 2  s .com
                public void handleError(HttpMethodBase method) throws GerritException {
                    String errorMsg = getResponseBodyAsString(method);
                    if (isNotPermitted(method, errorMsg) || isConflict(method)) {
                        throw new GerritException(NLS.bind("Cannot get submit change: {0}", errorMsg)); //$NON-NLS-1$
                    }
                }

                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
                            && "submit not permitted\n".equals(msg); //$NON-NLS-1$
                }

                private boolean isConflict(HttpMethodBase method) {
                    return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT;
                }
            }, monitor);
    for (SubmitRecord element : submitRecordArray) {
        List<SubmitRecord.Label> list = null;
        if (element.getStatus().equalsIgnoreCase("OK")) { //$NON-NLS-1$
            list = element.createLabel(element, element.getOkMap(), OK);
        } else if (element.getStatus().equalsIgnoreCase("NOT_READY")) { //$NON-NLS-1$
            list = element.createLabel(element, element.getNeedMap(), NEED);
        } else if (element.getStatus().equalsIgnoreCase("REJECT")) { //$NON-NLS-1$
            list = element.createLabel(element, element.getRejectMap(), REJECT);
        } else if (element.getStatus().equalsIgnoreCase("MAY")) { //$NON-NLS-1$
            list = element.createLabel(element, element.getMayMap(), MAY);
        }
        element.setLabels(list);
        submitRecordList.add(element);
    }

    return submitRecordList;
}

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

/**
 * Updates a tenant./*ww  w .j  av a2 s  .  co m*/
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to update the tenant with.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> update(final String tenantId, final JsonObject tenantSpec) {

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

    if (getConfig().isModificationEnabled()) {
        if (tenants.containsKey(tenantId)) {
            try {
                final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
                tenant.setTenantId(tenantId);
                final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
                if (conflictingTenant != null && !tenantId.equals(conflictingTenant.getTenantId())) {
                    // we are trying to use the same CA as another tenant
                    return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
                } else {
                    tenants.put(tenantId, tenant);
                    dirty = true;
                    return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
                }
            } catch (IllegalArgumentException e) {
                return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

@Test
public void testUpdateConfigEntryUsingPOST() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        // set some dummy value
        final String ENTRY_KEY = "a.b.c";
        final String ENTRY_VALUE = "v";

        request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        JSONObject configResponse = new JSONObject(response.getText());
        String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION);

        // update config entry using POST
        final String NEW_ENTRY_VALUE = "valueABC";

        request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, NEW_ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CONFLICT, response.getResponseCode());

        // get value of config entry
        JSONObject configEntry = listConfigEntries(entryLocation);
        // assert unchanged
        assertConfigOption(configEntry, ENTRY_KEY, ENTRY_VALUE);
    }//from  w ww  . jav a2  s  . c om
}

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

private CredentialsResult<JsonObject> addCredentialsResult(final String tenantId,
        final JsonObject credentialsToAdd) {

    final String authId = credentialsToAdd.getString(CredentialsConstants.FIELD_AUTH_ID);
    final String type = credentialsToAdd.getString(CredentialsConstants.FIELD_TYPE);
    log.debug("adding credentials for device [tenant-id: {}, auth-id: {}, type: {}]", tenantId, authId, type);

    final Map<String, JsonArray> credentialsForTenant = getCredentialsForTenant(tenantId);

    final JsonArray authIdCredentials = getAuthIdCredentials(authId, credentialsForTenant);

    // check if credentials already exist with the type and auth-id from the payload
    for (final Object credentialsObj : authIdCredentials) {
        final JsonObject credentials = (JsonObject) credentialsObj;
        if (credentials.getString(CredentialsConstants.FIELD_TYPE).equals(type)) {
            return CredentialsResult.from(HttpURLConnection.HTTP_CONFLICT);
        }//w  ww .  j  av a 2 s.c o  m
    }

    authIdCredentials.add(credentialsToAdd);
    dirty = true;
    return CredentialsResult.from(HttpURLConnection.HTTP_CREATED);
}

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

@Test
public void testConflictTruncate() throws IOException {
    try {/*  ww  w.  j a  va2 s .  c  o  m*/
        streamClient.truncate(TestUtils.CONFLICT_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_CONFLICT, e.getStatusCode());
    }
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClient.java

/**
 * Execute a HTTP request and handle common error cases.
 *
 * @param connection the HttpConnection request to execute
 * @return the executed HttpConnection//  w  ww  .ja v a2  s .c  om
 * @throws CouchDbException for HTTP error codes or if an IOException was thrown
 */
public HttpConnection execute(HttpConnection connection) {

    //set our HttpUrlFactory on the connection
    connection.connectionFactory = factory;

    // all CouchClient requests want to receive application/json responses
    connection.requestProperties.put("Accept", "application/json");
    connection.responseInterceptors.addAll(this.responseInterceptors);
    connection.requestInterceptors.addAll(this.requestInterceptors);
    InputStream es = null; // error stream - response from server for a 500 etc

    // first try to execute our request and get the input stream with the server's response
    // we want to catch IOException because HttpUrlConnection throws these for non-success
    // responses (eg 404 throws a FileNotFoundException) but we need to map to our own
    // specific exceptions
    try {
        try {
            connection = connection.execute();
        } catch (HttpConnectionInterceptorException e) {
            CouchDbException exception = new CouchDbException(connection.getConnection().getResponseMessage(),
                    connection.getConnection().getResponseCode());
            exception.error = e.error;
            exception.reason = e.reason;
            throw exception;
        }
        int code = connection.getConnection().getResponseCode();
        String response = connection.getConnection().getResponseMessage();
        // everything ok? return the stream
        if (code / 100 == 2) { // success [200,299]
            return connection;
        } else {
            final CouchDbException ex;
            switch (code) {
            case HttpURLConnection.HTTP_NOT_FOUND: //404
                ex = new NoDocumentException(response);
                break;
            case HttpURLConnection.HTTP_CONFLICT: //409
                ex = new DocumentConflictException(response);
                break;
            case HttpURLConnection.HTTP_PRECON_FAILED: //412
                ex = new PreconditionFailedException(response);
                break;
            default:
                ex = new CouchDbException(response, code);
                break;
            }
            es = connection.getConnection().getErrorStream();
            //if there is an error stream try to deserialize into the typed exception
            if (es != null) {
                //read the error stream into memory
                byte[] errorResponse = IOUtils.toByteArray(es);

                Class<? extends CouchDbException> exceptionClass = ex.getClass();
                //treat the error as JSON and try to deserialize
                try {
                    //Register an InstanceCreator that returns the existing exception so we can
                    //just populate the fields, but not ignore the constructor.
                    //Uses a new Gson so we don't accidentally recycle an exception.
                    Gson g = new GsonBuilder()
                            .registerTypeAdapter(exceptionClass, new InstanceCreator<CouchDbException>() {
                                @Override
                                public CouchDbException createInstance(Type type) {
                                    return ex;
                                }
                            }).create();
                    //now populate the exception with the error/reason other info from JSON
                    g.fromJson(new InputStreamReader(new ByteArrayInputStream(errorResponse), "UTF-8"),
                            exceptionClass);
                } catch (JsonParseException e) {
                    //the error stream was not JSON so just set the string content as the error
                    // field on ex before we throw it
                    ex.error = new String(errorResponse, "UTF-8");
                }
            }
            throw ex;
        }
    } catch (IOException ioe) {
        throw new CouchDbException("Error retrieving server response", ioe);
    } finally {
        close(es);
    }
}

From source file:org.dcm4che3.tool.stowrs.StowRS.java

private static StowRSResponse sendDicomFile(String url, File f) throws IOException {
    int rspCode = 0;
    String rspMessage = null;/* ww w.  ja  va 2 s.  co  m*/

    URL newUrl = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type",
            "multipart/related; type=application/dicom; boundary=" + MULTIPART_BOUNDARY);
    connection.setRequestProperty("Accept", "application/dicom+xml");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);

    DataOutputStream wr;
    wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "\r\n");
    wr.writeBytes("Content-Disposition: inline; name=\"file[]\"; filename=\"" + f.getName() + "\"\r\n");
    wr.writeBytes("Content-Type: application/dicom \r\n");
    wr.writeBytes("\r\n");
    FileInputStream fis = new FileInputStream(f);
    StreamUtils.copy(fis, wr);
    fis.close();
    wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "--\r\n");
    wr.flush();
    wr.close();
    String response = connection.getResponseMessage();
    rspCode = connection.getResponseCode();
    rspMessage = connection.getResponseMessage();
    LOG.info("response: " + response);
    Attributes responseAttrs = null;
    try {
        InputStream in;
        boolean isErrorCase = rspCode >= HttpURLConnection.HTTP_BAD_REQUEST;
        if (!isErrorCase) {
            in = connection.getInputStream();
        } else {
            in = connection.getErrorStream();
        }
        if (!isErrorCase || rspCode == HttpURLConnection.HTTP_CONFLICT)
            responseAttrs = SAXReader.parse(in);
    } catch (SAXException e) {
        throw new IOException(e);
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }
    connection.disconnect();

    return new StowRSResponse(rspCode, rspMessage, responseAttrs);
}

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

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

From source file:org.eclipse.orion.server.tests.servlets.git.GitCheckoutTest.java

@Test
public void testCheckoutAborted() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        JSONObject testTxt = getChild(folder, "test.txt");

        // create branch
        clone = getCloneForGitResource(testTxt);
        response = branch(clone.getString(GitConstants.KEY_BRANCH), "branch");

        // change on the branch
        modifyFile(testTxt, "master change");

        addFile(testTxt);/*ww  w.j  av  a2  s .  com*/

        commitFile(testTxt, "commit on master", false);

        // local change, not committed
        modifyFile(testTxt, "working tree change");

        // checkout
        response = checkoutBranch(clone.getString(ProtocolConstants.KEY_LOCATION), "branch");
        assertEquals(HttpURLConnection.HTTP_CONFLICT, response.getResponseCode());
        JSONObject result = new JSONObject(response.getText());
        assertEquals(HttpURLConnection.HTTP_CONFLICT, result.getInt("HttpCode"));
        assertEquals("Error", result.getString("Severity"));
        assertEquals("Checkout aborted.", result.getString("Message"));
        assertEquals("Checkout conflict with files: \ntest.txt", result.getString("DetailedMessage"));
    }
}

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

public ChangeDetail restore(String reviewId, int patchSetId, final String message, 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() + "/restore"; //$NON-NLS-1$ //$NON-NLS-2$
    try {//  www .  j a v a2  s  .  com
        executePostRestRequest(uri, new RestoreInput(message), ChangeInfo.class, null/*no error handler*/,
                monitor);
    } catch (GerritHttpException e) {
        if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT) {
            throw new GerritException("Not Found", e); //$NON-NLS-1$
        }
    }
    return getChangeDetail(id.getParentKey().get(), monitor);
}