Example usage for org.apache.commons.httpclient HttpStatus SC_PRECONDITION_FAILED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_PRECONDITION_FAILED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_PRECONDITION_FAILED.

Prototype

int SC_PRECONDITION_FAILED

To view the source code for org.apache.commons.httpclient HttpStatus SC_PRECONDITION_FAILED.

Click Source Link

Document

<tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:davmail.exchange.dav.DavExchangeSession.java

protected void moveItem(MoveMethod method) throws IOException {
    try {/*  www. j  a va 2s .  c  o  m*/
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_ITEM");
        } else if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected void moveMessage(String sourceUrl, String targetFolder) throws IOException {
    String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
    MoveMethod method = new MoveMethod(URIUtil.encodePath(sourceUrl), targetPath, false);
    // allow rename if a message with the same name exists
    method.addRequestHeader("Allow-Rename", "t");
    try {//from   ww  w .jav  a2s  .com
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_MESSAGE");
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected void copyMessage(String sourceUrl, String targetFolder) throws IOException {
    String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
    CopyMethod method = new CopyMethod(URIUtil.encodePath(sourceUrl), targetPath, false);
    // allow rename if a message with the same name exists
    method.addRequestHeader("Allow-Rename", "t");
    try {/* ww  w. ja v a2s  .  co  m*/
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_COPY_MESSAGE");
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.alfresco.integrations.google.docs.webscripts.IsLatestRevision.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/* w w w  .  j  ava2  s  .  c o m*/

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

    /* Get the nodeRef to test */
    String param_nodeRef = req.getParameter(PARAM_NODEREF);
    NodeRef nodeRef = new NodeRef(param_nodeRef);
    log.debug("Comparing Node Revision Id from Alfresco and Google: " + nodeRef);

    /* The revision Id persisted on the node */
    String currentRevision = null;
    /* The latest revision Id from Google for the file */
    String latestRevision = null;

    try {
        /* The node needs the editingInGoogle aspect if not then tell return 412 */
        if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
            Credential credential = googledocsService.getCredential();

            /* get the nodes revision Id null if not found */
            Serializable property = nodeService.getProperty(nodeRef, GoogleDocsModel.PROP_REVISION_ID);
            currentRevision = property != null ? property.toString() : null;
            log.debug("currentRevision: " + currentRevision);

            /* get the latest revision Id null if not found */
            Revision revision = googledocsService.getLatestRevision(credential, nodeRef);
            latestRevision = revision != null ? revision.getId() : null;
            log.debug("latestRevision: " + latestRevision);

            /* compare the revision Ids */
            if (currentRevision != null && latestRevision != null) {

                isLatestRevision = currentRevision.equals(latestRevision);
            }

            model.put(MODEL_IS_LATEST_REVISION, isLatestRevision);
        } else {
            throw new WebScriptException(HttpStatus.SC_PRECONDITION_FAILED,
                    "Node: " + nodeRef.toString() + " has no revision Ids.");
        }
    } catch (GoogleDocsAuthenticationException gdae) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
    } catch (GoogleDocsServiceException gdse) {
        if (gdse.getPassedStatusCode() > -1) {
            throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
        } else {
            throw new WebScriptException(gdse.getMessage());
        }
    } catch (GoogleDocsRefreshTokenException gdrte) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
    } catch (IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
    }

    return model;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.CreationAndUpdateBaseTests.java

protected void updateCreatedResourceWithFailedPrecondition(String contentType, String accept,
        String createContent, String updateContent) throws IOException {
    HttpResponse resp = createResource(contentType, accept, createContent);
    Header location = getRequiredLocationHeader(resp);
    Header eTag = resp.getFirstHeader("ETag");
    Header lastModified = resp.getFirstHeader("Last-Modified");

    assertTrue("Either ETag(" + eTag + ") or Last-Modified(" + lastModified + ") must not be null",
            eTag != null || lastModified != null);

    int size = headers.length + 1;
    Header[] putHeaders = new Header[size];
    int i = 0;/* www .  j  a  v a 2 s .  com*/
    for (; i < headers.length; i++) {
        putHeaders[i] = headers[i];
    }
    if (eTag != null) {
        putHeaders[i++] = new BasicHeader("If-Match", "Bogus");
    } else if (lastModified != null) {
        putHeaders[i++] = new BasicHeader("If-Unmodified-Since", "Tue, 15 Nov 1994 12:45:26 GMT");
    }

    // Now, go to the url of the new change request and update it.
    resp = OSLCUtils.putDataToUrl(location.getValue(), basicCreds, accept, contentType, updateContent,
            putHeaders);
    if (resp != null && resp.getEntity() != null)
        EntityUtils.consume(resp.getEntity());

    assertEquals(HttpStatus.SC_PRECONDITION_FAILED, resp.getStatusLine().getStatusCode());

    // Clean up after the test by attempting to delete the created resource
    resp = OSLCUtils.deleteFromUrl(location.getValue(), basicCreds, "");

    if (resp != null && resp.getEntity() != null)
        EntityUtils.consume(resp.getEntity());
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default:/*from   w ww.j av a2s.  c  om*/
        return 1;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/bulb/{state}")
@POST/*from   w w w . j  a v  a2s  .  c o m*/
public void switchBulb(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @PathParam("state") String state,
        @Context HttpServletResponse response) {

    try {
        DeviceValidator deviceValidator = new DeviceValidator();
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    } catch (DeviceManagementException e) {
        log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    String switchToState = state.toUpperCase();

    if (!switchToState.equals(FireAlarmConstants.STATE_ON)
            && !switchToState.equals(FireAlarmConstants.STATE_OFF)) {
        log.error("The requested state change shoud be either - 'ON' or 'OFF'");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String deviceIP = deviceToIpMap.get(deviceId);
    if (deviceIP == null) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    }

    String protocolString = protocol.toUpperCase();
    String callUrlPattern = BULB_CONTEXT + switchToState;

    log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + "via" + " "
            + protocol);

    try {
        switch (protocolString) {
        case HTTP_PROTOCOL:
            sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            break;
        case MQTT_PROTOCOL:
            callUrlPattern = BULB_CONTEXT.replace("/", "");
            sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState);
            break;
        default:
            if (protocolString == null) {
                sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            } else {
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + " " + protocol);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    response.setStatus(HttpStatus.SC_OK);
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/fan/{state}")
@POST/*from w w  w . ja v  a2  s.  com*/
public void switchFan(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @PathParam("state") String state,
        @Context HttpServletResponse response) {

    try {
        DeviceValidator deviceValidator = new DeviceValidator();
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    } catch (DeviceManagementException e) {
        log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    String switchToState = state.toUpperCase();

    if (!switchToState.equals(FireAlarmConstants.STATE_ON)
            && !switchToState.equals(FireAlarmConstants.STATE_OFF)) {
        log.error("The requested state change shoud be either - 'ON' or 'OFF'");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String deviceIP = deviceToIpMap.get(deviceId);

    if (deviceIP == null) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    }

    String protocolString = protocol.toUpperCase();
    String callUrlPattern = FAN_CONTEXT + switchToState;

    log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + "via" + " "
            + protocol);

    try {
        switch (protocolString) {
        case HTTP_PROTOCOL:
            sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            break;
        case MQTT_PROTOCOL:
            callUrlPattern = FAN_CONTEXT.replace("/", "");
            sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState);
            break;
        default:
            if (protocolString == null) {
                sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            } else {
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + " " + protocol);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    response.setStatus(HttpStatus.SC_OK);
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/readtemperature")
@GET//w  ww .java 2  s .  c o  m
public String requestTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) {
    String replyMsg = "";

    DeviceValidator deviceValidator = new DeviceValidator();
    try {
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return "Unauthorized Access";
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    String deviceIp = deviceToIpMap.get(deviceId);

    if (deviceIp == null) {
        replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return replyMsg;
    }

    try {
        switch (protocol) {
        case HTTP_PROTOCOL:
            log.info(
                    "Sending request to read firealarm-temperature at : " + deviceIp + " via " + HTTP_PROTOCOL);

            replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
            break;

        case XMPP_PROTOCOL:
            log.info(
                    "Sending request to read firealarm-temperature at : " + deviceIp + " via " + XMPP_PROTOCOL);
            replyMsg = requestTemperatureViaXMPP(deviceIp, response);
            break;

        default:
            if (protocol == null) {
                log.info("Sending request to read firealarm-temperature at : " + deviceIp + " via "
                        + HTTP_PROTOCOL);

                replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
            } else {
                replyMsg = "Requested protocol '" + protocol + "' is not supported";
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return replyMsg;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    response.setStatus(HttpStatus.SC_OK);
    replyMsg = "The current temperature of the device is " + replyMsg;
    return replyMsg;
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/readsonar")
@GET//from  w  w  w  . ja v a  2 s .  co m
public String requestSonar(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) {
    String replyMsg = "";

    DeviceValidator deviceValidator = new DeviceValidator();
    try {
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return "Unauthorized Access";
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    String deviceIp = deviceToIpMap.get(deviceId);

    if (deviceIp == null) {
        replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return replyMsg;
    }

    try {
        switch (protocol) {
        case HTTP_PROTOCOL:
            log.info("Sending request to read firealarm-sonar at : " + deviceIp + " via " + HTTP_PROTOCOL);

            replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
            break;

        //            case XMPP_PROTOCOL:
        //               log.info("Sending request to read firealarm-sonar at : " + deviceIp +
        //                            " via " +
        //                            XMPP_PROTOCOL);
        //               replyMsg = requestTemperatureViaXMPP(deviceIp, response);
        //               break;

        default:
            if (protocol == null) {
                log.info("Sending request to read firealarm-sonar at : " + deviceIp + " via " + HTTP_PROTOCOL);

                replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
            } else {
                replyMsg = "Requested protocol '" + protocol + "' is not supported";
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return replyMsg;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        replyMsg = e.getErrorMessage();
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return replyMsg;
    }

    response.setStatus(HttpStatus.SC_OK);
    replyMsg = "The current sonar reading of the device is " + replyMsg;
    return replyMsg;
}