Example usage for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE

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

Introduction

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

Prototype

int SC_NOT_ACCEPTABLE

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

Click Source Link

Document

Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Usage

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*  w w  w . j av  a 2s. c  om*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:org.sprintapi.api.http.HttpServlet.java

protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ErrorException, IOException {

    final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest));
    request.setContext(httpRequest.getContextPath());

    // Resolve incoming URL and get resource descriptor
    final ResourceDescriptor resourceDsc = resolve(request.getUri());

    // Does the requested resource exist?
    if (resourceDsc == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND);
    }//  ww w. j  a v a2s  .  c  om

    // Is requested method supported?
    if (httpRequest.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US)));

    } catch (IllegalArgumentException ex) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    if (request.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get supported methods for requested resource
    Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods();

    // Get requested method descriptors for the resource
    MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null;

    // Is requested method supported?
    if ((methodDsc == null)) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    ContentAdapter<InputStream, ?> inputContentAdapter = null;

    // Is request body expected?
    if (request.getMethod().isRequestBody()) {
        String requestContentType = httpRequest.getContentType();

        inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType)
                : null;
        if (inputContentAdapter == null) {
            throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

    } else if (httpRequest.getContentLength() > 0) {
        // Unexpected request body
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    ContentAdapter<?, InputStream> outputContentAdapter = null;

    String responseContentType = null;

    // Is response body expected?
    if (request.getMethod().isResponseBody()) {
        // Check Accept header
        HttpAcceptHeader acceptHeader = HttpAcceptHeader
                .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT));
        if (acceptHeader != null) {

            Map<String, ?> produces = methodDsc.produces();

            // Response content negotiation 
            if (produces != null) {
                int weight = 0;

                for (String ct : produces.keySet()) {
                    int tw = acceptHeader.accept(ct);
                    if (tw > weight) {
                        weight = tw;
                        responseContentType = ct;
                        outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct);
                    }
                }
            }
            if (outputContentAdapter == null) {
                throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        }
    }

    if (inputContentAdapter != null) {
        ContentHolder<Object> lc = new ContentHolder<Object>();
        lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream()));
        request.setContent(lc);
    }

    // Invoke resource method
    Response response = methodDsc.invoke((Request) request);

    if (response == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // Write response status
    int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK;
    httpResponse.setStatus(responseStatus);

    if (response.getContent() == null) {
        return;
    }

    // Write response headers
    if (response.getContent().getMetaNames() != null) {
        for (String metaName : response.getContent().getMetaNames()) {
            Object metaValue = response.getContent().getMeta(metaName);
            if (metaValue != null) {
                if (metaValue instanceof Date) {
                    httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue)));
                } else {
                    httpResponse.setHeader(metaName, metaValue.toString());
                }
            }
        }
    }

    if ((HttpServletResponse.SC_CREATED == responseStatus)) {
        httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri());
    }

    if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) {
        return;
    }

    // Write response body
    if (outputContentAdapter != null) {
        httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType);
        InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter)
                .transform(request.getUri(), response.getContent().getBody());
        if (is != null) {
            CopyUtils.copy(is, httpResponse.getOutputStream());
        }
    }
}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/* w  ww .ja  va2  s  . co m*/
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:org.dataconservancy.ui.api.DataItemController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleDataItemGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException {

    // Check to see if the user is authenticated (TODO: have Spring Security be responsible for this?)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;// w  w  w.  j av  a  2  s.  c o m
    }
    // Resolve the Request URL to the ID of the DataItem (in this case URL == ID)
    String dataItemId = requestUtil.buildRequestUrl(request);

    if (dataItemId == null || dataItemId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // Get the DataItem
    final DataItem dataItem = getDataItem(dataItemId);
    // Calculate the ETag for the DataItem, may be null.
    final String etag;
    if (dataItem != null) {
        etag = calculateEtag(dataItem);
    } else {
        etag = null;
    }
    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, dataItem, etag,
            dataItemId, "DataItem")) {
        return;
    }

    final DateTime lastModified;
    if (dataItem != null) {
        lastModified = getLastModified(dataItem.getId());
    } else {
        lastModified = null;
    }
    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, dataItem, etag, dataItemId,
            lastModified, modifiedSince)) {
        return;
    }

    if (dataItem == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }
    // Check to see if the user is authorized
    if (!authzService.canRetrieveDataSet(authenticatedUser, dataItem)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addDataItem(dataItem);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();
    // Compose the Response (headers, entity body)

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsManagementProcessor.java

/**
 * Login operation for remote analytics api servlet.
 *
 * @param req HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException/*from ww  w  .j a v  a 2  s  .  c om*/
 * @throws IOException
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
    if (operation != null && operation.equalsIgnoreCase(AnalyticsAPIConstants.LOGIN_OPERATION)) {
        String[] credentials = getUserPassword(req.getHeader(AnalyticsAPIConstants.AUTHORIZATION_HEADER));
        if (credentials == null) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication!");
        } else {
            String userName = credentials[0];
            String password = credentials[1];
            try {
                String sessionId = ServiceHolder.getAuthenticator().authenticate(userName, password);
                PrintWriter writer = resp.getWriter();
                writer.print(AnalyticsAPIConstants.SESSION_ID + AnalyticsAPIConstants.SEPARATOR + sessionId);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsAPIAuthenticationException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized user: " + userName);
            }
        }
    } else if (operation != null
            && operation.equalsIgnoreCase(AnalyticsAPIConstants.IS_PAGINATION_SUPPORTED_OPERATION)) {
        String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
        if (sessionId == null || sessionId.trim().isEmpty()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        } else {
            try {
                ServiceHolder.getAuthenticator().validateSessionId(sessionId);
            } catch (AnalyticsAPIAuthenticationException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
            }
        }
        String recordStoreName = req.getParameter(AnalyticsAPIConstants.RECORD_STORE_NAME_PARAM);

        try {
            boolean isSupported = ServiceHolder.getAnalyticsDataService()
                    .isPaginationSupported(recordStoreName);
            PrintWriter writer = resp.getWriter();
            writer.print(
                    AnalyticsAPIConstants.PAGINATION_SUPPORT + AnalyticsAPIConstants.SEPARATOR + isSupported);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (AnalyticsException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } else if (operation != null
            && operation.equalsIgnoreCase(AnalyticsAPIConstants.IS_RECORD_COUNT_SUPPORTED_OPERATION)) {
        String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
        if (sessionId == null || sessionId.trim().isEmpty()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        } else {
            try {
                ServiceHolder.getAuthenticator().validateSessionId(sessionId);
            } catch (AnalyticsAPIAuthenticationException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
            }
        }
        String recordStoreName = req.getParameter(AnalyticsAPIConstants.RECORD_STORE_NAME_PARAM);

        try {
            boolean isSupported = ServiceHolder.getAnalyticsDataService()
                    .isRecordCountSupported(recordStoreName);
            PrintWriter writer = resp.getWriter();
            writer.print(
                    AnalyticsAPIConstants.RECORD_COUNT_SUPPORT + AnalyticsAPIConstants.SEPARATOR + isSupported);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (AnalyticsException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Unavailable operation provided!");
        log.error("unsupported operation performed : " + operation + " with get request!");
    }
}

From source file:com.homesnap.webserver.AbstractRestApi.java

protected JSONObject putRequestJSONObject(String urn, String body, int returnCodeExpected) {
    Client client = Client.create();/*from   ww w.  j a  v a2s  . c  o m*/
    WebResource webResource = client.resource("http://" + server + ":" + port + urn);

    String json = null;
    try {
        ClientResponse response = webResource.accept("application/json").put(ClientResponse.class, body);
        Assert.assertEquals(returnCodeExpected, response.getStatus());
        if (returnCodeExpected == HttpServletResponse.SC_NOT_IMPLEMENTED
                || returnCodeExpected == HttpServletResponse.SC_NOT_ACCEPTABLE
                || returnCodeExpected == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            return null;
        }
        json = response.getEntity(String.class);
        return JSonTools.fromJson(json);
    } catch (JSONException e) {
        e.printStackTrace();
        Assert.fail("Problem with JSON [" + json + "] :" + e.getMessage());
    }
    Assert.fail("Problem when call [" + urn + "].");
    return null;
}

From source file:org.dataconservancy.ui.api.CollectionController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleCollectionGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException, BizInternalException {

    // Check to see if the user is authenticated (TODO: Spring Security should be responsible for this)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;//from  w w  w  .ja  v a 2 s  .c  om
    }

    // Resolve the Request URL to the ID of the Collection (in this case URL == ID)
    String collectionId = requestUtil.buildRequestUrl(request);

    if (collectionId == null || collectionId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Get the Collection
    final Collection collection = getCollection(collectionId);

    // Calculate the ETag for the Collection, may be null.
    final String etag;
    if (collection != null) {
        etag = calculateEtag(collection);
    } else {
        etag = null;
    }

    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, collection, etag,
            collectionId, "Collection")) {
        return;
    }

    final DateTime lastModified;
    if (collection != null) {
        lastModified = getLastModified(collection.getId());
    } else {
        lastModified = null;
    }

    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, collection, etag,
            collectionId, lastModified, modifiedSince)) {
        return;
    }

    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }

    // Check to see if the user is authorized
    if (!authzService.canRetrieveCollection(authenticatedUser, collection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addCollection(collection);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabUploadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from  w  ww.  j a  v a2 s.  c om
    LabUploadForm frm = (LabUploadForm) form;
    FormFile importFile = frm.getImportFile();

    String signature = request.getParameter("signature");
    String key = request.getParameter("key");
    String service = request.getParameter("service");
    String outcome = "";
    String audit = "";
    Integer httpCode = 200;

    ArrayList<Object> clientInfo = getClientInfo(service);
    PublicKey clientKey = (PublicKey) clientInfo.get(0);
    String type = (String) clientInfo.get(1);

    try {

        InputStream is = decryptMessage(importFile.getInputStream(), key, clientKey);
        String fileName = importFile.getFileName();
        String filePath = Utilities.saveFile(is, fileName);
        importFile.getInputStream().close();
        File file = new File(filePath);

        if (validateSignature(clientKey, signature, file)) {
            logger.debug("Validated Successfully");
            MessageHandler msgHandler = HandlerClassFactory.getHandler(type);

            if (type.equals("HHSEMR") && OscarProperties.getInstance()
                    .getProperty("lab.hhsemr.filter_ordering_provider", "false").equals("true")) {
                logger.info("Applying filter to HHS EMR lab");
                String hl7Data = FileUtils.readFileToString(file, "UTF-8");
                HHSEmrDownloadHandler filterHandler = new HHSEmrDownloadHandler();
                filterHandler.init(hl7Data);
                OtherId providerOtherId = OtherIdManager.searchTable(OtherIdManager.PROVIDER, "STAR",
                        filterHandler.getClientRef());
                if (providerOtherId == null) {
                    logger.info("Filtering out this message, as we don't have client ref "
                            + filterHandler.getClientRef() + " in our database (" + file + ")");
                    outcome = "uploaded";
                    request.setAttribute("outcome", outcome);
                    return mapping.findForward("success");
                }
            }

            is = new FileInputStream(file);
            try {
                int check = FileUploadCheck.addFile(file.getName(), is, "0");
                if (check != FileUploadCheck.UNSUCCESSFUL_SAVE) {
                    if ((audit = msgHandler.parse(service, filePath, check)) != null) {
                        outcome = "uploaded";
                        httpCode = HttpServletResponse.SC_OK;
                    } else {
                        outcome = "upload failed";
                        httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    }
                } else {
                    outcome = "uploaded previously";
                    httpCode = HttpServletResponse.SC_CONFLICT;
                }
            } finally {
                is.close();
            }
        } else {
            logger.info("failed to validate");
            outcome = "validation failed";
            httpCode = HttpServletResponse.SC_NOT_ACCEPTABLE;
        }
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
        outcome = "exception";
        httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    request.setAttribute("outcome", outcome);
    request.setAttribute("audit", audit);

    if (request.getParameter("use_http_response_code") != null) {
        try {
            response.sendError(httpCode, outcome);
        } catch (IOException e) {
            logger.error("Error", e);
        }
        return (null);
    } else
        return mapping.findForward("success");
}

From source file:com.homesnap.webserver.ControllerRestAPITest.java

@Test
public void test07PutControllerFromLabel() {
    // Test controller add in a label
    JSONObject jo = putRequestJSONObject(urn_labels + "/ch1/controller?id=17", createJsonController17Bis(),
            HttpServletResponse.SC_OK);//  w w  w . j a v  a 2s  .c  o  m
    testController17Bis(jo);

    // impossible to add again the same controller
    putRequestJSONObject(urn_labels + "/ch1/11", createJsonController11Bis(), HttpServletResponse.SC_OK);

    // Test impossible to create a new controller not existing in a Group
    putRequestJSONObject(urn_labels + "/ch1/6", createJsonController6(), HttpServletResponse.SC_NOT_ACCEPTABLE);
    putRequestJSONObject(urn_labels + "/ch1/controller?id=6", createJsonController6(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }/*from w w w.  j  a v  a2s . co  m*/

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}