Example usage for javax.servlet.http HttpServletRequest getContentLength

List of usage examples for javax.servlet.http HttpServletRequest getContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentLength.

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * PROPFIND Method.// ww w .j a  va 2  s . c o m
 */
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    AtmosApi api = getAPIFromAuthent(req, resp);

    // Properties which are to be displayed.
    List<String> properties = null;
    // Propfind depth
    int depth = 1;
    // Propfind type
    int type = FIND_ALL_PROP;

    String href = getPathFromReq(req);

    if ("0".equals(req.getHeader("Depth"))) {
        depth = 0; // only accepted values are 0 and 1
    }

    Element propNode = null;
    if (req.getContentLength() > 0) {
        Builder parser = new Builder();

        try {
            Document doc = parser.build(req.getInputStream());

            // Get the root element of the document
            Element root = doc.getRootElement();
            Elements childList = root.getChildElements();

            for (int i = 0; i < childList.size(); i++) {
                Element currentNode = childList.get(i);
                if (currentNode.getLocalName().equals("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentNode;
                }
                if (currentNode.getLocalName().equals("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentNode.getLocalName().equals("allprop")) {
                    type = FIND_ALL_PROP;
                }
            }
        } catch (Exception e) {
            // Something went wrong - bad request
            resp.sendError(resp.SC_BAD_REQUEST);
            return;
        }
    }

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector<String>();
        Elements childList = propNode.getChildElements();
        for (int i = 0; i < childList.size(); i++) {
            properties.add(childList.get(i).getLocalName());
        }

    }

    try {
        //EsuRestApi api = new EsuRestApi(ATMOS_ENDPOINT_HOST, ATMOS_ENDPOINT_PORT, "69a36dbcbe9c4b0cad8ac8d696deed71/Int001", "Vv67+N+2u7SAZsboJwX8+yd2GXc=");
        MetadataList metadata = getObjectMetadata(api.api, getAtmosPath(href, api));
        AtmosType obj_type = getObjectType(metadata);

        if (obj_type == AtmosType.NON_EXISTENT) {
            // check if we need to initialize the directory container for webdav
            if ("/".equals(href)) {
                api.api.createObjectOnPath(getAtmosPath(href, api), null, null, null, null);
                obj_type = AtmosType.DIRECTORY;
            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, href);
                return;
            }
        }

        if ((obj_type == AtmosType.DIRECTORY) && (!href.endsWith("/")))
            href += "/";

        resp.setStatus(SC_MULTI_STATUS);
        resp.setContentType("text/xml; charset=UTF-8");

        // Create multistatus object
        Element root = new Element("multistatus", DAV_NAMESPACE);
        Document xml = new Document(root);

        parseProperties(req, metadata, root, getAtmosPath(href, api).toString(), type, api, properties);
        if ((depth > 0) && (obj_type == AtmosType.DIRECTORY)) {
            List<DirectoryEntry> dir_entries = api.api.listDirectory(getAtmosPath(href, api));
            for (DirectoryEntry dir_entry : dir_entries) {
                try {
                    MetadataList entry_metadata = getObjectMetadata(api.api, dir_entry.getPath());
                    //                        String local_name = entry_metadata.getMetadata("objname").getValue();
                    parseProperties(req, entry_metadata, root, dir_entry.getPath().toString(), type, api,
                            properties);
                } catch (EsuException e) {
                    if ((e.getAtmosCode() != 403) && (e.getAtmosCode() != 1003))
                        throw e;
                }
            }
        }

        String sxml = xml.toXML();
        resp.getWriter().write(sxml);

    } catch (EsuException e) {
        resp.sendError(e.getHttpCode(), e.getMessage());
    } catch (Exception e) {
        resp.sendError(resp.SC_INTERNAL_SERVER_ERROR, "Exception: " + e.getMessage());
    }

}

From source file:org.openmrs.module.sync.web.controller.ImportListController.java

@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {

    log.info("***********************************************************\n");
    log.info("Inside SynchronizationImportListController");

    // just fail fast if in the midst of refreshing the context, as this was causing issues, see SYNC-318
    if (Context.isRefreshingContext()) {
        return null;
    }/*ww  w. j a v  a 2s.  com*/

    // There are 3 ways to come to this point, so we'll handle all of them:
    // 1) uploading a file (results in a file attachment as response)
    // 2) posting data to page (results in pure XML output)
    // 3) remote connection (with username + password, also posting data) (results in pure XML)
    // none of these result in user-friendly - so no comfy, user-friendly stuff needed here

    //outputing statistics: debug only!
    log.info("HttpServletRequest INFO:");
    log.info("ContentType: " + request.getContentType());
    log.info("CharacterEncoding: " + request.getCharacterEncoding());
    log.info("ContentLength: " + request.getContentLength());
    log.info("checksum: " + request.getParameter("checksum"));
    log.info("syncData: " + request.getParameter("syncData"));
    log.info("syncDataResponse: " + request.getParameter("syncDataResponse"));

    long checksum = 0;
    Integer serverId = 0;
    boolean isResponse = false;
    boolean isUpload = false;
    boolean useCompression = false;

    String contents = "";
    String username = "";
    String password = "";

    //file-based upload, and multi-part form submission
    if (request instanceof MultipartHttpServletRequest) {
        log.info("Processing contents of syncDataFile multipart request parameter");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        serverId = ServletRequestUtils.getIntParameter(multipartRequest, "serverId", 0);
        isResponse = ServletRequestUtils.getBooleanParameter(multipartRequest, "isResponse", false);
        useCompression = ServletRequestUtils.getBooleanParameter(multipartRequest, "compressed", false);
        isUpload = ServletRequestUtils.getBooleanParameter(multipartRequest, "upload", false);
        username = ServletRequestUtils.getStringParameter(multipartRequest, "username", "");
        password = ServletRequestUtils.getStringParameter(multipartRequest, "password", "");

        log.info("Request class: " + request.getClass());
        log.info("serverId: " + serverId);
        log.info("upload = " + isUpload);
        log.info("compressed = " + useCompression);
        log.info("response = " + isResponse);
        log.info("username = " + username);

        log.info("Request content length: " + request.getContentLength());
        MultipartFile multipartFile = multipartRequest.getFile("syncDataFile");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            InputStream inputStream = null;
            try {
                // Decompress content in file
                ConnectionResponse syncResponse = new ConnectionResponse(
                        new ByteArrayInputStream(multipartFile.getBytes()), useCompression);

                log.info("Content to decompress: " + multipartFile.getBytes());
                log.info("Content received: " + syncResponse.getResponsePayload());
                log.info("Decompression Checksum: " + syncResponse.getChecksum());

                contents = syncResponse.getResponsePayload();
                checksum = syncResponse.getChecksum();

                log.info("Final content: " + contents);

            } catch (Exception e) {
                log.warn("Unable to read in sync data file", e);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    } else {
        log.debug("seems we DO NOT have a file object");
    }

    // prepare to process the input: contents now contains decompressed request ready to be processed
    SyncTransmissionResponse str = new SyncTransmissionResponse();
    str.setErrorMessage(SyncConstants.ERROR_TX_NOT_UNDERSTOOD);
    str.setFileName(SyncConstants.FILENAME_TX_NOT_UNDERSTOOD);
    str.setUuid(SyncConstants.UUID_UNKNOWN);
    str.setSyncSourceUuid(SyncConstants.UUID_UNKNOWN);
    str.setSyncTargetUuid(SyncConstants.UUID_UNKNOWN);
    str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
    str.setTimestamp(new Date()); //set the timestamp of the response

    if (log.isInfoEnabled()) {
        log.info("CONTENT IN IMPORT CONTROLLER: " + contents);
    }

    //if no content, nothing to process just send back response
    if (contents == null || contents.length() < 0) {
        log.info("returning from ingest: nothing to process.");
        this.sendResponse(str, isUpload, response);
        return null;
    }

    // if this is option 3 (posting from remote server), we need to authenticate
    if (!Context.isAuthenticated()) {
        try {
            Context.authenticate(username, password);
        } catch (Exception e) {
        }
    }
    // Could not authenticate user: send back error
    if (!Context.isAuthenticated()) {
        str.setErrorMessage(SyncConstants.ERROR_AUTH_FAILED);
        str.setFileName(SyncConstants.FILENAME_AUTH_FAILED);
        str.setState(SyncTransmissionState.AUTH_FAILED);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    //Fill-in the server uuid for the response: since request was authenticated we can start letting callers
    //know about us
    str.setSyncTargetUuid(Context.getService(SyncService.class).getServerUuid());

    //Checksum check before doing anything at all: on unreliable networks we can get seemingly
    //valid HTTP POST but content is messed up, defend against it with custom checksums
    long checksumReceived = ServletRequestUtils.getLongParameter(request, "checksum", -1);
    log.info("checksum value received in POST: " + checksumReceived);
    log.info("checksum value of payload: " + checksum);
    log.info("SIZE of payload: " + contents.length());
    if (checksumReceived > 0 && (checksumReceived != checksum)) {
        log.error("ERROR: FAILED CHECKSUM!");
        str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    //Test message. Test message was sent (i.e. using 'test connection' button on server screen)
    //just send empty acknowledgment
    if (SyncConstants.TEST_MESSAGE.equals(contents)) {
        str.setErrorMessage("");
        str.setState(SyncTransmissionState.OK);
        str.setUuid("");
        str.setFileName(SyncConstants.FILENAME_TEST);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    if (SyncConstants.CLONE_MESSAGE.equals(contents)) {
        try {
            log.info("CLONE MESSAGE RECEIVED, TRYING TO CLONE THE DB");
            File file = Context.getService(SyncService.class).generateDataFile();
            StringWriter writer = new StringWriter();
            IOUtils.copy(new FileInputStream(file), writer);
            this.sendCloneResponse(writer.toString(), response, false);

            boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService()
                    .getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true"));

            if (!clonedDBLog) {
                file.delete();
            }
        } catch (Exception ex) {
            log.warn(ex.toString());
            ex.printStackTrace();
        }
        return null;
    }

    /*************************************************************************************************************************
     * This is a real transmission: - user was properly authenticated - checksums match - it is
     * not a test transmission Start processing! 1. Deserialize what was sent; it can be either
     * SyncTransmssion, or SyncTransmissionResponse 2. If it is a response,
     *************************************************************************************************************************/
    SyncTransmission st = null;

    if (!isResponse) {
        //this is not 'response' to something we sent out; thus the contents should contain plan SyncTransmission 
        try {
            log.info("xml to sync transmission with contents: " + contents);
            st = SyncDeserializer.xmlToSyncTransmission(contents);
        } catch (Exception e) {
            log.error("Unable to deserialize the following: " + contents, e);
            str.setErrorMessage("Unable to deserialize transmission contents into SyncTansmission.");
            str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
            this.sendResponse(str, isUpload, response);
            return null;
        }
    } else {
        log.info("Processing a response, not a transmission");
        SyncTransmissionResponse priorResponse = null;

        try {
            // this is the confirmation of receipt of previous transmission
            priorResponse = SyncDeserializer.xmlToSyncTransmissionResponse(contents);
            log.info("This is a response from a previous transmission.  Uuid is: " + priorResponse.getUuid());
        } catch (Exception e) {
            log.error("Unable to deserialize the following: " + contents, e);
            str.setErrorMessage("Unable to deserialize transmission contents into SyncTransmissionResponse.");
            str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
            this.sendResponse(str, isUpload, response);
            return null;
        }

        // figure out where this came from:
        // for responses, the target ID contains the server that generated the response
        String sourceUuid = priorResponse.getSyncTargetUuid();
        log.info("SyncTransmissionResponse has a sourceUuid of " + sourceUuid);
        RemoteServer origin = Context.getService(SyncService.class).getRemoteServer(sourceUuid);
        if (origin == null) {
            log.error("Source server not registered locally. Unable to find source server by uuid: "
                    + sourceUuid);
            str.setErrorMessage(
                    "Source server not registered locally. Unable to find source server by uuid " + sourceUuid);
            str.setState(SyncTransmissionState.INVALID_SERVER);
            this.sendResponse(str, isUpload, response);
            return null;
        } else {
            log.info("Found source server by uuid: " + sourceUuid + " = " + origin.getNickname());
            log.info("Source server is " + origin.getNickname());
        }

        if (priorResponse == null) {
        }

        // process response that was sent to us; the sync response normally contains:
        //a) results of the records that we sent out
        //b) new records from 'source' to be applied against this server
        if (priorResponse.getSyncImportRecords() == null) {
            log.debug("No records to process in response");
        } else {
            // now process each incoming syncImportRecord, this is just status update
            for (SyncImportRecord importRecord : priorResponse.getSyncImportRecords()) {
                Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord, origin);
            }
        }

        // now pull out the data that originated on the 'source' server and try to process it
        st = priorResponse.getSyncTransmission();

    }

    // now process the syncTransmission if one was received                    
    if (st != null) {
        str = SyncUtilTransmission.processSyncTransmission(st,
                SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_WEB));
    } else
        log.info("st was null");

    //send response
    this.sendResponse(str, isUpload, response);

    // never a situation where we want to actually use the model/view - either file download or http request
    return null;
}

From source file:org.polymap.rap.updownload.upload.UploadService.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//from   w  ww .j  a va  2s .  c o m
        FileItemIterator it = fileUpload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();

            try (InputStream in = item.openStream()) {
                if (item.isFormField()) {
                    log.info("Form field " + item.getFieldName() + " with value " + Streams.asString(in)
                            + " detected.");
                } else {
                    log.info("File field " + item.getFieldName() + " with file name " + item.getName()
                            + " detected.");

                    String handlerId = request.getParameter(ID_REQUEST_PARAM);
                    assert handlerId != null;
                    IUploadHandler handler = handlers.get(handlerId);
                    ClientFile clientFile = new ClientFile() {
                        @Override
                        public String getName() {
                            return item.getName();
                        }

                        @Override
                        public String getType() {
                            return item.getContentType();
                        }

                        @Override
                        public long getSize() {
                            // for the upload field we always get just one item (which has the length of the request!?)
                            return request.getContentLength();
                        }
                    };
                    handler.uploadStarted(clientFile, in);
                }
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java

public void finalizeRequest(HttpServletRequest request, HttpServletResponse response) {

    logger.debug("In...:finalizeRequest");
    String servicename = UtilLib.getServiceName(request);

    PerformanceTrackingBean perfTrackerBean = (PerformanceTrackingBean) request
            .getAttribute(PERFORMANCE_TRACKER_BEAN);
    long startTime = (long) request.getAttribute(CommonNames.START_TIME);
    AuditRecord ar = new AuditRecord();
    try {/*ww  w  .jav  a2  s  .c  o  m*/
        logger.debug("Starting application specific handling...:finalizeRequest");
        // request.setAttribute(CommonNames.AUDIT_RECORD, ar);
        // request.setAttribute(CommonNames.ATTR_START_TIME,
        // Long.valueOf(startTime).toString());
        perfTrackerBean.setAuditRecord(ar);
        servicename = LoggerNameConverter.convertNormalizedName(request, servicename);

        perfTrackerBean.setServiceName(servicename);

        perfTrackerBean.setRequestContentLen(request.getContentLength());
        perfTrackerBean.setResponseMsgSize(getResponseLength(request));
        perfTrackerBean.setMethod(request.getMethod());

        ar.setInstanceName(SystemParams.instance().getInstanceName());
        ar.setInitiatedTimestamp(UtilLib.epochToXmlGC(startTime));
        ar.setVtier(SystemParams.instance().getVtier());
        ar.setCluster(SystemParams.instance().getCluster());
        ar.setHostName(SystemParams.instance().getHostName());
        ar.setHostIPAddress(SystemParams.instance().getIpAddress());
        ar.setSubject("CW.pub.spm2." + servicename + ".response");
        ar.setMode("");
        ar.setServiceKeyData1("");
        ar.setServiceKeyData2("");
        ar.setSourceClass(CommonNames.SOURCE_CLASS);
        ar.setSourceMethod(CommonNames.AUDIT_LOGGER_NAME);
        ar.setTransactionName(servicename);
        /*
         * ar.setApplicationId(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setConversationId(request.getAttribute(CommonNames.
         * CSI_CONVERSATION_ID));
         * ar.setUniqueTransactionId(request.getAttribute(CommonNames.
         * CSI_UNIQUE_TXN_ID));
         * ar.setOriginalMessageId(request.getAttribute(CommonNames.
         * CSI_MESSAGE_ID));
         * ar.setOriginatorId(request.getAttribute(CommonNames.
         * CSI_ORIGINATOR_ID));
         * ar.setClientApp(UtilLib.ifNullThenEmpty(request.getAttribute(
         * CommonNames.CSI_CLIENT_APP))); ar.setOriginationSystemId("N/A");
         * ar.setOriginationSystemName(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setOriginationSystemVersion(request.getAttribute(CommonNames.
         * CSI_VERSION));
         */

        ar.setApplicationId(perfTrackerBean.getUserName());
        ar.setConversationId(perfTrackerBean.getConversationId());
        ar.setUniqueTransactionId(perfTrackerBean.getUniqueTransactionId());
        ar.setOriginalMessageId(perfTrackerBean.getOriginalMessageId());
        ar.setOriginatorId(perfTrackerBean.getOriginatorId());
        ar.setClientApp(UtilLib.ifNullThenEmpty(perfTrackerBean.getClientApp()));
        ar.setOriginationSystemId("N/A");
        ar.setOriginationSystemName(perfTrackerBean.getUserName());
        ar.setOriginationSystemVersion(perfTrackerBean.getOriginationSystemVersion());

        // new fields added per new schema
        ar.setClientIP(request.getRemoteAddr());
        ar.setHttpMethod(perfTrackerBean.getMethod());
        ar.setRequestURL(request.getPathInfo());

        // PerformanceTracking.initPerfTrack(request,servicename);
        PerformanceTracking.initPerfTrack(perfTrackerBean, servicename);
        // PerformanceTracking.addPerfTrack(request, "Main", "I",
        // startTime.toString(), servicename);

        int httpCode = response.getStatus();

        if (httpCode == HttpServletResponse.SC_UNAUTHORIZED) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_401_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_FORBIDDEN) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_403_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_NOT_IMPLEMENTED) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_501_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_503_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (400 <= httpCode && httpCode <= 499) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_4NN_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == 500) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_500_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

        else {
            ar.setResponseDescription(CommonNames.CSI_SUCCESS);
            ar.setResponseCode(CommonNames.CSI_SUCCESS_RESPONSE_CODE);
            ar.setTransactionStatus("C");
        }

        // Enhance CSI logging to use the CAET error code

        if (response.getHeader(CommonNames.CAET_RestErrorCode) != null
                || response.getHeader(CommonNames.CAET_CingularErrorCode) != null) {

            // if(request.getHeader("X-CAET-CingularErrorCode") != null){
            if ("Y".equals(request.getAttribute(CommonNames.AJSC_CAET_IS_REST_SERVICE))) {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCategory));
                ar.setResponseDescription(response.getHeader(CommonNames.CAET_RestErrorDescription));

            } else

            {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCode));

                ar.setResponseDescription(response.getHeader(CommonNames.CAET_CingularErrorDescription));

            }

            ar.setFaultCode(response.getHeader(CommonNames.CAET_FaultCode));

            ar.setFaultDescription(response.getHeader(CommonNames.CAET_FaultDesc));

            ar.setFaultLevel(CommonNames.ERROR);

            ar.setFaultEntity(response.getHeader(CommonNames.CAET_FaultEntity));

            ar.setTransactionStatus("E");

            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));

            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));

            ar.setExternalFaultCode(String.valueOf(httpCode));

            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

    }

    catch (Exception e) {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        ar.setResponseCode(CommonNames.CSI_GENERIC_UNKNOWN_ERROR);
        ar.setResponseDescription(CommonErrors.DEF_5NN_FAULT_DESC);
        ar.setFaultEntity("CSI");
        ar.setFaultCode(CommonErrors.DEF_5NN_FAULT_CODE);
        ar.setFaultDescription(e.getMessage());
        ar.setFaultLevel("ERROR");
        ar.setFaultSequenceNumber("1");
        ar.setTransactionStatus("E");
        ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
        // ar.setFaultTimestamp(UtilLib.epochToXmlGC(((Long)System.nanoTime()/1000000).longValue()));
        logger.error("EXCEPTION - " + e.getMessage());
    }

    finally {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        if (ar != null) {

            if (perfTrackerBean != null && !perfTrackerBean.isAsync()) {
                perfTrackerBean.setAuditRecord(ar);
                logger.debug("Before calling completeLogging");
                completeLogging(request, servicename);
            }

        } else {
            logger.debug("Audit Record is null,abort logging");
        }
    }

}

From source file:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///  w  w  w.  java2s.  c o  m
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:com.fluidops.iwb.server.SparqlServlet.java

/**
 * Handles the forward to the {@link HybridSearchServlet} by performing a redirect or a forward.
 * A redirect is performed if the content length of the request is smaller than Jetty's buffer
 * limit, otherwise the request is directly forwarded.
 * /*  ww w .  j a  v a 2 s . c o  m*/
 * All parameters are passed to the {@link HybridSearchServlet} as part of the request. Note
 * that the "repository" parameter is in addition mapped to "queryTarget".
 * 
 * Note that certain request parameters as defined in {@link #requestParamIgnoreKeys} are
 * not forwarded.
 * 
 * @param req
 * @param resp
 * @throws IOException
 */
protected void handleForward(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // determine the query target (used for repository manager)
    String repositoryID = req.getParameter("repository");
    String queryTarget;
    if (StringUtil.isNotNullNorEmpty(repositoryID))
        queryTarget = StringUtil.urlEncode(repositoryID);
    else
        queryTarget = "RDF";

    // Apparently, the jetty limit on request header buffer size is 6144, which is filled by (contentLength*2 + something else).
    // Content length 2965 was sufficient for the query to pass.
    // Moved the threshold down in case if additional properties are to be passed (e.g., multiple query targets).
    if (req.getContentLength() < 2800) {

        StringBuilder forwardedParams = new StringBuilder();
        /*
         * Sanitize the request parameters before redirect to
         * prevent HTTP response splitting vulnerabilities
         * 
         * @see http://de.wikipedia.org/wiki/HTTP_Response_Splitting
         */
        for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
            if (requestParamIgnoreKeys.contains(entry.getKey()))
                continue;
            for (String value : entry.getValue()) {
                forwardedParams.append(String.format("&%s=%s", entry.getKey(), StringUtil.urlEncode(value)));
            }
        }
        String location = req.getContextPath() + "/search/?queryLanguage=SPARQL&queryTarget=" + queryTarget
                + forwardedParams.toString();

        resp.sendRedirect(location);
    } else {

        RequestDispatcher dispatcher = req
                .getRequestDispatcher("/search/?queryLanguage=SPARQL&queryTarget=" + queryTarget);
        try {
            dispatcher.forward(req, resp);
        } catch (ServletException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not forward request to search servlet.");
        }
    }
}

From source file:helma.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws IOException {
    // check if there are any parameters before we get started
    String queryString = request.getQueryString();
    String contentType = request.getContentType();
    boolean isFormPost = "post".equals(request.getMethod().toLowerCase()) && contentType != null
            && contentType.toLowerCase().startsWith("application/x-www-form-urlencoded");

    if (queryString == null && !isFormPost) {
        return;// w w w . jav a 2  s.  c  om
    }

    HashMap parameters = new HashMap();

    // Parse any query string parameters from the request
    if (queryString != null) {
        parseParameters(parameters, queryString.getBytes(), encoding, false);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, false);
            parameters.clear();
        }
    }

    // Parse any posted parameters in the input stream
    if (isFormPost) {
        int max = request.getContentLength();
        if (max > totalUploadLimit * 1024) {
            throw new IOException("Exceeded Upload limit");
        }
        int len = 0;
        byte[] buf = new byte[max];
        ServletInputStream is = request.getInputStream();

        while (len < max) {
            int next = is.read(buf, len, max - len);

            if (next < 0) {
                break;
            }

            len += next;
        }

        // is.close();
        parseParameters(parameters, buf, encoding, true);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, true);
            parameters.clear();
        }
    }
}