Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:net.ymate.module.webproxy.WebProxy.java

@SuppressWarnings("unchecked")
public void transmission(HttpServletRequest request, HttpServletResponse response, String url,
        Type.HttpMethod method) throws Exception {
    StopWatch _consumeTime = null;/*w w  w.  j a v a 2 s  .  c o m*/
    long _threadId = 0;
    if (_LOG.isDebugEnabled()) {
        _consumeTime = new StopWatch();
        _consumeTime.start();
        _threadId = Thread.currentThread().getId();
        _LOG.debug("-------------------------------------------------");
        _LOG.debug("--> [" + _threadId + "] URL: " + url);
    }
    //
    HttpURLConnection _conn = null;
    try {
        if (__moduleCfg.isUseProxy()) {
            _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy());
        } else {
            _conn = (HttpURLConnection) new URL(url).openConnection();
        }
        _conn.setUseCaches(__moduleCfg.isUseCaches());
        _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects());
        //
        boolean _postFlag = Type.HttpMethod.POST.equals(method);
        boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/");
        if (_postFlag) {
            _conn.setDoOutput(true);
            _conn.setDoInput(true);
            _conn.setRequestMethod(method.name());
        }
        if (__moduleCfg.getConnectTimeout() > 0) {
            _conn.setConnectTimeout(__moduleCfg.getConnectTimeout());
        }
        if (__moduleCfg.getReadTimeout() > 0) {
            _conn.setReadTimeout(__moduleCfg.getReadTimeout());
        }
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Method: " + method.name());
            _LOG.debug("--> [" + _threadId + "] Request Headers: ");
        }
        //
        Enumeration _header = request.getHeaderNames();
        while (_header.hasMoreElements()) {
            String _name = (String) _header.nextElement();
            String _value = request.getHeader(_name);
            boolean _flag = false;
            if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type")
                    || __moduleCfg.isTransferHeaderEnabled()
                            && (!__moduleCfg.getTransferHeaderBlackList().isEmpty()
                                    && !__moduleCfg.getTransferHeaderBlackList().contains(_name)
                                    || !__moduleCfg.getTransferHeaderWhiteList().isEmpty()
                                            && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) {
                _conn.setRequestProperty(_name, _value);
                _flag = true;
            }
            //
            if (_LOG.isDebugEnabled()) {
                _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value);
            }
        }
        _conn.connect();
        //
        if (_postFlag) {
            DataOutputStream _output = new DataOutputStream(_conn.getOutputStream());
            try {
                if (_multipartFlag) {
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Multipart: TRUE");
                    }
                    IOUtils.copyLarge(request.getInputStream(), _output);
                } else {
                    String _charset = request.getCharacterEncoding();
                    String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset);
                    IOUtils.write(_queryStr, _output, _charset);
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Request Parameters: ");
                        Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true,
                                _charset);
                        for (Map.Entry<String, String> _param : _paramsMap.entrySet()) {
                            _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": "
                                    + _param.getValue());
                        }
                    }
                }
                _output.flush();
            } finally {
                IOUtils.closeQuietly(_output);
            }
        }
        //
        int _code = _conn.getResponseCode();
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Response Code: " + _code);
            _LOG.debug("--> [" + _threadId + "] Response Headers: ");
        }
        //
        Map<String, List<String>> _headers = _conn.getHeaderFields();
        for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) {
            if (_entry.getKey() != null) {
                boolean _flag = false;
                String _values = StringUtils.join(_entry.getValue(), ",");
                if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type")
                        || __moduleCfg.isTransferHeaderEnabled()
                                && !__moduleCfg.getResponseHeaderWhileList().isEmpty()
                                && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) {
                    response.setHeader(_entry.getKey(), _values);
                    _flag = true;
                }
                if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": "
                            + _values);
                }
            }
        }
        if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) {
            response.sendError(_code);
        } else {
            if (HttpURLConnection.HTTP_OK == _code) {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    if (!_multipartFlag) {
                        byte[] _content = IOUtils.toByteArray(_inputStream);
                        IOUtils.write(_content, response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(
                                    _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                        }
                    } else {
                        IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody");
                        }
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.flushBuffer();
            } else {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    byte[] _content = IOUtils.toByteArray(_inputStream);
                    IOUtils.write(_content, response.getOutputStream());
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn,
                                _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.setStatus(_code);
                response.flushBuffer();
            }
        }
    } catch (Throwable e) {
        _LOG.warn("An exception occurred while processing request mapping '" + url + "': ",
                RuntimeUtils.unwrapThrow(e));
    } finally {
        IOUtils.close(_conn);
        //
        if (_LOG.isDebugEnabled()) {
            if (_consumeTime != null) {
                _consumeTime.stop();
                _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms");
            }
            _LOG.debug("-------------------------------------------------");
        }
    }
}

From source file:org.opendatakit.api.odktables.InstanceFileService.java

@POST
@Path("file/{filePath:.*}")
// @Consumes({MediaType.MEDIA_TYPE_WILDCARD})
public Response putFile(@Context HttpServletRequest req, @PathParam("filePath") List<PathSegment> segments,
        byte[] content)
        throws IOException, ODKTaskLockException, PermissionDeniedException, ODKDatastoreException {
    if (segments.size() < 1) {
        return Response.status(Status.BAD_REQUEST).entity(InstanceFileService.ERROR_MSG_INSUFFICIENT_PATH)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();//from w w w . j  a va 2  s  .co  m
    }
    // The appId and tableId are from the surrounding TableService.
    // The rowId is already pulled out.
    // The segments are just rest/of/path in the full app-centric
    // path of:
    // appid/data/attachments/tableid/instances/instanceId/rest/of/path
    String partialPath = constructPathFromSegments(segments);
    String contentType = req.getContentType();
    String md5Hash = PersistenceUtils.newMD5HashUri(content);

    InstanceFileManager fileInstanceManager = new InstanceFileManager(appId, cc);

    FileContentInfo fileContentInfo = new FileContentInfo(partialPath, contentType, (long) content.length,
            md5Hash, content);
    InstanceFileChangeDetail outcome = fileInstanceManager.putFile(tableId, rowId, fileContentInfo,
            userPermissions);

    UriBuilder uriBuilder = info.getBaseUriBuilder();
    uriBuilder.path(OdkTables.class);
    uriBuilder.path(OdkTables.class, "getTablesService");

    URI getFile = uriBuilder.clone().path(TableService.class, "getRealizedTable")
            .path(RealizedTableService.class, "getInstanceFiles").path(InstanceFileService.class, "getFile")
            .build(appId, tableId, schemaETag, rowId, partialPath);

    String locationUrl = getFile.toURL().toExternalForm();

    if (outcome == InstanceFileChangeDetail.FILE_PRESENT) {

        return Response.status(Status.CREATED).header("Location", locationUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    } else {

        return Response.status(Status.BAD_REQUEST).entity(ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    }
}

From source file:org.aludratest.cloud.impl.request.ClientRequestServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//  w  ww. j  a  v  a  2  s. c  o  m
        requestSeparator.enter();
    } catch (InterruptedException e) {
        return;
    }
    LOG.debug("doPost() enter");

    try {
        // small protection against DoS attacks
        if (req.getContentLength() > MAX_CONTENT_LENGTH) {
            LOG.debug("Detected request larger than max content length. Sending BAD_REQUEST.");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // must be /resource
        // TODO should be removed; is subject to Application container to register Servlet whereever needed
        String uri = req.getServletPath();
        if (!"/resource".equals(uri)) {
            LOG.debug("Detected request to other path than /resource. Sending NOT_FOUND.");
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        User user = BasicAuthUtil.authenticate(req, resp);
        if (user == null) {
            LOG.debug("No or invalid user information in request. Aborting.");
            return;
        }

        // request must be JSON
        String contentType = req.getContentType();
        if (contentType != null && contentType.contains(";")) {
            contentType = contentType.substring(0, contentType.indexOf(';'));
        }
        if (CONTENT_TYPE_CHECK_ENABLED && !JSON_CONTENT_TYPE.equals(contentType)) {
            LOG.debug("Invalid content type detected. Sending BAD_REQUEST.");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // encoding must be UTF-8
        if (req.getCharacterEncoding() != null && !"UTF-8".equalsIgnoreCase(req.getCharacterEncoding())) {
            LOG.debug("Invalid character encoding detected. Sending BAD_REQUEST.");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // extract JSON payload
        InputStream data = req.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(data, baos);
        data.close();

        String jsonSource = new String(baos.toByteArray(), "UTF-8");
        try {
            JSONObject requestObject = new JSONObject(jsonSource);
            waitingRequests.incrementAndGet();
            JSONObject resultObject = requestHandler.handleResourceRequest(user, requestObject);
            waitingRequests.decrementAndGet();

            // send it to response
            StringWriter writer = new StringWriter();
            resultObject.write(writer);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType(JSON_CONTENT_TYPE);
            byte[] resultData = writer.toString().getBytes("UTF-8");
            resp.setContentLength(resultData.length);

            try {
                OutputStream os = resp.getOutputStream();
                os.write(resultData);
                os.close();
            } catch (IOException e) {
                // client closed connection during wait
                if (resultObject.has("requestId")) {
                    requestHandler.abortWaitingRequest(resultObject.getString("requestId"));
                }
            }
        } catch (JSONException e) {
            LOG.debug("JSON exception occurred. Sending BAD_REQUEST.");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    } finally {
        LOG.debug("doPost() leave");
    }
}

From source file:org.dspace.app.webui.servlet.SubmissionController.java

protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // Configuration of current step in Item Submission Process
    SubmissionStepConfig currentStepConfig;

    //need to find out what type of form we are dealing with
    String contentType = request.getContentType();

    // if multipart form, we have to wrap the multipart request
    // in order to be able to retrieve request parameters, etc.
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        try {//from w w w  .  j a  va2 s.  co m
            request = wrapMultipartRequest(request);
        } catch (FileSizeLimitExceededException e) {
            log.warn("Upload exceeded upload.max");
            JSPManager.showFileSizeLimitExceededError(request, response, e.getMessage(), e.getActualSize(),
                    e.getPermittedSize());
        }

        //also, upload any files and save their contents to Request (for later processing by UploadStep)
        uploadFiles(context, request);
    }

    // Reload submission info from request parameters
    SubmissionInfo subInfo = getSubmissionInfo(context, request);

    // a submission info object is necessary to continue
    if (subInfo == null) {
        // Work around for problem where people select "is a thesis", see
        // the error page, and then use their "back" button thinking they
        // can start another submission - it's been removed so the ID in the
        // form is invalid. If we detect the "removed_thesis" attribute we
        // display a friendly message instead of an integrity error.
        if (request.getSession().getAttribute("removed_thesis") != null) {
            request.getSession().removeAttribute("removed_thesis");
            JSPManager.showJSP(request, response, "/submit/thesis-removed-workaround.jsp");

            return;
        } else {
            // If the submission info was invalid, throw an integrity error
            log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request)));
            JSPManager.showIntegrityError(request, response);
            return;
        }
    }

    // First, check for a click on "Cancel/Save" button.
    if (UIUtil.getSubmitButton(request, "").equals(AbstractProcessingStep.CANCEL_BUTTON)) {
        // Get the current step
        currentStepConfig = getCurrentStepConfig(request, subInfo);

        // forward user to JSP which will confirm 
        // the cancel/save request.
        doCancelOrSave(context, request, response, subInfo, currentStepConfig);
    }
    // Special case - no InProgressSubmission yet
    // If no submission, we assume we will be going
    // to the "select collection" step.
    else if (subInfo.getSubmissionItem() == null) {
        // we have just started this submission
        // (or we have just resumed a saved submission)

        // do the "Select Collection" step
        doStep(context, request, response, subInfo, SELECT_COLLECTION);
    } else
    // otherwise, figure out the next Step to call!
    {
        // Get the current step
        currentStepConfig = getCurrentStepConfig(request, subInfo);

        //if user already confirmed the cancel/save request
        if (UIUtil.getBoolParameter(request, "cancellation")) {
            // user came from the cancel/save page, 
            // so we need to process that page before proceeding
            processCancelOrSave(context, request, response, subInfo, currentStepConfig);
        }
        //check for click on "<- Previous" button
        else if (UIUtil.getSubmitButton(request, "").startsWith(AbstractProcessingStep.PREVIOUS_BUTTON)) {
            // return to the previous step
            doPreviousStep(context, request, response, subInfo, currentStepConfig);
        }
        //check for click on Progress Bar
        else if (UIUtil.getSubmitButton(request, "").startsWith(AbstractProcessingStep.PROGRESS_BAR_PREFIX)) {
            // jumping to a particular step/page
            doStepJump(context, request, response, subInfo, currentStepConfig);
        } else {
            // by default, load step class to start 
            // or continue its processing
            doStep(context, request, response, subInfo, currentStepConfig.getStepNumber());
        }
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.inbound.HttpIdentityRequestFactory.java

public void create(IdentityRequest.IdentityRequestBuilder builder, HttpServletRequest request,
        HttpServletResponse response) throws FrameworkClientException {

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        builder.addHeader(headerName, request.getHeader(headerName));
    }/*  www.j ava  2s.c  o  m*/

    // We need to create a new map with the parameters sent in servlet request to avoid having a reference.
    Map<String, String[]> paramMap = new HashMap<>(request.getParameterMap());
    builder.setParameters(paramMap);

    Enumeration<String> attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = attrNames.nextElement();
        builder.addAttribute(attrName, request.getAttribute(attrName));
    }
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            builder.addCookie(cookie.getName(), cookie);
        }
    }

    String requestURI = request.getRequestURI();

    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (StringUtils.isNotBlank(tenantDomain)) {
        builder.setTenantDomain(tenantDomain);
    } else {
        builder.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    builder.setContentType(request.getContentType());
    builder.setContextPath(request.getContextPath());
    builder.setMethod(request.getMethod());
    builder.setPathInfo(request.getPathInfo());
    builder.setPathTranslated(request.getPathTranslated());
    builder.setQueryString(request.getQueryString());
    builder.setRequestURI(requestURI);
    builder.setRequestURL(request.getRequestURL());
    builder.setServletPath(request.getServletPath());

}

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;
    }//w  ww.j av a2 s .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.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or
 * JSON according to the XACML 3.0 Specifications for both.
 *
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w  w  w .ja va2s .c  o m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // no point in doing any work if we know from the get-go that we cannot do anything with the request
    //
    if (status.getLoadedRootPolicies().size() == 0) {
        logger.warn("Request from PEP at " + request.getRequestURI()
                + " for service when PDP has No Root Policies loaded");
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    XACMLRest.dumpRequest(request);
    //
    // Set our no-cache header
    //
    response.setHeader("Cache-Control", "no-cache");
    //
    // They must send a Content-Type
    //
    if (request.getContentType() == null) {
        logger.warn("Must specify a Content-Type");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
        return;
    }
    //
    // Limit the Content-Length to something reasonable
    //
    if (request.getContentLength() > Integer
            .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
        String message = "Content-Length larger than server will accept.";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    if (request.getContentLength() <= 0) {
        String message = "Content-Length is negative";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    ContentType contentType = null;
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (Exception e) {
        String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // What exactly did they send us?
    //
    String incomingRequestString = null;
    Request pdpRequest = null;
    if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
        //
        // Read in the string
        //
        StringBuilder buffer = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            incomingRequestString = buffer.toString();
        }
        logger.info(incomingRequestString);
        //
        // Parse into a request
        //
        try {
            if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                pdpRequest = JSONRequest.load(incomingRequestString);
            } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                    || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
                pdpRequest = DOMRequest.load(incomingRequestString);
            }
        } catch (Exception e) {
            logger.error("Could not parse request", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }
    } else {
        String message = "unsupported content type" + request.getContentType();
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Did we successfully get and parse a request?
    //
    if (pdpRequest == null || pdpRequest.getRequestAttributes() == null
            || pdpRequest.getRequestAttributes().size() <= 0) {
        String message = "Zero Attributes found in the request";
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Run it
    //
    try {
        //
        // Get the pointer to the PDP Engine
        //
        PDPEngine myEngine = null;
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
        }
        if (myEngine == null) {
            String message = "No engine loaded.";
            logger.error(message);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
            return;
        }
        //
        // Send the request and save the response
        //
        long lTimeStart, lTimeEnd;
        Response pdpResponse = null;

        // TODO - Make this unnecessary
        // TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in
        // the middle of processing
        // TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide()
        // method).
        // TODO Using synchronize will slow down processing of PEP requests, possibly by a significant
        // amount.
        // TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate
        // this sychronized block.
        // TODO
        // TODO This problem was found by starting one PDP then
        // TODO RestLoadTest switching between 2 configurations, 1 second apart
        // TODO both configurations contain the datarouter policy
        // TODO both configurations already have all policies cached in the PDPs config directory
        // TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval
        // TODO With that configuration this code (without the synchronized) throws a NullPointerException
        // TODO within a few seconds.
        //
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
            try {
                lTimeStart = System.currentTimeMillis();
                pdpResponse = myEngine.decide(pdpRequest);
                lTimeEnd = System.currentTimeMillis();
            } catch (PDPException e) {
                String message = "Exception during decide: " + e.getMessage();
                logger.error(message);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                return;
            }
        }
        requestLogger.info(lTimeStart + "=" + incomingRequestString);
        if (logger.isDebugEnabled()) {
            logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
        }
        //
        // Convert Response to appropriate Content-Type
        //
        if (pdpResponse == null) {
            requestLogger.info(lTimeStart + "=" + "{}");
            throw new Exception("Failed to get response from PDP engine.");
        }
        //
        // Set our content-type
        //
        response.setContentType(contentType.getMimeType());
        //
        // Convert the PDP response object to a String to
        // return to our caller as well as dump to our loggers.
        //
        String outgoingResponseString = "";
        if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = JSONResponse.toString(pdpResponse, false);
            }
        } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = DOMResponse.toString(pdpResponse, false);
            }
        }
        //
        // lTimeStart is used as an ID within the requestLogger to match up
        // request's with responses.
        //
        requestLogger.info(lTimeStart + "=" + outgoingResponseString);
        response.getWriter().print(outgoingResponseString);
    } catch (Exception e) {
        String message = "Exception executing request: " + e;
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return;
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.krawler.esp.servlets.importICSServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;charset=UTF-8");
    Connection conn = null;/*from   ww w . j a  va  2 s. c om*/
    FileInputStream fstream = null;
    String result = KWLErrorMsgs.rsSuccessFalse;
    String contentType = request.getContentType();
    String projid = request.getParameter("projid");
    String Ccname = "";
    String Cdesc = "";
    String Ccid = "";

    String Eeid = "";
    String Estartts = "";
    String Eendts = "";
    String Esubject = "";
    String Edescr = "";
    String Elocation = "";

    try {
        int auditMode = 0;

        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            String loginid = AuthHandler.getUserid(request);
            String companyid = AuthHandler.getCompanyid(request);
            String ipAddress = AuthHandler.getIPAddress(request);
            conn = DbPool.getConnection();
            if (request.getParameter("mode").compareToIgnoreCase("new") == 0) {
                Ccname = request.getParameter("calName");
                File f1 = getfile(request);
                fstream = new FileInputStream(f1);
                Calendar cal = null;

                setSystemProperties();
                CalendarBuilder bldr = new CalendarBuilder(new CalendarParserImpl());
                cal = bldr.build(fstream);

                Ccid = Tree.insertNewCalendar(conn, Ccname, Cdesc, "", "", "0", 2, 0, projid);

                for (Iterator i = cal.getComponents().iterator(); i.hasNext();) {
                    Component component = (Component) i.next();
                    Eeid = "";
                    Esubject = "";
                    Estartts = "";
                    Eendts = "";
                    Elocation = "";
                    Edescr = "";
                    for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
                        Property property = (Property) j.next();
                        if (property.getName().equals("SUMMARY"))
                            Esubject = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DTSTART"))
                            Estartts = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DTEND"))
                            Eendts = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("LOCATION"))
                            Elocation = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DESCRIPTION"))
                            Edescr = StringUtil.serverHTMLStripper(property.getValue());
                    }
                    //Property Without End Date
                    if (!StringUtil.isNullOrEmpty(Esubject) && !StringUtil.isNullOrEmpty(Estartts)
                            && StringUtil.isNullOrEmpty(Eendts)) {
                        //Only date given no time
                        if (Estartts.length() < 9)
                            Estartts = iCaltoKWLDayDate(Estartts);
                        //Date and time specified with "TimeZone", hence no "Z" at the end.
                        else if (!Estartts.endsWith("Z")) {
                            Estartts = Estartts.concat("Z");
                            Estartts = iCaltoStartDate(Estartts);
                        } //Date and time in iCalendar format.
                        else
                            Estartts = iCaltoStartDate(Estartts);
                        Eendts = getNextDay(Estartts);//Setting end time as next day

                        if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts))
                            Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject, Edescr,
                                    Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                    } //Property With End Date
                    else if (!StringUtil.isNullOrEmpty(Esubject) || !StringUtil.isNullOrEmpty(Estartts)
                            || !StringUtil.isNullOrEmpty(Eendts)) {
                        //Only date given no time
                        if (Estartts.length() < 9 && Eendts.length() < 9) {
                            Estartts = iCaltoKWLDayDate(Estartts);
                            Eendts = iCaltoKWLEndDayDate(Eendts);
                            Eendts = getTimeHourDiff(Estartts, Eendts);
                            if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                        Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                            }
                        } //Date and time specified with "TimeZone", hence no "Z" at the end.
                        else {
                            if (!Estartts.endsWith("Z") && !Eendts.endsWith("Z")) {
                                Estartts = Estartts.concat("Z");
                                Eendts = Eendts.concat("Z");
                                Estartts = iCaltoKWLDate(Estartts);
                                Eendts = iCaltoKWLDate(Eendts);
                            } //Date and time in iCalendar format.
                            else {
                                Estartts = iCaltoKWLDate(Estartts);
                                Eendts = iCaltoKWLDate(Eendts);
                            }
                            Eendts = getTimeHourDiff(Estartts, Eendts);
                            if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                Eeid = calEvent.insertEvent(conn, Ccid, Estartts, Eendts, Esubject, Edescr,
                                        Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "0", "0", "");
                            }
                        }
                    }
                }
                String calDetails = Tree.getCalendar(conn, Ccid);
                com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject(
                        calDetails);
                jobj.getJSONArray("data").getJSONObject(0).put("permissionlevel", "");
                Map<String, String> data = new HashMap<String, String>();
                data.put("action", "1");
                data.put("data", jobj.toString());
                data.put("success", "true");
                ServerEventManager.publish("/calTree/" + projid, data, this.getServletContext());

                String params = AuthHandler.getAuthor(conn, loginid) + " (" + AuthHandler.getUserName(request)
                        + "), " + Ccname + ", " + projdb.getProjectName(conn, projid);
                AuditTrail.insertLog(conn, "127", loginid, Ccid, projid, companyid, params, ipAddress,
                        auditMode);

                conn.commit();
                fstream.close();
                result = KWLErrorMsgs.rsSuccessTrue;

            } else if (request.getParameter("mode").compareToIgnoreCase("merge") == 0) {
                File f1 = getfile(request);
                fstream = new FileInputStream(f1);
                Calendar cal = null;
                String eventDetails = "";
                String cid = "";
                int cnt = 0;
                Ccid = request.getParameter("calId");
                Ccname = Tree.getCalendarName(conn, Ccid);

                setSystemProperties();
                CalendarBuilder bldr = new CalendarBuilder(new CalendarParserImpl());
                cal = bldr.build(fstream);

                for (Iterator i = cal.getComponents().iterator(); i.hasNext();) {
                    Component component = (Component) i.next();
                    Eeid = "";
                    Esubject = "";
                    Estartts = "";
                    Eendts = "";
                    Elocation = "";
                    Edescr = "";
                    for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
                        Property property = (Property) j.next();
                        if (property.getName().equals("UID"))
                            Eeid = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("SUMMARY"))
                            Esubject = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DTSTART"))
                            Estartts = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DTEND"))
                            Eendts = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("LOCATION"))
                            Elocation = StringUtil.serverHTMLStripper(property.getValue());
                        if (property.getName().equals("DESCRIPTION"))
                            Edescr = StringUtil.serverHTMLStripper(property.getValue());
                    }
                    //Property Without End Date
                    if (!StringUtil.isNullOrEmpty(Esubject) && !StringUtil.isNullOrEmpty(Estartts)
                            && StringUtil.isNullOrEmpty(Eendts)) {
                        //Only date given no time
                        if (Estartts.length() < 9)
                            Estartts = iCaltoKWLDayDate(Estartts);
                        //Date and time specified with "TimeZone", hence no "Z" at the end.
                        else if (!Estartts.endsWith("Z")) {
                            Estartts = Estartts.concat("Z");
                            Estartts = iCaltoStartDate(Estartts);
                        } //Date and time in iCalendar format.
                        else
                            Estartts = iCaltoStartDate(Estartts);
                        Eendts = getNextDay(Estartts);//Setting end time as next day

                        if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                            eventDetails = calEvent.getEventDetails(conn, Eeid).toString();
                            if (eventDetails.compareTo("{data:{}}") == 0)
                                Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                        Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                            else if (eventDetails.compareTo("{data:{}}") != 0) {
                                com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject(
                                        eventDetails);
                                cid = jobj.getJSONArray("data").getJSONObject(0).getString("cid");
                                if (cid.compareTo(Ccid) == 0) {
                                    cnt = calEvent.updateAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                            Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", Eeid);
                                } else
                                    Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                            Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                            }
                        }
                    }
                    //Property With End Date
                    else if (!StringUtil.isNullOrEmpty(Esubject) || !StringUtil.isNullOrEmpty(Estartts)
                            || !StringUtil.isNullOrEmpty(Eendts)) {
                        //Only date given no time
                        if (Estartts.length() < 9 && Eendts.length() < 9) {
                            Estartts = iCaltoKWLDayDate(Estartts);
                            Eendts = iCaltoKWLEndDayDate(Eendts);
                            if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                eventDetails = calEvent.getEventDetails(conn, Eeid).toString();
                                Eendts = getTimeHourDiff(Estartts, Eendts);
                                if (eventDetails.compareTo("{data:{}}") == 0)
                                    Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                            Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                                else if (eventDetails.compareTo("{data:{}}") != 0) {
                                    com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject(
                                            eventDetails);
                                    cid = jobj.getJSONArray("data").getJSONObject(0).getString("cid");
                                    if (cid.compareTo(Ccid) == 0)
                                        cnt = calEvent.updateAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                                Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "",
                                                Eeid);
                                    else
                                        Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts,
                                                Esubject, Edescr, Elocation, "b", "m", "",
                                                "1970-01-01 00:00:00", "", "");
                                }
                            }
                        } //Date and time specified with "TimeZone", hence no "Z" at the end.
                        else {
                            if (!Estartts.endsWith("Z") && !Eendts.endsWith("Z")) {
                                Estartts = Estartts.concat("Z");
                                Eendts = Eendts.concat("Z");
                                Estartts = iCaltoKWLDate(Estartts);
                                Eendts = iCaltoKWLDate(Eendts);
                            } //Date and time in iCalendar format.
                            else {
                                Estartts = iCaltoKWLDate(Estartts);
                                Eendts = iCaltoKWLDate(Eendts);
                            }

                            if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                eventDetails = calEvent.getEventDetails(conn, Eeid).toString();
                                Eendts = getTimeHourDiff(Estartts, Eendts);
                                if (eventDetails.compareTo("{data:{}}") == 0)
                                    Eeid = calEvent.insertEvent(conn, Ccid, Estartts, Eendts, Esubject, Edescr,
                                            Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "0", "0", "");
                                else if (eventDetails.compareTo("{data:{}}") != 0) {
                                    com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject(
                                            eventDetails);
                                    cid = jobj.getJSONArray("data").getJSONObject(0).getString("cid");
                                    if (cid.compareTo(Ccid) == 0)
                                        cnt = calEvent.updateEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                                Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "",
                                                Eeid, "0", "0");
                                    else
                                        Eeid = calEvent.insertEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                                Edescr, Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "0",
                                                "0", "");
                                }
                            }
                        }
                    }
                }
                Map<String, String> data = new HashMap<String, String>();
                data.put("action", "4");
                data.put("success", "true");
                data.put("cid", Ccid);
                ServerEventManager.publish("/calEvent/" + Ccid, data, this.getServletContext());

                String params = AuthHandler.getAuthor(conn, loginid) + " (" + AuthHandler.getUserName(request)
                        + "), " + Ccname + ", " + projdb.getProjectName(conn, projid);
                AuditTrail.insertLog(conn, "128", loginid, Ccid, projid, companyid, params, ipAddress,
                        auditMode);

                conn.commit();
                fstream.close();
                result = KWLErrorMsgs.rsSuccessTrue;

            } else if (request.getParameter("mode").compareToIgnoreCase("browse") == 0) {
                String calId = request.getParameter("calId");
                Ccname = Tree.getCalendarName(conn, calId);
                String calSharedCheck = Tree.getCalendarSharedCheck(conn, calId, projid);
                if (calSharedCheck.compareTo("{data:{}}") == 0) {
                    String res = Tree.insertCalPermission(conn, calId, projid, 3);
                    if (!res.equals("0")) {
                        String returnStr = Tree.getSharedCalendar(conn, res, projid);
                        if (returnStr.compareTo("{data:{}}") != 0) {
                            JSONObject jobj = new JSONObject(returnStr.toString());
                            Map<String, String> data = new HashMap<String, String>();
                            data.put("action", "1");
                            data.put("data", jobj.toString());
                            data.put("success", "true");
                            ServerEventManager.publish("/calTree/" + projid, data, this.getServletContext());

                            String params = AuthHandler.getAuthor(conn, loginid) + " ("
                                    + AuthHandler.getUserName(request) + "), " + Ccname + ", "
                                    + projdb.getProjectName(conn, projid);
                            AuditTrail.insertLog(conn, "129", loginid, Ccid, projid, companyid, params,
                                    ipAddress, auditMode);

                            conn.commit();
                            result = KWLErrorMsgs.rsSuccessTrue;
                        }
                    }
                } else {
                    result = KWLErrorMsgs.rsSuccessFalse;
                }
            }
        } else {
            if (request.getParameter("mode").compareToIgnoreCase("url") == 0) {
                String loginid = AuthHandler.getUserid(request);
                String companyid = AuthHandler.getCompanyid(request);
                String ipAddress = AuthHandler.getIPAddress(request);
                conn = DbPool.getConnection();
                String url = request.getParameter("url");
                Ccname = request.getParameter("cname");
                Cdesc = request.getParameter("description");
                String CcolorCode = request.getParameter("colorcode");
                int interval = Integer.parseInt(request.getParameter("interval"));

                result = KWLErrorMsgs.rsSuccessFalse;
                String ID = UUID.randomUUID().toString();
                Calendar cal = setUpICal(url, ID, interval);
                if (cal != null) {
                    Ccid = ID;
                    int cnt = Tree.insertNewCalendar(conn, Ccid, Ccname, Cdesc, "", "", CcolorCode, 4, 0,
                            projid);
                    if (cnt != 0) {
                        Tree.insertInternetCalendar(conn, Ccid, loginid, url, interval);
                        conn.commit();
                        result = KWLErrorMsgs.rsSuccessTrue;

                        String calDetails = Tree.getCalendar(conn, Ccid);
                        JSONObject jobj = new JSONObject(calDetails);
                        jobj.getJSONArray("data").getJSONObject(0).put("permissionlevel", "2");
                        Map<String, String> data = new HashMap<String, String>();
                        data.put("action", "1");
                        data.put("data", jobj.toString());
                        data.put("success", "true");
                        ServerEventManager.publish("/calTree/" + projid, data, this.getServletContext());

                        String params = AuthHandler.getAuthor(conn, loginid) + " ("
                                + AuthHandler.getUserName(request) + "), " + Tree.getCalendarName(conn, Ccid)
                                + ", " + projdb.getProjectName(conn, projid);
                        AuditTrail.insertLog(conn, "124", loginid, Ccid, projid, companyid, params, ipAddress,
                                auditMode);
                    }
                }
            } else if (request.getParameter("mode").compareToIgnoreCase("uploadHoliday") == 0) {
                String src = "";
                conn = DbPool.getConnection();
                Calendar cal = null;
                String[] names = new String[] { "Indian_Holidays", "Italian_Holidays", "Dutch_Holidays",
                        "Canadian_Holidays", "Indonesian_Holidays", "Malaysian_Holidays",
                        "New_Zealand_Holidays", "South_Africa_Holidays", "US_Holidays", "UK_Holidays",
                        "Irish_Holidays", "Mexican_Holidays", "Brazilian_Holidays", "Swedish_Holidays",
                        "Danish_Holidays", "China_Holidays", "Australian_Holidays", "Hong_Kong_C_Holidays",
                        "Finnish_Holidays", "French_Holidays", "German_Holidays", "Hong_Kong_Holidays",
                        "Japanese_Holidays", "Norwegian_Holidays", "Philippines_Holidays",
                        "Portuguese_Holidays", "South_Korean_Holidays", "Spain_Holidays", "Taiwan_Holidays",
                        "Thai_Holidays", "Jewish_Holidays", "Islamic_Holidays" };

                for (int n = 0; n <= names.length; n++) {
                    src = StorageHandler.GetDocStorePath();
                    src = src + StorageHandler.GetFileSeparator() + "HolidayCalendarFiles"
                            + StorageHandler.GetFileSeparator() + names[n] + ".ics";

                    fstream = new FileInputStream(src);
                    setSystemProperties();
                    CalendarBuilder bldr = new CalendarBuilder(new CalendarParserImpl());
                    cal = bldr.build(fstream);

                    Ccid = names[n];

                    for (Iterator i = cal.getComponents().iterator(); i.hasNext();) {
                        Component component = (Component) i.next();
                        Eeid = "";
                        Esubject = "";
                        Estartts = "";
                        Eendts = "";
                        Elocation = "";
                        Edescr = "";
                        for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
                            Property property = (Property) j.next();
                            if (property.getName().equals("SUMMARY")) {
                                Esubject = StringUtil.serverHTMLStripper(property.getValue());
                            }
                            if (property.getName().equals("DTSTART")) {
                                Estartts = StringUtil.serverHTMLStripper(property.getValue());
                            }
                            if (property.getName().equals("DTEND")) {
                                Eendts = StringUtil.serverHTMLStripper(property.getValue());
                            }
                            if (property.getName().equals("LOCATION")) {
                                Elocation = StringUtil.serverHTMLStripper(property.getValue());
                            }
                            if (property.getName().equals("DESCRIPTION")) {
                                Edescr = StringUtil.serverHTMLStripper(property.getValue());
                            }
                        }
                        //Property Without End Date
                        if (!StringUtil.isNullOrEmpty(Esubject) && !StringUtil.isNullOrEmpty(Estartts)
                                && StringUtil.isNullOrEmpty(Eendts)) {
                            //Only date given no time
                            if (Estartts.length() < 9) {
                                Estartts = iCaltoKWLDayDate(Estartts);
                            } //Date and time specified with "TimeZone", hence no "Z" at the end.
                            else if (!Estartts.endsWith("Z")) {
                                Estartts = Estartts.concat("Z");
                                Estartts = iCaltoStartDate(Estartts);
                            } //Date and time in iCalendar format.
                            else {
                                Estartts = iCaltoStartDate(Estartts);
                            }
                            Eendts = getNextDay(Estartts);//Setting end time as next day

                            if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject, "",
                                        Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                            }
                        } //Property With End Date
                        else if (!StringUtil.isNullOrEmpty(Esubject) || !StringUtil.isNullOrEmpty(Estartts)
                                || !StringUtil.isNullOrEmpty(Eendts)) {
                            //Only date given no time
                            if (Estartts.length() < 9 && Eendts.length() < 9) {
                                Estartts = iCaltoKWLDayDate(Estartts);
                                Eendts = iCaltoKWLEndDayDate(Eendts);
                                Eendts = getTimeHourDiff(Estartts, Eendts);
                                if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                    Eeid = calEvent.insertAllDayEvent(conn, Ccid, Estartts, Eendts, Esubject,
                                            "", Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "");
                                }
                            } //Date and time specified with "TimeZone", hence no "Z" at the end.
                            else {
                                if (!Estartts.endsWith("Z") && !Eendts.endsWith("Z")) {
                                    Estartts = Estartts.concat("Z");
                                    Eendts = Eendts.concat("Z");
                                    Estartts = iCaltoKWLDate(Estartts);
                                    Eendts = iCaltoKWLDate(Eendts);
                                } //Date and time in iCalendar format.
                                else {
                                    Estartts = iCaltoKWLDate(Estartts);
                                    Eendts = iCaltoKWLDate(Eendts);
                                }
                                Eendts = getTimeHourDiff(Estartts, Eendts);
                                if (!StringUtil.isNullOrEmpty(Estartts) || !StringUtil.isNullOrEmpty(Eendts)) {
                                    Eeid = calEvent.insertEvent(conn, Ccid, Estartts, Eendts, Esubject, "",
                                            Elocation, "b", "m", "", "1970-01-01 00:00:00", "", "0", "0", "");
                                }
                            }
                        }
                    }

                    conn.commit();
                    fstream.close();
                    result = KWLErrorMsgs.rsSuccessTrue;
                }
            }

        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(importICSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        DbPool.quietRollback(conn);
        Logger.getLogger(importICSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServiceException ex) {
        DbPool.quietRollback(conn);
        String msg = ex.getMessage();
        if (msg.contains(":")) {
            msg = msg.substring(msg.indexOf(":") + 2, msg.length());
        }
        result = KWLErrorMsgs.rsValidTrueSuccessFalseErr + MessageSourceProxy.getMessage(msg, null, request)
                + "\"}";
        Logger.getLogger(importICSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserException ex) {
        DbPool.quietRollback(conn);
        Logger.getLogger(importICSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        DbPool.quietRollback(conn);
        Logger.getLogger(importICSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbPool.quietClose(conn);
        response.getWriter().println(result);
        response.getWriter().close();
    }
}