Package org.restlet.data

Examples of org.restlet.data.Status


     *            The high-level request.
     * @return The result status.
     */
    @Override
    public Status sendRequest(Request request) {
        Status result = null;
        Representation entity = request.isEntityAvailable() ? request
                .getEntity() : null;

        // Get the connector service to callback
        org.restlet.service.ConnectorService connectorService = ConnectorHelper
                .getConnectorService();
        if (connectorService != null) {
            connectorService.beforeSend(entity);
        }

        try {
            try {
                // Set the request headers
                List<MessageHeader> headers = new CopyOnWriteArrayList<SdcFrame.MessageHeader>();

                for (Parameter header : getRequestHeaders()) {
                    if (!header.getName().equals(
                            HeaderConstants.HEADER_CONTENT_LENGTH)
                            && !header.getName().equals(
                                    HeaderConstants.HEADER_PROXY_AUTHORIZATION)) {
                        headers.add(MessageHeader.newBuilder()
                                .setKey(header.getName())
                                .setValue(header.getValue()).build());
                    }
                }

                if (!Method.GET.equals(request.getMethod())) {
                    headers.add(MessageHeader.newBuilder()
                            .setKey("x-sdc-http-method")
                            .setValue(request.getMethod().getName()).build());
                }

                if (entity != null) {
                    OutputStream requestStream = getRequestEntityStream();

                    if (requestStream != null) {
                        entity.write(requestStream);
                        requestStream.flush();
                        requestStream.close();

                        // Build the fetch request
                        setFetchRequest(FetchRequest
                                .newBuilder()
                                .setId(UUID.randomUUID().toString())
                                .setResource(
                                        request.getResourceRef().toString())
                                .setStrategy("HTTPClient")
                                .addAllHeaders(headers)
                                .setContents(
                                        ByteString
                                                .copyFrom(this.requestEntityStream
                                                        .toByteArray()))
                                .build());
                    }
                } else {
                    // Build the fetch request
                    setFetchRequest(FetchRequest.newBuilder()
                            .setId(UUID.randomUUID().toString())
                            .setResource(request.getResourceRef().toString())
                            .setStrategy("HTTPClient").addAllHeaders(headers)
                            .build());
                }

                getConnection().sendRequest(this);

                // Block the thread until we receive the response or a
                // timeout occurs
                if (!getLatch()
                        .await(IoUtils.TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                    // Timeout detected
                    result = new Status(Status.CONNECTOR_ERROR_INTERNAL,
                            "The calling thread timed out while waiting for a response to unblock it.");
                } else {
                    result = Status.valueOf(getFetchReply().getStatus());
                }
            } catch (Exception e) {
                getHelper()
                        .getLogger()
                        .log(Level.FINE,
                                "An unexpected error occurred during the sending of the HTTP request.",
                                e);
                result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e);
            }

            // Now we can access the status code, this MUST happen after closing
            // any open request stream.
            result = new Status(getStatusCode(), null, getReasonPhrase(), null);
        } catch (IOException ioe) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An error occured during the communication with the remote HTTP server.",
                            ioe);
            result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
        } finally {
            if (entity != null) {
                entity.release();
            }

View Full Code Here


    assertEqualMediaType(MediaType.TEXT_PLAIN, actualMediaType);
  }

  public void testGetPlainText() throws Exception {
    final Response response = get(MediaType.TEXT_PLAIN);
    final Status status = response.getStatus();
    assertTrue("Status should be 2xx, but is " + status, status.isSuccess());
    final Representation representation = response.getEntity();
    assertEquals(CarListResource.DUMMY_CAR_LIST, representation.getText());
    assertEqualMediaType(MediaType.TEXT_PLAIN,
        representation.getMediaType());
  }
View Full Code Here

                        getClientDispatcher().handle(contextRequest,
                                contextResponse);
                    } else {
                        // We found variants, but not the right one
                        contextResponse
                                .setStatus(new Status(
                                        Status.CLIENT_ERROR_NOT_ACCEPTABLE,
                                        "Unable to process properly the request. Several variants exist but none of them suits precisely. "));
                    }
                } else {
                    contextResponse.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
View Full Code Here

     * @param request
     *            The high-level request.
     * @return the status of the communication
     */
    public Status sendRequest(Request request) {
        Status result = null;
        Representation entity = request.isEntityAvailable() ? request
                .getEntity() : null;

        // Get the connector service to callback
        org.restlet.service.ConnectorService connectorService = ConnectorHelper
                .getConnectorService();
        if (connectorService != null) {
            connectorService.beforeSend(entity);
        }

        try {
            if (entity != null) {

                // In order to workaround bug #6472250
                // (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6472250),
                // it is very important to reuse that exact same "requestStream"
                // reference when manipulating the request stream, otherwise
                // "insufficient data sent" exceptions will occur in
                // "fixedLengthMode"
                OutputStream requestStream = getRequestEntityStream();
                java.nio.channels.WritableByteChannel requestChannel = getRequestEntityChannel();

                if (requestChannel != null) {
                    entity.write(requestChannel);
                    requestChannel.close();
                } else if (requestStream != null) {
                    entity.write(requestStream);
                    requestStream.flush();
                    requestStream.close();
                }
            }

            // Now we can access the status code, this MUST happen after closing
            // any open request stream.
            result = new Status(getStatusCode(), null, getReasonPhrase(), null);
        } catch (IOException ioe) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An error occured during the communication with the remote HTTP server.",
                            ioe);
            result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
        } finally {
            if (entity != null) {
                entity.release();
            }

View Full Code Here

        boolean isDirectory = false;

        if (file.exists()) {
            if (file.isDirectory()) {
                isDirectory = true;
                response.setStatus(new Status(Status.CLIENT_ERROR_FORBIDDEN,
                        "Can't put a new representation of a directory"));
                return;
            }
        } else {
            // No existing file or directory found
            if (path.endsWith("/")) {
                isDirectory = true;

                // Create a new directory and its parents if necessary
                if (file.mkdirs()) {
                    response.setStatus(Status.SUCCESS_NO_CONTENT);
                } else {
                    getLogger().log(Level.WARNING,
                            "Unable to create the new directory");
                    response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL,
                            "Unable to create the new directory"));
                }

                return;
            }
        }

        if (!isDirectory) {
            // Several checks : first the consistency of the metadata and the
            // filename
            boolean partialPut = !request.getRanges().isEmpty();

            if (!checkMetadataConsistency(file.getName(), request.getEntity())) {
                // Ask the client to reiterate properly its request
                response.setStatus(new Status(Status.CLIENT_ERROR_BAD_REQUEST,
                        "The metadata are not consistent with the URI"));
                return;
            }

            // We look for the possible variants
            // Set up base name as the longest part of the name without known
            // extensions (beginning from the left)
            final String baseName = Entity.getBaseName(file.getName(),
                    getMetadataService());

            // Look for resources with the same base name
            FileFilter filter = new FileFilter() {
                public boolean accept(File file) {
                    return file.isFile()
                            && baseName.equals(Entity.getBaseName(
                                    file.getName(), getMetadataService()));
                }
            };

            File[] files = file.getParentFile().listFiles(filter);
            File uniqueVariant = null;
            List<File> variantsList = new ArrayList<File>();

            if (files != null && files.length > 0) {
                // Set the list of extensions, due to the file name and the
                // default metadata.
                // TODO It seems we could handle more clearly the equivalence
                // between the file name space and the target resource (URI
                // completed by default metadata)
                Variant variant = new Variant();
                Entity.updateMetadata(file.getName(), variant, false,
                        getMetadataService());
                Collection<String> extensions = Entity.getExtensions(variant,
                        getMetadataService());

                for (File entry : files) {
                    Collection<String> entryExtensions = Entity.getExtensions(
                            entry.getName(), getMetadataService());

                    if (entryExtensions.containsAll(extensions)) {
                        variantsList.add(entry);

                        if (extensions.containsAll(entryExtensions)) {
                            // The right representation has been found.
                            uniqueVariant = entry;
                        }
                    }
                }
            }

            if (uniqueVariant != null) {
                file = uniqueVariant;
            } else {
                if (!variantsList.isEmpty()) {
                    // Negotiated resource (several variants, but not the right
                    // one). Check if the request could be completed or not.
                    // The request could be more precise
                    response.setStatus(new Status(
                            Status.CLIENT_ERROR_NOT_ACCEPTABLE,
                            "Unable to process properly the request. Several variants exist but none of them suits precisely."));
                    return;
                }

                // This resource does not exist, yet. Complete it with the
                // default metadata
                Entity.updateMetadata(file.getName(), request.getEntity(),
                        true, getMetadataService());

                // Update the URI
                StringBuilder fileName = new StringBuilder(baseName);

                for (Language language : request.getEntity().getLanguages()) {
                    updateFileExtension(fileName, language);
                }

                for (Encoding encoding : request.getEntity().getEncodings()) {
                    updateFileExtension(fileName, encoding);
                }

                // It is important to finish with the media type as it is
                // often leveraged by operating systems to detect file type
                updateFileExtension(fileName, request.getEntity()
                        .getMediaType());

                file = new File(file.getParentFile(), fileName.toString());
            }

            // Before putting the file representation, we check that all the
            // extensions are known
            if (!checkExtensionsConsistency(file)) {
                response.setStatus(new Status(
                        Status.SERVER_ERROR_INTERNAL,
                        "Unable to process properly the URI. At least one extension is not known by the server."));
                return;
            }

            File tmp = null;
            boolean error = false;

            if (file.exists()) {
                // The PUT call is handled in two phases:
                // 1- write a temporary file
                // 2- rename the target file
                if (partialPut) {
                    RandomAccessFile raf = null;

                    // Replace the content of the file. First, create a
                    // temporary file
                    try {
                        // The temporary file used for partial PUT.
                        tmp = new File(file.getCanonicalPath() + "."
                                + getTemporaryExtension());
                        // Support only one range.
                        Range range = request.getRanges().get(0);

                        if (tmp.exists() && !isResumeUpload()) {
                            BioUtils.delete(tmp);
                        }

                        if (!tmp.exists()) {
                            // Copy the target file.
                            InputStream in = new FileInputStream(file);
                            OutputStream out = new FileOutputStream(tmp);
                            BioUtils.copy(in, out);
                            out.flush();
                            out.close();
                        }

                        raf = new RandomAccessFile(tmp, "rwd");

                        // Go to the desired offset.
                        if (range.getIndex() == Range.INDEX_LAST) {
                            if (raf.length() <= range.getSize()) {
                                raf.seek(range.getSize());
                            } else {
                                raf.seek(raf.length() - range.getSize());
                            }
                        } else {
                            raf.seek(range.getIndex());
                        }

                        // Write the entity to the temporary file.
                        if (request.isEntityAvailable()) {
                            BioUtils.copy(request.getEntity().getStream(), raf);
                        }
                    } catch (IOException ioe) {
                        getLogger().log(Level.WARNING,
                                "Unable to create the temporary file", ioe);
                        response.setStatus(new Status(
                                Status.SERVER_ERROR_INTERNAL,
                                "Unable to create a temporary file"));
                        error = true;
                    } finally {
                        try {
                            if (raf != null) {
                                raf.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().log(Level.WARNING,
                                    "Unable to close the temporary file", ioe);
                            response.setStatus(Status.SERVER_ERROR_INTERNAL,
                                    ioe);
                            error = true;
                        }
                    }
                } else {
                    FileOutputStream fos = null;
                    try {
                        tmp = File.createTempFile("restlet-upload", "bin");
                        if (request.isEntityAvailable()) {
                            fos = new FileOutputStream(tmp);
                            BioUtils.copy(request.getEntity().getStream(), fos);
                        }
                    } catch (IOException ioe) {
                        getLogger().log(Level.WARNING,
                                "Unable to create the temporary file", ioe);
                        response.setStatus(new Status(
                                Status.SERVER_ERROR_INTERNAL,
                                "Unable to create a temporary file"));
                        error = true;
                    } finally {
                        try {
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().log(Level.WARNING,
                                    "Unable to close the temporary file", ioe);
                            response.setStatus(Status.SERVER_ERROR_INTERNAL,
                                    ioe);
                            error = true;
                        }
                    }
                }

                if (error) {
                    if (tmp.exists() && !isResumeUpload()) {
                        BioUtils.delete(tmp);
                    }

                    return;
                }

                // Then delete the existing file
                if (tmp.exists() && BioUtils.delete(file)) {
                    // Finally move the temporary file to the existing file
                    // location
                    boolean renameSuccessful = false;
                    if (tmp.renameTo(file)) {
                        if (request.getEntity() == null) {
                            response.setStatus(Status.SUCCESS_NO_CONTENT);
                        } else {
                            response.setStatus(Status.SUCCESS_OK);
                        }

                        renameSuccessful = true;
                    } else {
                        // Many aspects of the behavior of the method "renameTo"
                        // are inherently platform-dependent: the rename
                        // operation might not be able to move a file from one
                        // file system to another.
                        if (tmp.exists()) {
                            try {
                                InputStream in = new FileInputStream(tmp);
                                OutputStream out = new FileOutputStream(file);
                                BioUtils.copy(in, out);
                                out.close();
                                renameSuccessful = true;
                                BioUtils.delete(tmp);
                            } catch (Exception e) {
                                renameSuccessful = false;
                            }
                        }
                        if (!renameSuccessful) {
                            getLogger()
                                    .log(Level.WARNING,
                                            "Unable to move the temporary file to replace the existing file");
                            response.setStatus(new Status(
                                    Status.SERVER_ERROR_INTERNAL,
                                    "Unable to move the temporary file to replace the existing file"));
                        }
                    }
                } else {
                    getLogger().log(Level.WARNING,
                            "Unable to delete the existing file");
                    response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL,
                            "Unable to delete the existing file"));

                    if (tmp.exists() && !isResumeUpload()) {
                        BioUtils.delete(tmp);
                    }
                }
            } else {
                // The file does not exist yet.
                File parent = file.getParentFile();

                if ((parent != null) && !parent.exists()) {
                    // Create the parent directories then the new file
                    if (!parent.mkdirs()) {
                        getLogger().log(Level.WARNING,
                                "Unable to create the parent directory");
                        response.setStatus(new Status(
                                Status.SERVER_ERROR_INTERNAL,
                                "Unable to create the parent directory"));
                    }
                }

                // Create the new file
                if (partialPut) {
                    // This is a partial PUT
                    RandomAccessFile raf = null;
                    try {
                        raf = new RandomAccessFile(file, "rwd");
                        // Support only one range.
                        Range range = request.getRanges().get(0);
                        // Go to the desired offset.
                        if (range.getIndex() == Range.INDEX_LAST) {
                            if (raf.length() <= range.getSize()) {
                                raf.seek(range.getSize());
                            } else {
                                raf.seek(raf.length() - range.getSize());
                            }
                        } else {
                            raf.seek(range.getIndex());
                        }
                        // Write the entity to the file.
                        if (request.isEntityAvailable()) {
                            BioUtils.copy(request.getEntity().getStream(), raf);
                        }
                    } catch (FileNotFoundException fnfe) {
                        getLogger().log(Level.WARNING,
                                "Unable to create the new file", fnfe);
                        response.setStatus(Status.SERVER_ERROR_INTERNAL, fnfe);
                    } catch (IOException ioe) {
                        getLogger().log(Level.WARNING,
                                "Unable to create the new file", ioe);
                        response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe);
                    } finally {
                        try {
                            if (raf != null) {
                                raf.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().log(Level.WARNING,
                                    "Unable to close the new file", ioe);
                            response.setStatus(Status.SERVER_ERROR_INTERNAL,
                                    ioe);
                        }
                    }

                } else {
                    // This is simple PUT of the full entity
                    FileOutputStream fos = null;

                    try {
                        if (file.createNewFile()) {
                            if (request.getEntity() == null) {
                                response.setStatus(Status.SUCCESS_NO_CONTENT);
                            } else {
                                fos = new FileOutputStream(file);
                                BioUtils.copy(request.getEntity().getStream(),
                                        fos);
                                response.setStatus(Status.SUCCESS_CREATED);
                            }
                        } else {
                            getLogger().log(Level.WARNING,
                                    "Unable to create the new file");
                            response.setStatus(new Status(
                                    Status.SERVER_ERROR_INTERNAL,
                                    "Unable to create the new file"));
                        }
                    } catch (FileNotFoundException fnfe) {
                        getLogger().log(Level.WARNING,
View Full Code Here

     *            The response updated.
     * @return The representation of the given status.
     */
    public Status getStatus(Throwable throwable, Request request,
            Response response) {
        Status result = null;

        if (throwable instanceof ResourceException) {
            ResourceException re = (ResourceException) throwable;

            if (re.getCause() != null) {
                // What is most interesting is the embedded cause
                result = new Status(re.getStatus(), re.getCause());
            } else {
                result = re.getStatus();
            }
        } else {
            result = new Status(Status.SERVER_ERROR_INTERNAL, throwable);
        }

        return result;
    }
View Full Code Here

     *            The high-level request.
     * @return The result status.
     */
    @Override
    public Status sendRequest(Request request) {
        Status result = null;

        try {
            if (request.isEntityAvailable()) {
                Representation entity = request.getEntity();

                // These properties can only be used with Java 1.5 and upper
                // releases
                int majorVersionNumber = SystemUtils.getJavaMajorVersion();
                int minorVersionNumber = SystemUtils.getJavaMinorVersion();
                if ((majorVersionNumber > 1)
                        || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) {
                    // Adjust the streaming mode
                    if (entity.getSize() != -1) {
                        // The size of the entity is known in advance
                        getConnection().setFixedLengthStreamingMode(
                                (int) entity.getSize());
                    } else {
                        // The size of the entity is not known in advance
                        if (getHelper().getChunkLength() >= 0) {
                            // Use chunked encoding
                            getConnection().setChunkedStreamingMode(
                                    getHelper().getChunkLength());
                        } else {
                            // Use entity buffering to determine the content
                            // length
                        }
                    }
                }
            }

            // Set the request method
            getConnection().setRequestMethod(getMethod());

            // Set the request headers
            for (Parameter header : getRequestHeaders()) {
                getConnection().addRequestProperty(header.getName(),
                        header.getValue());
            }

            if ((Edition.CURRENT == Edition.GAE)
                    && (request.getProtocol() == Protocol.SDC)) {
                // This is to ensure portable code with other Restlet editions.
                // that uses the proxy authorization header to transmit SDC
                // security parameters (not required on GAE).
                getConnection().getRequestProperties().remove(
                        HeaderConstants.HEADER_PROXY_AUTHORIZATION);
                getConnection().setRequestProperty("use_intranet", "true");
            }

            // Ensure that the connection is active
            getConnection().connect();

            // Send the optional entity
            result = super.sendRequest(request);
        } catch (ConnectException ce) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An error occurred during the connection to the remote HTTP server.",
                            ce);
            result = new Status(Status.CONNECTOR_ERROR_CONNECTION, ce);
        } catch (SocketTimeoutException ste) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An timeout error occurred during the communication with the remote HTTP server.",
                            ste);
            result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ste);
        } catch (FileNotFoundException fnfe) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An unexpected error occurred during the sending of the HTTP request.",
                            fnfe);
            result = new Status(Status.CONNECTOR_ERROR_INTERNAL, fnfe);
        } catch (IOException ioe) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An error occurred during the communication with the remote HTTP server.",
                            ioe);
            result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
        } catch (Exception e) {
            getHelper()
                    .getLogger()
                    .log(Level.FINE,
                            "An unexpected error occurred during the sending of the HTTP request.",
                            e);
            result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e);
        }

        return result;
    }
View Full Code Here

                // Send the request to the client
                httpCall.sendRequest(request, response, new Uniform() {
                    public void handle(Request request, Response response) {
                        try {
                            updateResponse(response,
                                    new Status(httpCall.getStatusCode(), null,
                                            httpCall.getReasonPhrase(), null),
                                    httpCall);
                            userCallback.handle(request, response);
                        } catch (Exception e) {
                            // Unexpected exception occurred
View Full Code Here

        clientResource = null;
        super.tearDown();
    }

    public void testGet() throws IOException, ResourceException {
        Status status = null;
        try {
            clientResource.get();
            status = clientResource.getStatus();
        } catch (ResourceException e) {
            status = e.getStatus();
View Full Code Here

    private RequestHandledException handleInvocationTargetExc(
            InvocationTargetException ite) throws RequestHandledException {
        Throwable cause = ite.getCause();
        if (cause instanceof ResourceException) {
            // avoid mapping to a JAX-RS Response and back to a Restlet Response
            Status status = ((ResourceException) cause).getStatus();
            Response restletResponse = tlContext.get().getResponse();
            restletResponse.setStatus(status);
        } else {
            javax.ws.rs.core.Response jaxRsResp = this.providers.convert(cause);
            jaxRsRespToRestletResp(jaxRsResp, null);
View Full Code Here

TOP

Related Classes of org.restlet.data.Status

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.