Example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT

List of usage examples for javax.servlet.http HttpServletResponse SC_NO_CONTENT

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT.

Prototype

int SC_NO_CONTENT

To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.

Click Source Link

Document

Status code (204) indicating that the request succeeded but that there was no new information to return.

Usage

From source file:org.alfresco.repo.webdav.PutMethodTest.java

/**
 * Putting a zero content file and update it
 * <p>/*from  w  ww  .j a  v a2  s .  co  m*/
 * Put an empty file
 * <p>
 * Lock the file
 * <p>
 * Put the contents
 * <p>
 * Unlock the node
 */
@Test
public void testPutNoContentFileAndUpdate() throws Exception {
    String fileName = "file-" + GUID.generate();
    NodeRef fileNoderef = null;
    try {
        executeMethod(WebDAV.METHOD_PUT, fileName, new byte[0], null);

        ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home//cm:" + fileName + "\"");
        fileNoderef = resultSet.getNodeRef(0);
        resultSet.close();

        assertTrue("File should exist.", nodeService.exists(fileNoderef));
        assertEquals("Filename is not correct", fileName,
                nodeService.getProperty(fileNoderef, ContentModel.PROP_NAME));

        assertTrue("Expected return status is " + HttpServletResponse.SC_CREATED + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_CREATED == response.getStatus());
        byte[] updatedFile = IOUtils
                .toByteArray(fileFolderService.getReader(fileNoderef).getContentInputStream());
        assertTrue("The content should be empty", updatedFile.length == 0);
    } catch (Exception e) {
        throw new RuntimeException("Failed to upload a file", e);
    }

    try {
        executeMethod(WebDAV.METHOD_LOCK, fileName, davLockInfoAdminFile, null);

        assertEquals("File should be locked", LockStatus.LOCK_OWNER, lockService.getLockStatus(fileNoderef));
    } catch (Exception e) {
        throw new RuntimeException("Failed to lock a file", e);
    }

    // Construct IF HEADER
    String lockToken = fileNoderef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR
            + AuthenticationUtil.getAdminUserName();
    String lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, fileName, testDataFile, headers);

        assertTrue("File does not exist.", nodeService.exists(fileNoderef));
        assertEquals("Filename is not correct", fileName,
                nodeService.getProperty(fileNoderef, ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());

        assertTrue("File should have NO_CONTENT aspect",
                nodeService.hasAspect(fileNoderef, ContentModel.ASPECT_NO_CONTENT));
        InputStream updatedFileIS = fileFolderService.getReader(fileNoderef).getContentInputStream();
        byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
        updatedFileIS.close();
        assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
    } catch (Exception e) {
        throw new RuntimeException("Failed to upload a file", e);
    }

    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">");
    try {
        executeMethod(WebDAV.METHOD_UNLOCK, fileName, null, headers);

        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        assertFalse("File should not have NO_CONTENT aspect",
                nodeService.hasAspect(fileNoderef, ContentModel.ASPECT_NO_CONTENT));
        assertEquals("File should be unlocked", LockStatus.NO_LOCK, lockService.getLockStatus(fileNoderef));
    } catch (Exception e) {
        throw new RuntimeException("Failed to unlock a file", e);
    }

    if (fileNoderef != null) {
        nodeService.deleteNode(fileNoderef);
    }
}

From source file:org.gss_project.gss.server.rest.Webdav.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;// www  .j av a  2  s.c  om
    }

    final User user = getUser(req);
    String path = getRelativePath(req);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    try {
        resource = getService().getResourceAtPath(user.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader)
            file = (FileHeader) resource;
        else {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }
    boolean result = true;

    // Temporary content file used to support partial PUT.
    File contentFile = null;

    Range range = parseContentRange(req, resp);

    InputStream resourceInputStream = null;

    // Append data specified in ranges to existing content for this
    // resource - create a temporary file on the local filesystem to
    // perform this operation.
    // Assume just one range is specified for now
    if (range != null) {
        try {
            contentFile = executePartialPut(req, range, path);
        } catch (RpcException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
            return;
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        resourceInputStream = new FileInputStream(contentFile);
    } else
        resourceInputStream = req.getInputStream();

    try {
        Object parent = getService().getResourceAtPath(user.getId(), getParentPath(path), true);
        if (!(parent instanceof Folder)) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }
        final Folder folderLocal = (Folder) parent;
        final String name = getLastElement(path);
        final String mimeType = getServletContext().getMimeType(name);
        File uploadedFile = null;
        try {
            uploadedFile = getService().uploadFile(resourceInputStream, user.getId());
        } catch (IOException ex) {
            throw new GSSIOException(ex, false);
        }
        // FIXME: Add attributes
        FileHeader fileLocal = null;
        final FileHeader f = file;
        final File uf = uploadedFile;
        if (exists)
            fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().updateFileContents(user.getId(), f.getId(), mimeType, uf.length(),
                            uf.getAbsolutePath());
                }
            });
        else
            fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().createFile(user.getId(), folderLocal.getId(), name, mimeType,
                            uf.length(), uf.getAbsolutePath());
                }
            });
        updateAccounting(user, new Date(), fileLocal.getCurrentBody().getFileSize());
    } catch (ObjectNotFoundException e) {
        result = false;
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (result) {
        if (exists)
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        else
            resp.setStatus(HttpServletResponse.SC_CREATED);
    } else
        resp.sendError(HttpServletResponse.SC_CONFLICT);

}

From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile,
        String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from w  ww.j a  va 2s  .  c  om
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);

        final Map<String, String> headers = new HashMap<>();

        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        EasyMock.replay(request, rm);

        servlet.init();
        servlet.doPut(request, response);

        EasyMock.verify(request, rm);

        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.ednovo.gooru.controllers.v2.api.UserRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_ROLE_DELETE })
@RequestMapping(method = { RequestMethod.DELETE, RequestMethod.PUT }, value = "/{userUid}/role")
public void removeAssignedRoleByUserUid(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable(USER_UID) final String userUid, @RequestBody final String data) throws Exception {

    this.getUserManagementService()
            .removeAssignedRoleByUserUid(this.buildRoleFromInputParameters(data).getRoleId(), userUid);
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }//ww w . j  a  v  a 2s  .c  o m
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:org.apache.karaf.cave.server.maven.MavenProxyServletTest.java

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile,
        String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//w  ww .  ja va  2s . c  o  m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        CaveMavenServlet servlet = new CaveMavenServlet(resolver, 5, null, null, null);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }

            @Override
            public boolean isFinished() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // TODO Auto-generated method stub

            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);

        final Map<String, String> headers = new HashMap<>();

        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        EasyMock.replay(request, rm);

        servlet.init();
        servlet.doPut(request, response);

        EasyMock.verify(request, rm);

        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile,
        String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from w  ww . j  ava 2s .  co m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
        EasyMock.expect(request.getParameter("profile")).andReturn(profile);
        EasyMock.expect(request.getParameter("version")).andReturn(version);

        final Map<String, String> headers = new HashMap<>();

        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        EasyMock.replay(request, rm);

        servlet.start();
        servlet.doPut(request, response);

        EasyMock.verify(request, rm);

        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.gdo.servlet.RpcWrapper.java

private void facet(StclContext stclContext, RpcArgs args) throws IOException {
    HttpServletResponse response = stclContext.getResponse();

    try {/*from w w w .j  av a  2s.  c  o m*/

        // gets facet type and mode
        String type = args.getStringParameter(stclContext, FACETS_PARAM);
        String mode = args.getStringParameter(stclContext, MODES_PARAM);
        if (StringUtils.isBlank(type)) {

            // the type is undefined
            String msg = String.format("no facet defined (param %s)", FACETS_PARAM);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }

        // gets stencil
        PStcl stcl = args.getStencilFromPath(stclContext);
        if (StencilUtils.isNull(stcl)) {

            // null stencil may be accepted
            if (args.acceptNoStencil()) {
                StudioGdoServlet.writeHTMLResponse(stclContext.getResponse(), "",
                        args.getCharacterEncoding(stclContext));
                return;
            }

            // stencil may not be null
            String reason = StencilUtils.getNullReason(stcl);
            String msg = String.format("facet service : cannot found stencil at path %s : %s", args.getPath(),
                    reason);
            response.sendError(HttpServletResponse.SC_NO_CONTENT, msg);
            return;
        }

        // searches facet from stencil
        RenderContext<StclContext, PStcl> renderCtxt = new RenderContext<StclContext, PStcl>(stclContext, stcl,
                type, mode);
        FacetResult facetResult = stcl.getFacet(renderCtxt);
        if (facetResult.isNotSuccess()) {

            // error in facet
            response.sendError(HttpServletResponse.SC_NOT_FOUND, facetResult.getMessage());
            return;
        }

        // HTML facet
        if (FacetType.HTML.equals(type)) {
            StringWriter writer = new StringWriter();
            writer.write("<html>\n");
            writer.write(" <META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n");
            writer.write(" <META HTTP-EQUIV=\"Expires\" CONTENT=\"-1\">\n");
            writer.write(" <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n");
            writer.write("<body>\n");
            IOUtils.copy(facetResult.getInputStream(), writer);
            facetResult.closeInputStream();
            writer.write("</body>\n</html>\n");
            String content = stcl.format(stclContext, writer.getBuffer().toString());
            StudioGdoServlet.writeHTMLResponse(response, content, args.getCharacterEncoding(stclContext));
            return;
        }

        // HTML 5 facet or JSON facet
        if (FacetType.HTML5.equals(type) || FacetType.DOM5.equals(type) || FacetType.TRANS.equals(type)
                || FacetType.JSON.equals(type) || FacetType.JSKEL.equals(type) || FacetType.PYTHON.equals(type)
                || FacetType.REST.equals(type)) {
            String mime = facetResult.getMimeType();
            InputStream in = facetResult.getInputStream();
            StudioGdoServlet.writeResponse(stclContext.getResponse(), HttpServletResponse.SC_OK, mime, in,
                    StclContext.getCharacterEncoding());
            return;
        }

        // file facet
        if (FacetType.FILE.equals(type)) {
            if (FacetType.E4X.equals(mode)) {
                InputStream in = facetResult.getInputStream();
                String enc = StclContext.getCharacterEncoding();
                StudioGdoServlet.writeXMLResponse(stclContext.getResponse(), in, enc);
                facetResult.closeInputStream();
                return;
            }
            CatalinaUtils.writeFileResponse(stclContext, facetResult);
            return;
        }

        // write result
        Reader reader = new InputStreamReader(facetResult.getInputStream());
        XmlStringWriter writer = new XmlStringWriter(args.getCharacterEncoding(stclContext));
        writer.startElement("result");
        args.writeAttributes(stclContext, stcl, false, writer);
        addStatus(writer, Result.success());

        // not escaped as XML may be used in data
        writer.writeCDATAElement("data", StringHelper.read(reader));
        writer.endElement("result");

        // trace and response
        String xml = writer.getString();
        logTrace(stclContext, xml);
        StudioGdoServlet.writeXMLResponse(stclContext.getResponse(), xml,
                args.getCharacterEncoding(stclContext));
        facetResult.closeInputStream();
    } catch (Exception e) {
        String msg = logError(stclContext, e.toString());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc.//from   w w w. ja v  a  2s .c  o m
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponse(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
            //String resp = Messages.getMessage("noData00");
            //res.setContentLength((int) resp.getBytes().length);
            //res.getWriter().print(resp);
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
            // log.debug("Returned Content-Length:" +
            //          responseMsg.getContentLength());
        }

        try {
            res.setContentType(contentType);

            /* My understand of Content-Length
             * HTTP 1.0
             *   -Required for requests, but optional for responses.
             * HTTP 1.1
             *  - Either Content-Length or HTTP Chunking is required.
             *   Most servlet engines will do chunking if content-length is not specified.
             *
             *
             */

            //if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary.
            //     res.setContentLength(responseMsg.getContentLength());

            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable String postString(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint
                + "," + resource + "," + payload + ")");
    }//from ww w.  j a va2 s.  c  om
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/json");
        post.addHeader("X-Auth-Token", authToken);

        if (payload != null) {
            post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
        }
        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (payload != null) {
                wire.debug(payload);
                wire.debug("");
            }
        }
        HttpResponse response;

        try {
            response = client.execute(post);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("postString(): Expected ACCEPTED for POST request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED) {
                HttpEntity entity = response.getEntity();
                String json = null;

                if (entity != null) {
                    try {
                        json = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}