Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:org.rti.zcore.dar.report.ChooseReportAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //log.debug("Starting Report:" + DateUtils.getTime());
    HttpSession session = request.getSession();
    SessionUtil zeprs_session = null;//  w w w  .  j  a  va 2s  .  co  m
    try {
        zeprs_session = (SessionUtil) session.getAttribute("zeprs_session");
    } catch (Exception e) {
        // unit testing - it's ok...
    }
    String task = "";
    if (request.getParameter("task") != null) {
        task = request.getParameter("task");
    }
    boolean isXml = false;
    if (request.getParameter("isXml") != null) {
        isXml = true;
    }
    boolean isCombinedReport = false; // For combined Monthly Reports for ARV and OI
    boolean isFacilityReport = false; // For combined Monthly Reports for ARV and OI
    boolean dynamicReport = false; // For combined Monthly Reports for ARV and OI
    if (request.getParameter("isCombinedReport") != null) {
        isCombinedReport = true;
        request.setAttribute("isCombinedReport", "1");
    }
    if (request.getParameter("dynamicReport") != null) {
        dynamicReport = true;
        request.setAttribute("dynamicReport", "1");
    }
    if (request.getParameter("isFacilityReport") != null) {
        isFacilityReport = true;
        request.setAttribute("isFacilityReport", "1");
    }

    Report report = null;
    Register register = null;

    int reportID = 0;

    //int reportID = Integer.parseInt(((chooseReportForm) form).getReport());
    if (request.getParameter("report") != null) {
        reportID = (Integer.valueOf(request.getParameter("report").toString()));
    } else {
        return mapping.findForward("reports");
    }

    Date beginDate = null;
    Date endDate = null;
    if (request.getParameter("bdate") != null) {
        beginDate = Date.valueOf(String.valueOf(request.getParameter("bdate")));
    }
    if (request.getParameter("edate") != null) {
        endDate = Date.valueOf(String.valueOf(request.getParameter("edate")));
    }

    if (reportID == 10) {
        isCombinedReport = true;
        reportID = 5;
    } else if (reportID == 14) {
        dynamicReport = true;
        isCombinedReport = true;
        reportID = 5;
    } else if (reportID == 15) {
        dynamicReport = true;
        reportID = 5;
    } else if (reportID == 16) {
        dynamicReport = true;
        reportID = 6;
    } else if (reportID == 17) {
        dynamicReport = true;
        reportID = 7;
    } else if (reportID == 20) {
        isFacilityReport = false;
        isCombinedReport = true;
        reportID = 5;
    }

    /*if (isCombinedReport == true) {
     Calendar gc = new GregorianCalendar();
     gc.setTime(endDate);
     int maxDate = gc.getActualMaximum(Calendar.DAY_OF_MONTH);
     int month = gc.get(Calendar.MONTH);
     int year = gc.get(Calendar.YEAR);
     gc.set(year, month, 0, 0, 0, 0);
     gc.add(Calendar.DAY_OF_MONTH, 1);
     Calendar monthEndCal = new GregorianCalendar();
     monthEndCal.set(year, month, maxDate, 0, 0, 0);
     // re-assign values for begin/endDate
     beginDate = new Date(gc.getTime().getTime());
     endDate = new Date(monthEndCal.getTime().getTime());
    }*/

    java.util.Calendar c = java.util.Calendar.getInstance();
    c.add(java.util.Calendar.MONTH, -1);
    java.util.Date date1monthpast = c.getTime();
    String DATE_FORMAT = "yyyy-MM-dd";
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
    sdf.setTimeZone(TimeZone.getDefault());
    String date1monthpastStr = sdf.format(date1monthpast);
    java.sql.Date date1monthpastSql = java.sql.Date.valueOf(date1monthpastStr);

    // week behind - for defaulters report
    java.util.Calendar c2 = java.util.Calendar.getInstance();
    c2.add(java.util.Calendar.WEEK_OF_YEAR, -1);
    java.util.Date date1weekpast = c2.getTime();
    sdf.setTimeZone(TimeZone.getDefault());
    String date1weekpastStr = sdf.format(date1weekpast);
    java.sql.Date date1weekpastSql = java.sql.Date.valueOf(date1weekpastStr);

    // week ahead
    java.util.Calendar c4 = java.util.Calendar.getInstance();
    c4.add(java.util.Calendar.WEEK_OF_YEAR, +1);
    java.util.Date date1weekahead = c4.getTime();
    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat(DATE_FORMAT);
    sdf2.setTimeZone(TimeZone.getDefault());
    String date1weekaheadStr = sdf2.format(date1weekahead);
    java.sql.Date date1weekaheadSql = java.sql.Date.valueOf(date1weekaheadStr);

    // Name of the forward to use - see ChooseReportAction in struts-config
    // Most of the reports have thier own jsp page. Name sets the name of this file.
    String name = "none";
    // int siteId = ((chooseReportForm) form).getSiteId();
    int siteId = 0;
    if (request.getParameter("siteId") != null) {
        siteId = (Integer.valueOf(request.getParameter("siteId").toString()));
    }
    // boolean  isXml= ((chooseReportForm) form).isXml();
    String siteName;
    if (siteId == 0) {
        siteName = "All sites";
    } else {
        Site site = (Site) DynaSiteObjects.getClinicMap().get((long) siteId);
        siteName = site.getName();
    }
    request.setAttribute("siteId", siteId);
    request.setAttribute("siteName", siteName);
    List records = new ArrayList();
    String abbrev = "enc";
    Class clazz = EncounterData.class;

    java.sql.Date dateNow = DateUtils.getNow();
    request.setAttribute("dateNow", dateNow);

    request.setAttribute("bdate", beginDate);
    request.setAttribute("edate", endDate);

    Principal user = request.getUserPrincipal();
    String username = user.getName();
    ReportCreator reportCreator = new ReportCreator();
    reportCreator.setUsernameR(username);
    System.out.println("Report Id " + reportID);
    switch (reportID) {
    /**/

    case 1:
        System.out.println("OIDailyActivityReport");
        register = new DailyActivityReport();
        register.setType("OIDailyActivityReport");
        register.setSiteName(siteName);
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        request.setAttribute("register", register);
        name = "OIDailyActivityReport";
        abbrev = "OIDAR";
        clazz = DailyActivityReport.class;
        break;
    case 2:
        System.out.println("ARTAdultDailyActivityReport");
        register = new DailyActivityReport();
        register.setType("ARTAdultDailyActivityReport");
        register.setSiteName(siteName);
        register.getPatientRegister(beginDate, endDate, siteId);
        System.out.println("BAck from Database");
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        request.setAttribute("register", register);
        name = "ARTAdultDailyActivityReport";
        abbrev = "ARTADAR";
        clazz = DailyActivityReport.class;
        break;
    case 3:
        System.out.println("OIDailyActivityReport");
        register = new DailyActivityReport();
        register.setType("ARTChildDailyActivityReport");
        register.setSiteName(siteName);
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        request.setAttribute("register", register);
        name = "ARTChildDailyActivityReport";
        abbrev = "ARTCDAR";
        clazz = DailyActivityReport.class;
        break;
    /*            case 4:
       register = new OIARTAdultDailyActivityReport();
       register.setType("print");   // not (longer) view version
       register.setSiteName(siteName);
       register.getPatientRegister(beginDate, endDate, siteId);
       register.setBeginDate(beginDate);
       register.setEndDate(endDate);
       request.setAttribute("register", register);
       name = "OIARTAdultDailyActivityReport";
       abbrev = "OIARTADAR";
       clazz = OIARTAdultDailyActivityReport.class;
       break;*/
    case 5:
        System.out.println("CDRRArtReport");
        //register = new CDRRArtReport();
        register = new DailyActivityReport();
        /*if (dynamicReport == true) {
          request.setAttribute("dynamicReport", "1");
          register.setDynamicReport(true);
        }*/

        register.setType("CDRRArtReport");
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        ClientSettings clientSettings = zeprs_session.getClientSettings();
        Site site = clientSettings.getSite();
        String siteAbbrev = site.getAbbreviation();
        int i = 1;
        String reportFileName = "CDRRArtReport" + "-" + siteAbbrev + "-" + username + "-"
                + DateUtils.getNowPretty() + "-" + i;
        String path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                + Constants.pathSep + reportFileName + ".xls";
        // check if file exists
        File f = new File(path);
        while (f.exists()) {
            i++;
            reportFileName = "CDRRArtReport" + "-" + siteAbbrev + "-" + username + "-"
                    + DateUtils.getNowPretty() + "-" + i;
            path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                    + Constants.pathSep + reportFileName + ".xls";
            f = new File(path);
        }
        register.setReportFileName(reportFileName);
        register.setReportPath(path);
        request.setAttribute("register", register);
        if (isCombinedReport == true) {
            request.setAttribute("isCombinedReport", "1");
        }
        if (isFacilityReport == true) {
            request.setAttribute("isFacilityReport", "1");
        }
        name = "CDRRArtReport";
        abbrev = "CDRRArt";
        //clazz = CDRRArtReport.class;
        SessionUtil.getInstance(session).getReports().put(name, register);
        break;
    case 6:
        System.out.println("print");
        register = new MonthlyArtReport();
        /*if (dynamicReport == true) {
          request.setAttribute("dynamicReport", "1");
          register.setDynamicReport(true);
        }*/
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
        i = 1;
        reportFileName = "MonthlyArtReport" + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty()
                + "-" + i;
        path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                + Constants.pathSep + reportFileName + ".xls";
        // check if file exists
        f = new File(path);
        while (f.exists()) {
            i++;
            reportFileName = "MonthlyArtReport" + "-" + siteAbbrev + "-" + username + "-"
                    + DateUtils.getNowPretty() + "-" + i;
            path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                    + Constants.pathSep + reportFileName + ".xls";
            f = new File(path);
        }
        register.setReportFileName(reportFileName);
        register.setReportPath(path);
        request.setAttribute("register", register);
        name = "MonthlyArtReport";
        abbrev = "MART";
        clazz = MonthlyArtReport.class;
        SessionUtil.getInstance(session).getReports().put(name, register);
        break;
    case 7:
        //register = new CDRROIReport();

        System.out.println("CDRROIReport");
        register = new DailyActivityReport();
        register.setType("CDRROIReport");
        /*if (dynamicReport == true) {
          request.setAttribute("dynamicReport", "1");
          register.setDynamicReport(true);
        }*/
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
        i = 1;
        reportFileName = "CDRROIReport" + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty()
                + "-" + i;
        path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                + Constants.pathSep + reportFileName + ".xls";
        // check if file exists
        f = new File(path);
        while (f.exists()) {
            i++;
            reportFileName = "CDRROIReport" + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty()
                    + "-" + i;
            path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                    + Constants.pathSep + reportFileName + ".xls";
            f = new File(path);
        }
        register.setReportFileName(reportFileName);
        register.setReportPath(path);
        request.setAttribute("register", register);
        name = "CDRROIReport";
        abbrev = "CDRROI";
        clazz = CDRROIReport.class;
        SessionUtil.getInstance(session).getReports().put(name, register);
        break;
    case 8:

        System.out.println("8 AppointmentRegister");
        register = new AppointmentRegister();
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        if (beginDate == null) {
            beginDate = dateNow;
        }
        if (endDate == null) {
            endDate = date1weekaheadSql;
        }
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        request.setAttribute("register", register);
        name = "AppointmentRegister";
        abbrev = "APPREG";
        clazz = AppointmentRegister.class;
        break;
    case 9:
        System.out.println("9+ DefaultersRegister");
        System.out.println("9+ DefaultersRegister");
        register = new DefaultersRegister();
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        if (beginDate == null) {
            beginDate = date1weekpastSql;
        }
        if (endDate == null) {
            endDate = dateNow;
        }
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        request.setAttribute("register", register);
        name = "DefaultersRegister";
        abbrev = "DEFREG";
        clazz = DefaultersRegister.class;
        break;
    case 11:

        System.out.println("9+SiteStatisticsReport");
        register = new SiteStatisticsReport();
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        if (beginDate == null) {
            beginDate = date1monthpastSql;
        }
        if (endDate == null) {
            endDate = dateNow;
        }
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        request.setAttribute("register", register);
        name = "SiteStatisticsReport";
        abbrev = "SSR";
        clazz = SiteStatisticsReport.class;
        break;
    case 12:
        System.out.println("12+StockUsageReport");
        register = new StockUsageReport();
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
        i = 1;
        reportFileName = "Monthly Drug Usage Report" + "-" + siteName.trim() + "-" + username.trim() + "-"
                + DateUtils.getNowPretty() + "-" + i;
        path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                + Constants.pathSep + reportFileName + ".xls";
        // check if file exists
        f = new File(path);
        while (f.exists()) {
            i++;
            reportFileName = "Monthly Drug Usage Report" + "-" + siteName.trim() + "-" + username.trim() + "-"
                    + DateUtils.getNowPretty() + "-" + i;
            path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                    + Constants.pathSep + reportFileName + ".xls";
            f = new File(path);
        }
        beginDate = Date.valueOf("1900-01-01");
        endDate = DateUtils.getNow();
        register.setReportFileName(reportFileName);
        register.setReportPath(path);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        try {
            register.getPatientRegister(beginDate, endDate, siteId);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        }
        request.setAttribute("register", register);
        name = "StockUsageReport";
        if ((!register.getType().equals("error")) && (!register.getType().equals("empty"))) {
            /* response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + path);*/
            //return(null);
            request.setAttribute("message", "Report saved at ");
            request.setAttribute("path", path);
        } else if (register.getType().equals("empty")) {
            request.setAttribute("exception",
                    "There was were not any stock transactions to generate this report.");
            return mapping.findForward("error");
        } else {
            request.setAttribute("exception", "There was an error generating this report.");
            return mapping.findForward("error");
        }
        break;
    case 13:
        System.out.println("RegimenChangeReport");
        register = new RegimenChangeReport();
        register.setType("print"); // not (longer) view version
        register.setSiteName(siteName);
        register.setReportCreator(reportCreator);
        if (beginDate == null) {
            beginDate = date1monthpastSql;
        }
        if (endDate == null) {
            endDate = dateNow;
        }
        register.getPatientRegister(beginDate, endDate, siteId);
        register.setBeginDate(beginDate);
        register.setEndDate(endDate);
        register.setReportDate(dateNow);
        register.setSiteId(siteId);
        request.setAttribute("register", register);
        name = "RegimenChangeReport";
        abbrev = "RCR";
        clazz = RegimenChangeReport.class;
        break;

    /**/
    default:
        break;

    } // end switch

    /* if ((reportID == 12) && (!register.getType().equals("error"))) {
        return(null);
     }*/

    if (isXml) {
        String reportType = null;

        if (records.size() > 0) {
            reportType = "records";
        } else if (register != null) {
            reportType = "register";
        }

        if (reportType != null) {
            XStream xstream = new XStream();
            xstream.alias(abbrev, clazz);
            xstream.alias("log", org.apache.commons.logging.impl.Log4JLogger.class);
            // response.setContentType("text/html");
            response.setContentType("text/xml");
            response.setContentType("application/vnd.ms-excel");
            PrintWriter writer = response.getWriter();
            writer.write("<?xml version=\"1.0\"?>\n");
            if (reportType.equals("records")) {
                xstream.toXML(records, writer);
            } else {
                xstream.toXML(register, writer);
            }
            //writer.write(xml);
            writer.flush();
            writer.close();
            // use writer to render text
            return (null);
            // log.info("saved register " + path + name + "Register.xml");
        }
    }
    if (task.equals("generate")) {
        if (report != null) {
            XStream xstream = new XStream();
            String path = Constants.REPORTS_XML_PATH;
            Writer writer = new BufferedWriter(new FileWriter(path + name + "Report.xml"));
            writer.write("<?xml version=\"1.0\"?>\n");
            xstream.toXML(report, writer);
            //writer.write(xml);
            writer.flush();
            writer.close();
            log.info("saved report " + path + name + "Report.xml");
        } else if (register != null) {
            XStream xstream = new XStream();
            String path = Constants.REPORTS_XML_PATH;
            Writer writer = new BufferedWriter(new FileWriter(path + name + "Report.xml"));
            writer.write("<?xml version=\"1.0\"?>\n");
            xstream.toXML(register, writer);
            //writer.write(xml);
            writer.flush();
            writer.close();
            log.info("saved register " + path + name + "Report.xml");
        }

    }

    return mapping.findForward(name);

}

From source file:com.niroshpg.android.gmail.PlusSampleServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Check if we have stored credentials using the Authorization Flow.
    // Note that we only check if there are stored credentials, but not if they are still valid.
    // The user may have revoked authorization, in which case we would need to go through the
    // authorization flow again, which this implementation does not handle.
    GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow();

    UserService userService = UserServiceFactory.getUserService();
    Credential credential = null;//from   w  w w.  j a  va 2  s.c  o  m
    if (userService != null) {
        String userId = userService.getCurrentUser().getUserId();
        Datastore.saveUserId(userId);
        credential = authFlow.loadCredential(userId);

        //
        if (credential == null) {
            //
            // If we don't have a token in store, redirect to authorization screen.
            logger.warning("auth flow started ...");
            resp.sendRedirect(
                    authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build());
            return;
        }
        //     try{
        //        credential.refreshToken();
        //     }
        //     catch(TokenResponseException e){
        //         resp.sendRedirect(
        //                 authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build());
        //         return;
        //     }

        // Create a new authorized Gmail API client
        Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential)
                .setApplicationName(APP_NAME).build();
        // Make the API call
        BigInteger startHistoryId = null;

        //service.users().getProfile("me").setRequestHeaders(service.users().getProfile("me").getRequestHeaders().)

        startHistoryId = getHistoryId(service, "me", credential);
        logger.warning("hid[url]= " + startHistoryId);
        List<Label> lableList = listLabels(service, "me");

        List<Message> messegeList = listMessagesWithLabels(service, "me",
                Arrays.asList(getLableIdForName(lableList, "EQM")/*,
                                                                 getLableIdForName(lableList,"UNREAD")*/
                ));

        logger.warning("store messages for processing ... ");
        for (Message message : messegeList) {

            //Message detailMessage = getMessage(service, "me", message.getId());
            String messageBody = "";
            try {
                MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                mimeMessage.writeTo(baos);
                messageBody = baos.toString();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //logger.warning("working "+detailMessage.getSnippet()+" ... ");
            //logger.warning("messageBody= "+messageBody+" ... ");

            //String messageBody = StringUtils.newStringUtf8(Base64.decodeBase64(detailMessage.getRaw()));//StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()/*Base64.decodeBase64(detailMessage.getPayload().getBody().decodeData())*/);
            //String messageBody = StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData());
            String extractedMsgBody = MessageUtility.extractData(messageBody);
            //logger.warning("adding "+extractedMsgBody+" ... ");
            Datastore.addMessage(extractedMsgBody);
        }

        logger.warning("invoke send all");
        sendMessagesToAll();
        logger.warning("removing label from messages ...");
        removeUnRead(service, "me", messegeList);

        //List<History> historyList = null;
        //if(messegeList != null && messegeList.size() > 1)
        //{ 
        //   logger.warning("messege count = " + messegeList.size());
        //   
        //   for(Message amsg : messegeList)
        //   {
        //logger.warning("id= " + amsg.getId());
        //   if(amsg.getHistoryId() != null)
        //   {
        //      startHistoryId = amsg.getHistoryId();
        //logger.warning("hid= " + amsg.getHistoryId());
        //      break;
        //   }
        //}
        //      if(startHistoryId != null)
        //      {      
        //         historyList = listHistory(service, "me", startHistoryId);
        //      }
        //      else
        //      {
        //         logger.warning("could not find start history id");
        //         
        //         //historyList = listHistory(service, "me", BigInteger.valueOf(1));
        //         
        //      }
        //   }

        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.println("<!doctype html><html><head>");
        writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        writer.println("<title>" + APP_NAME + "</title>");

        writer.println("</head><body>");

        //printThreadIds(service,writer);
        if (messegeList != null && messegeList.size() > 0) {
            writer.println("<p> msg count = " + messegeList.size() + "</p>");
            //for(Message msg : messegeList){                 
            //writer.println("<p>"+msg.toPrettyString()+"</p>");
            //}
        }
        //           if(historyList != null && historyList.size() >0)
        //           {
        //              for(History history : historyList){                 
        //                 writer.println("<p>"+history.toPrettyString()+"</p>");
        //              }
        //           }
        else {
            writer.println("<p>history not found</p>");
        }

        writer.println("<div class=\"header\"><b>" + req.getUserPrincipal().getName() + "</b> | " + "<a href=\""
                + userService.createLogoutURL(req.getRequestURL().toString()) + "\">Log out</a> | "
                + "<a href=\"http://code.google.com/p/google-api-java-client/source/browse"
                + "/calendar-appengine-sample?repo=samples\">See source code for " + "this sample</a></div>");
        writer.println("<div id=\"main\"/>");
        writer.println("</body></html>");
    } else {
        PrintWriter writer = resp.getWriter();
        writer.println("<!doctype html><html><head>");
        writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        writer.println("<title>" + APP_NAME + "</title>");

        writer.println("</head><body>");
        writer.println("<h2>user service not found</h2>");
        writer.println("</body></html>");
    }

}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Show HTTP header information.//from  w w  w .  ja va2 s .c  om
 */
@SuppressWarnings("unchecked")
protected void showRequestInfo(HttpServletRequest req) {

    if (M_log.isDebugEnabled())
        M_log.debug("DefaultServlet Request Info");

    // Show generic info
    if (M_log.isDebugEnabled())
        M_log.debug("Encoding : " + req.getCharacterEncoding());
    if (M_log.isDebugEnabled())
        M_log.debug("Length : " + req.getContentLength());
    if (M_log.isDebugEnabled())
        M_log.debug("Type : " + req.getContentType());

    if (M_log.isDebugEnabled())
        M_log.debug("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("Protocol : " + req.getProtocol());
    if (M_log.isDebugEnabled())
        M_log.debug("Address : " + req.getRemoteAddr());
    if (M_log.isDebugEnabled())
        M_log.debug("Host : " + req.getRemoteHost());
    if (M_log.isDebugEnabled())
        M_log.debug("Scheme : " + req.getScheme());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Name : " + req.getServerName());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Port : " + req.getServerPort());

    if (M_log.isDebugEnabled())
        M_log.debug("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getAttribute(attributeName).toString());
    }

    // Show HTTP info
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Header Info");

    if (M_log.isDebugEnabled())
        M_log.debug("Authentication Type : " + req.getAuthType());
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Method : " + req.getMethod());
    if (M_log.isDebugEnabled())
        M_log.debug("Path Info : " + req.getPathInfo());
    if (M_log.isDebugEnabled())
        M_log.debug("Path translated : " + req.getPathTranslated());
    if (M_log.isDebugEnabled())
        M_log.debug("Query string : " + req.getQueryString());
    if (M_log.isDebugEnabled())
        M_log.debug("Remote user : " + req.getRemoteUser());
    if (M_log.isDebugEnabled())
        M_log.debug("Requested session id : " + req.getRequestedSessionId());
    if (M_log.isDebugEnabled())
        M_log.debug("Request URI : " + req.getRequestURI());
    if (M_log.isDebugEnabled())
        M_log.debug("Context path : " + req.getContextPath());
    if (M_log.isDebugEnabled())
        M_log.debug("Servlet path : " + req.getServletPath());
    if (M_log.isDebugEnabled())
        M_log.debug("User principal : " + req.getUserPrincipal());
    if (M_log.isDebugEnabled())
        M_log.debug("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getHeader(headerName));
    }
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * This method gets called by the WdsRdbMapper bean to handle a HTTP
 * request. This method must be multi-thread capable. Note that since we're
 * not using Views, this method must return null.
 * //  w ww .j  av  a  2  s .  com
 * @param request
 *            the http request that is being serviced
 * @param response
 *            the response that will be sent back to the service consumer
 * @return must return null since we're not using a view
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****");

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod());
        LOG.trace(getBeanName() + ":handleRequestInternal - uri  = " + request.getRequestURI());
        LOG.trace(getBeanName() + ":handleRequestInternal - protocol  = " + request.getProtocol());
        LOG.trace(getBeanName() + ":handleRequestInternal - secure  = " + request.isSecure());

        // dump all the http headers and their values
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = "
                        + request.getHeader(headerName));
            }
        }

        if (request.getQueryString() != null) {
            LOG.trace(getBeanName() + ":handleRequestInternal - queryString  = " + request.getQueryString());
        }
    }

    long currentTime = System.currentTimeMillis();

    // give the response a Date header with the current time
    response.setDateHeader(DATE_HDR, currentTime);

    // assign the Server header this container's info
    response.setHeader(SERVER_HDR, getServerInfo());

    // determine the HTTP protocol version being used by the client
    // default version will be 0
    int protocolVersion = 0;
    try {
        protocolVersion = Integer
                .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]);
    } catch (Exception exc) {
        LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol "
                + "version, stack trace follows: ");
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
    }

    LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion);

    /*
     * Ok, the request first needs to run the security gauntlet
     * 
     * We do not want to send any error messages back to the client that
     * would give it a hint that we're invoking SQL statements. This is a
     * countermeasure for SQL injection probes.
     */

    // see if this RDB is restricting user agents and if so, validate user
    // agent
    if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty())
            || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) {

        String userAgent = request.getHeader(USER_AGENT_HDR);

        if (userAgent != null && userAgent.length() > 0) {
            LOG.debug(
                    getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent);

            // Convert to lower case as allowed agents have been
            // converted to lower case as well
            userAgent = userAgent.toLowerCase();

            boolean allow = false;
            if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) {
                for (String agent : getAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent "
                                + "was found: " + agent);
                        allow = true;
                        break;
                    }
                }
            } else {
                allow = true;
                for (String agent : getNotAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "non-allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed "
                                + "agent was found: " + agent);
                        allow = false;
                        break;
                    }
                }
            }
            if (!allow) {
                response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized");
                LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized");
                return null;
            }
        } else {
            response.sendError(SC_UNAUTHORIZED,
                    "ERROR, user agent info " + "was not received and is required!");
            LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header "
                    + "is required but was not provided by the client");
            return null;
        }
    }

    // we do not support chunked transfer encoding, which is a http
    // 1.1 feature.
    if (request.getHeader(TRANSFER_ENCODING_HDR) != null
            && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) {
        response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported");
        return null;
    }

    /*
     * isSecure returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS. so, if the channel must be
     * secure, but it is not, then throw an exception and return an error.
     */
    if (isSecure() && !request.isSecure()) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure");
        return null;
    }

    /*
     * getUserPrincipal() returns a java.security.Principal containing the
     * name of the user making this request, else it returns null if the
     * user has not been authenticated. so, if it is mandated that the user
     * be authenticated, but has not been authenticated, then throw an
     * exception and return an error
     */
    if (isAuthenticated() && request.getUserPrincipal() == null) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated");
        return null;
    }

    /*
     * Check for valid method - the only supported http methods are GET,
     * POST, PUT, and DELETE. Here are some good descriptions regarding the
     * methods and their use with respect to this servlet.
     * 
     * The GET method is used for projecting data from the DB. So it maps to
     * a select statement.
     * 
     * The PUT and POST methods are used for inserting or updating an entity
     * in the DB. So they map to either an update or insert.
     * 
     * The DELETE is used for removing one or more entities from the DB. So
     * it maps to a delete.
     * 
     * The bean must be assigned at least one of the methods to service
     */
    Method method = null;
    try {
        method = Enum.valueOf(Method.class, request.getMethod().toUpperCase());
        LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString());
    } catch (IllegalArgumentException e) {
        LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod()
                + "]");
        response.setHeader("Allow", allowedMethodsRsp);
        response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]");
        return null;
    }

    // do some more method validation; i.e., make sure requested method has
    // been assigned a SQL statement
    //
    // TODO: we may be able to remove this block of code
    String s1 = null;
    if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null
            || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) {
        response.setHeader("Allow", allowedMethodsRsp);
        s1 = "HTTP method [" + method + "] is not supported";
        response.sendError(SC_METHOD_NOT_ALLOWED, s1);
        LOG.error(getBeanName() + ":handleRequestInternal - " + s1);
        return null;
    }

    // If the client has specified an 'Accept' header field, then determine
    // if it is willing or capable of accepting JSON or anything (*/*)
    //
    // TODO: what about the client accepting urlencoded strings??
    s1 = request.getHeader(ACCEPT_HDR);
    if (s1 != null && s1.length() > 0) {
        LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media "
                + "type in accept header = " + s1);
        // parse the accept header's content
        String[] mediaTypes = s1.trim().split(COMMA_STR);
        boolean match = false;
        for (String mediaType : mediaTypes) {
            mediaType = mediaType.trim().toLowerCase();
            if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) {
                match = true;
                break;
            }
        }
        if (!match) {
            LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            return null;
        }
    }

    // pick up the corresponding list of SQL statements for this request
    List<SqlStmnt> sqlStmnts = null;
    switch (method) {
    case GET:
        sqlStmnts = getSqlStmnts4Get();
        break;
    case DELETE:
        sqlStmnts = getSqlStmnts4Delete();
        break;
    case PUT:
        sqlStmnts = getSqlStmnts4Put();
        break;
    case POST:
        sqlStmnts = getSqlStmnts4Post();
        break;
    default:
        response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method);
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: "
                + method);
        return null;
    }

    // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~

    // GETs with entity bodies are illegal
    if (method.isGet() && request.getContentLength() > 0) {
        response.sendError(SC_BAD_REQUEST,
                "Client has issued a malformed or illegal request; " + "GET cannot include entity body");
        return null;
    }

    // the DELETE method also cannot include an entity body; however, the
    // servlet containers already ignore them. so no need to check for that

    // see if json object arrived
    boolean jsonObjectPresent = (method.isPost() || method.isPut())
            && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType));

    LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent);

    // see if this is a PUT with entity. we've learned that for PUTs,
    // getParameterMap does not work the same across all servlet containers.
    // so we need take care of this ourselves
    boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0
            && request.getContentType().equalsIgnoreCase(urlEncodedContentType));

    LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent);

    // collect incoming parameters and place them in a common bucket
    //
    // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~
    //
    List<Map<String, String>> cParams = new ArrayList<Map<String, String>>();

    // first, get the incoming query or form parameters (if any); we will
    // assume that each key has only one parameter. in other words,
    // we're not dealing with drop-down boxes or things similar
    if (!putWithBodyPresent && !jsonObjectPresent) {
        Map<String, String[]> qParams = request.getParameterMap();
        if (qParams != null && !qParams.isEmpty()) {
            Map<String, String> qMap = new HashMap<String, String>();
            for (String key : qParams.keySet()) {
                qMap.put(key.toLowerCase(), qParams.get(key)[0]);
            }
            if (!qMap.isEmpty()) {
                cParams.add(qMap);
                LOG.debug(getBeanName() + ": query params = " + qMap.toString());
            }
        }
    }

    // a put with entity body arrived, so get the parameters from the
    // body and place them in the common bucket
    else if (putWithBodyPresent) {

        try {
            Map<String, String> putParams = null;
            // parseUrlEncoded will force keys to lower case
            putParams = Utils.parseUrlEncoded(request.getInputStream());
            if (putParams != null && !putParams.isEmpty()) {
                cParams.add(putParams);
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage());
            return null;
        }
    }

    // ok, a json object arrived, so get parameters defined in that object
    // and place them in the common bucket
    else {
        // its a json object, so parse it to extract params from it
        try {
            List<Map<String, String>> jParams = null;
            // parseJson will ensure that all passed-in JSON objects have
            // the same set of identical keys
            jParams = Utils.parseJson(request.getInputStream());
            if (jParams != null && !jParams.isEmpty()) {
                // if we also got query params then ensure they have the
                // same set of keys as the json params. why anyone would
                // ever do this is beyond me, but I'll leave it in for now
                if (!cParams.isEmpty()) {
                    Map<String, String> cMap = cParams.get(0);
                    Map<String, String> jMap = jParams.get(0);
                    for (String key : cMap.keySet()) {
                        if (jMap.get(key) == null) {
                            String eStr = getBeanName() + ": ERROR, json "
                                    + "object key set does not match query " + "param key set";
                            LOG.error(eStr);
                            response.sendError(SC_BAD_REQUEST, eStr);
                            return null;
                        }
                    }
                    // place the passed in query params in the jParams
                    // bucket
                    jParams.add(cMap);
                }
                // assign the jParams bucket to the common bucket
                cParams = jParams;
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage());
            return null;
        }
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        if (!cParams.isEmpty()) {
            for (int i = 0; i < cParams.size(); i++) {
                LOG.debug(getBeanName() + ": handleRequestInternal - received these params: "
                        + cParams.get(i).toString());
            }
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params");
        }
    }

    // ensure none of the params' values have been black listed
    if (!cParams.isEmpty() && getBlackList().length() > 0) {
        char[] bl = getBlackList().toCharArray();
        for (int i = 0; i < cParams.size(); i++) {
            for (String value : cParams.get(i).values()) {
                if (Utils.isOnBlackList(value, bl)) {
                    response.sendError(SC_BAD_REQUEST,
                            "encountered black listed character in this param " + "value: " + value);
                    LOG.error(getBeanName() + "handleRequestInternal - encountered black listed "
                            + "character in this param value: " + value);
                    return null;
                }

            }
        }
    }

    // find the proper SQL statement based on the incoming parameters' (if
    // any) keys
    SqlStmnt sqlStmnt = null;
    try {
        // getMatch will try and find a match, even if no params were
        // provided.
        // @formatter:off
        sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null)
                : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet());
        // @formatter:on

        if (sqlStmnt == null && !cParams.isEmpty()) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: "
                    + cParams.toString());
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        } else if (sqlStmnt == null) {
            LOG.warn(getBeanName() + ": warning, unable to find sql "
                    + "statement on first pass, will use extra path info");
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString());
        }
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error");
        return null;
    }

    // if getMatch could not find a match - perhaps input params were not
    // provided - then use the URI's 'extended path' information as an input
    // param
    if (sqlStmnt == null) {
        LOG.debug(getBeanName() + ": invoking getExtraPathInfo");
        String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
        } else {
            LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info");
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        }
        // put the xtra path info in the common param bucket and try again
        cParams.clear();
        Map<String, String> xMap = new HashMap<String, String>();
        xMap.put(xtraPathInfo[0], xtraPathInfo[1]);
        cParams.add(xMap);
        // try again with the extra path info
        sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet());
        if (sqlStmnt == null) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: "
                    + cParams.toString());
            response.sendError(SC_NOT_FOUND, "internal server error: mapping error");
            return null;
        }
    }

    // if we've gotten this far, we've gotten past the security gauntlet and
    // we have a SQL statement to work with.
    SqlResult sqlResult = null;
    try {
        // get the output stream
        OutputStream os = response.getOutputStream();

        // FIRE IN THE DB HOLE :)
        if ((sqlResult = sqlStmnt.execute(cParams)) == null) {
            // execute will have logged the necessary debug/error info
            response.sendError(SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // execute went through ok, lets see how to respond
        switch (method) {
        case GET:
            // if a resultset was returned, then set the content type,
            // convert it to json, and write it out
            List<Map<String, Object>> listMap = sqlResult.getResultSet();
            if (listMap != null) {
                // tell the client the content type
                response.setContentType(rspJsonContentType);
                String jsonOutput = Utils.generateJson(sqlResult.getResultSet());
                LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput);
                os.write(jsonOutput.getBytes());

                // ensure that only the client can cache the data and tell
                // the client how long the data can remain active
                response.setHeader(CACHE_CNTRL_HDR,
                        (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR);
                response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR);
                response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000));
            } else {
                LOG.debug(getBeanName() + ": NOT returning json message");
            }
            response.setStatus(SC_OK);
            break;
        case DELETE:
            // a DELETE should not send back an entity body
            response.setStatus(SC_NO_CONTENT);
            break;
        case PUT:
            /*
             * PUTs are idempotent; therefore, they must provide ALL the
             * properties that pertain to the resource/entity that they are
             * creating or updating. Updates cannot be partial updates; they
             * must be full updates. A PUT is issued by a client that knows
             * the identifier (in our case, primary key) of the
             * resource/entity. Therefore, we do not have to send back a
             * Location header in response to a PUT that has created a
             * resource.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
            } else {
                response.setStatus(SC_OK);
            }
            break;
        case POST:
            /*
             * A POST is not idempotent; therefore, it can be used to
             * perform a 'partial' update, as well as a full create. When
             * creating a resource via POST, the client does not know the
             * primary key, and it assumes it will be auto-generated;
             * therefore, a Location header with auto-generated key must be
             * returned to client.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
                // we need to return the new key, but only if it was not a
                // batch insert. the new key should be returned via the
                // location header

                // check if a key holder exists; if not, then table was not
                // configured with auto-generated key.
                String locationPath = request.getRequestURL().toString();
                if (sqlResult.getKeyHolder() != null) {
                    // key holder exists, check and see if a key is
                    // present
                    if (sqlResult.getKeyHolder().getKey() != null) {
                        String id = sqlResult.getKeyHolder().getKey().toString();
                        LOG.debug(getBeanName() + ": getKey() returns " + id);
                        locationPath += ("/" + id);
                        LOG.debug(getBeanName() + ": locationPath = " + locationPath);
                        response.setHeader(LOCATION_HDR, locationPath);
                    }
                    // no key, check for multiple keys
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeys() != null) {
                        Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys();
                        LOG.debug(getBeanName() + ": getKeys() returns " + keyMap);
                    }
                    // maybe map of keys?
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeyList() != null) {
                        for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) {
                            LOG.debug(getBeanName() + ": Map from getKeyList(): " + map);
                        }
                    }
                } else {
                    // if it was not an insert, then it was an update.
                    LOG.debug(getBeanName() + ": key holder was not returned for the insert");
                }
            } else {
                // it was not an insert, so just send back an OK for the
                // update
                response.setStatus(SC_OK);
            }
            break;
        default:
            response.setStatus(SC_OK);
            break;
        }
    } catch (JsonProcessingException exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json "
                + "message: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;

    } finally {
        if (sqlResult != null) {
            SqlResult.enqueue(sqlResult);
        }
    }

    // must return null, because we're not using views!
    return null;
}

From source file:de.innovationgate.wgpublisher.WGACore.java

/**
 * opens a content db based upon request.getRemoteUser and request.getUserPrincipal()
 * if request.getRemoteUser is 'null' and request.getUserPrincipal()!=null, WGDatabase.UNKNOWN_REMOTE_USER is given to the authmodule
 * @param db//  w  w  w  .  ja  va  2  s  . com
 * @param request
 * @return
 * @throws WGAPIException
 * @throws ClientAccessException 
 */
private WGDatabase openContentDBRequestBased(WGDatabase db, HttpServletRequest request, String accessFilter)
        throws WGException {
    if (request == null) {
        return prepareDB(db, request);
    }

    String user = request.getRemoteUser();
    Principal credentials = request.getUserPrincipal();

    if (user == null) {
        user = credentials == null ? WGDatabase.ANONYMOUS_USER : WGDatabase.UNKNOWN_REMOTE_USER;
    }

    db.openSession(user, credentials, accessFilter, request);

    if (db.isSessionOpen()) {
        updateLoginInfo(db, request, DBLoginInfo.AuthType.REQUEST);
    }

    return prepareDB(db, request);
}

From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java

public HashMap<String, Object> processRenewal(CertEnrollmentRequest data, HttpServletRequest request,
        AuthCredentials credentials) throws EBaseException {
    try {//from w  w  w.  j av  a2s.  c  om
        if (CMS.debugOn()) {
            HashMap<String, String> params = data.toParams();
            printParameterValues(params);
        }

        CMS.debug("RenewalProcessor: processRenewal()");

        startTiming("enrollment");
        request.setAttribute("reqType", "renewal");

        // in case of renew, "profile" is the orig profile
        // while "renewProfile" is the current profile used for renewal
        String renewProfileId = (this.profileID == null) ? data.getProfileId() : this.profileID;
        CMS.debug("RenewalProcessor: profile: " + renewProfileId);

        IProfile renewProfile = ps.getProfile(renewProfileId);
        if (renewProfile == null) {
            CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
            throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
        }
        if (!ps.isProfileEnable(renewProfileId)) {
            CMS.debug("RenewalProcessor: Profile " + renewProfileId + " not enabled");
            throw new BadRequestDataException("Profile " + renewProfileId + " not enabled");
        }

        BigInteger certSerial = null;

        // get serial number from <SerialNumber> element (no auth required)
        CertId serial = data.getSerialNum();
        if (serial != null) {
            CMS.debug("RenewalProcessor: serial number: " + serial);
            certSerial = serial.toBigInteger();
        }

        // if not found, get serial number from profile input (no auth required)
        if (certSerial == null) {

            IPluginRegistry registry = (IPluginRegistry) CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);

            // find SerialNumRenewInput
            for (ProfileInput input : data.getInputs()) {

                String inputId = input.getId();
                if (inputId == null) {
                    throw new BadRequestException("Missing input ID");
                }

                String classId = input.getClassId();
                if (classId == null) {
                    throw new BadRequestException("Missing class ID in input " + inputId);
                }

                IPluginInfo pluginInfo = registry.getPluginInfo("profileInput", classId);
                if (pluginInfo == null) {
                    throw new BadRequestException("Unregistered class ID " + classId + " in input " + inputId);
                }

                String className = pluginInfo.getClassName();
                if (!SerialNumRenewInput.class.getName().equals(className)) {
                    // check the next input
                    continue;
                }

                CMS.debug("RenewalProcessor: found SerialNumRenewInput");
                ProfileAttribute attribute = input.getAttribute(SerialNumRenewInput.SERIAL_NUM);

                if (attribute == null) {
                    throw new BadRequestException(
                            "Missing attribute " + SerialNumRenewInput.SERIAL_NUM + " in input " + inputId);
                }

                String value = attribute.getValue();
                CMS.debug("RenewalProcessor: profile input " + SerialNumRenewInput.SERIAL_NUM + " value: "
                        + value);

                if (!StringUtils.isEmpty(value)) {
                    serial = new CertId(value);
                    certSerial = serial.toBigInteger();
                    break;
                }
            }
        }

        // if still not found, get serial number from client certificate (if provided)
        if (certSerial == null) {

            if (!request.isSecure()) {
                throw new BadRequestException("Missing serial number");
            }

            // ssl client auth is to be used
            // this is not authentication. Just use the cert to search
            // for orig request and find the right profile
            CMS.debug("RenewalProcessor: get serial number from client certificate");
            certSerial = getSerialNumberFromCert(request);
        }

        CMS.debug("processRenewal: serial number of cert to renew:" + certSerial.toString());
        ICertRecord rec = certdb.readCertificateRecord(certSerial);
        if (rec == null) {
            CMS.debug("processRenewal: cert record not found for serial number " + certSerial.toString());
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        // check to see if the cert is revoked or revoked_expired
        if ((rec.getStatus().equals(ICertRecord.STATUS_REVOKED))
                || (rec.getStatus().equals(ICertRecord.STATUS_REVOKED_EXPIRED))) {
            CMS.debug("processRenewal: cert found to be revoked. Serial number = " + certSerial.toString());
            throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_CA_CANNOT_RENEW_REVOKED_CERT"));
        }

        X509CertImpl origCert = rec.getCertificate();
        if (origCert == null) {
            CMS.debug("processRenewal: original cert not found in cert record for serial number "
                    + certSerial.toString());
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        Date origNotAfter = origCert.getNotAfter();
        CMS.debug("processRenewal: origNotAfter =" + origNotAfter.toString());

        String origSubjectDN = origCert.getSubjectDN().getName();
        CMS.debug("processRenewal: orig subj dn =" + origSubjectDN);

        IRequest origReq = getOriginalRequest(certSerial, rec);
        if (origReq == null) {
            CMS.debug("processRenewal: original request not found");
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        String profileId = origReq.getExtDataInString(IRequest.PROFILE_ID);
        CMS.debug("RenewalSubmitter: renewal original profileId=" + profileId);

        String aidString = origReq.getExtDataInString(IRequest.AUTHORITY_ID);

        Integer origSeqNum = origReq.getExtDataInInteger(IEnrollProfile.REQUEST_SEQ_NUM);
        IProfile profile = ps.getProfile(profileId);
        if (profile == null) {
            CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(profileId)));
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(profileId)));
        }
        if (!ps.isProfileEnable(profileId)) {
            CMS.debug("RenewalSubmitter: Profile " + profileId + " not enabled");
            throw new BadRequestDataException("Profile " + profileId + " not enabled");
        }

        IProfileContext ctx = profile.createContext();

        if (aidString != null)
            ctx.set(IEnrollProfile.REQUEST_AUTHORITY_ID, aidString);

        IProfileAuthenticator authenticator = renewProfile.getAuthenticator();
        IProfileAuthenticator origAuthenticator = profile.getAuthenticator();

        if (authenticator != null) {
            CMS.debug("RenewalSubmitter: authenticator " + authenticator.getName() + " found");
            setCredentialsIntoContext(request, credentials, authenticator, ctx);
        }

        // for renewal, this will override or add auth info to the profile context
        if (origAuthenticator != null) {
            CMS.debug("RenewalSubmitter: for renewal, original authenticator " + origAuthenticator.getName()
                    + " found");
            setCredentialsIntoContext(request, credentials, origAuthenticator, ctx);
        }

        // for renewal, input needs to be retrieved from the orig req record
        CMS.debug("processRenewal: set original Inputs into profile Context");
        setInputsIntoContext(origReq, profile, ctx, locale);
        ctx.set(IEnrollProfile.CTX_RENEWAL, "true");
        ctx.set("renewProfileId", renewProfileId);
        ctx.set(IEnrollProfile.CTX_RENEWAL_SEQ_NUM, origSeqNum.toString());

        // for ssl authentication; pass in servlet for retrieving
        // ssl client certificates
        SessionContext context = SessionContext.getContext();
        context.put("profileContext", ctx);
        context.put("sslClientCertProvider", new SSLClientCertProvider(request));
        CMS.debug("RenewalSubmitter: set sslClientCertProvider");
        if (origSubjectDN != null)
            context.put("origSubjectDN", origSubjectDN);

        // before creating the request, authenticate the request
        IAuthToken authToken = null;
        Principal principal = request.getUserPrincipal();
        if (principal instanceof PKIPrincipal)
            authToken = ((PKIPrincipal) principal).getAuthToken();
        if (authToken == null)
            authToken = authenticate(request, origReq, authenticator, context, true, credentials);

        // authentication success, now authorize
        authorize(profileId, renewProfile, authToken);

        ///////////////////////////////////////////////
        // create and populate requests
        ///////////////////////////////////////////////
        startTiming("request_population");
        IRequest[] reqs = profile.createRequests(ctx, locale);
        populateRequests(data, true, locale, origNotAfter, origSubjectDN, origReq, profileId, profile, ctx,
                authenticator, authToken, reqs);
        endTiming("request_population");

        ///////////////////////////////////////////////
        // submit request
        ///////////////////////////////////////////////
        String errorCode = submitRequests(locale, profile, authToken, reqs);
        String errorReason = null;

        List<String> errors = new ArrayList<String>();
        if (errorCode != null) {
            for (IRequest req : reqs) {
                String error = req.getError(locale);
                if (error != null) {
                    String code = req.getErrorCode(locale);
                    errors.add(codeToReason(locale, code, error, req.getRequestId()));
                }
            }
            errorReason = StringUtils.join(errors, '\n');
        }

        HashMap<String, Object> ret = new HashMap<String, Object>();
        ret.put(ARG_REQUESTS, reqs);
        ret.put(ARG_ERROR_CODE, errorCode);
        ret.put(ARG_ERROR_REASON, errorReason);
        ret.put(ARG_PROFILE, profile);

        CMS.debug("RenewalSubmitter: done serving");
        endTiming("enrollment");

        return ret;
    } finally {
        SessionContext.releaseContext();
        endAllEvents();
    }
}

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

/**
 * The LOCK method.//from w  w w  .  ja va  2  s  .com
 *
 * @param req the HTTP request
 * @param resp the HTTP response
 * @throws IOException if an error occurs while sending the response
 * @throws ServletException
 */
private void doLock(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    LockInfo lock = new LockInfo();
    // Parsing lock request

    // Parsing depth header
    String depthStr = req.getHeader("Depth");
    if (depthStr == null)
        lock.depth = INFINITY;
    else if (depthStr.equals("0"))
        lock.depth = 0;
    else
        lock.depth = INFINITY;

    // Parsing timeout header
    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null)
        lockDuration = DEFAULT_TIMEOUT;
    else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1)
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        if (lockDurationStr.startsWith("Second-"))
            lockDuration = new Integer(lockDurationStr.substring(7)).intValue();
        else if (lockDurationStr.equalsIgnoreCase("infinity"))
            lockDuration = MAX_TIMEOUT;
        else
            try {
                lockDuration = new Integer(lockDurationStr).intValue();
            } catch (NumberFormatException e) {
                lockDuration = MAX_TIMEOUT;
            }
        if (lockDuration == 0)
            lockDuration = DEFAULT_TIMEOUT;
        if (lockDuration > MAX_TIMEOUT)
            lockDuration = MAX_TIMEOUT;
    }
    lock.expiresAt = System.currentTimeMillis() + lockDuration * 1000;

    int lockRequestType = LOCK_CREATION;
    Node lockInfoNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (IOException e) {
        lockRequestType = LOCK_REFRESH;
    } catch (SAXException e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {
        // Reading lock information
        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope"))
                    lockScopeNode = currentNode;
                if (nodeName.endsWith("locktype"))
                    lockTypeNode = currentNode;
                if (nodeName.endsWith("owner"))
                    lockOwnerNode = currentNode;
                break;
            }
        }

        if (lockScopeNode != null) {
            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1)
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    else
                        lock.scope = tempScope;
                    break;
                }
            }
            if (lock.scope == null)
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        } else
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);

        if (lockTypeNode != null) {
            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1)
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    else
                        lock.type = tempType;
                    break;
                }
            }

            if (lock.type == null)
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        } else
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);

        if (lockOwnerNode != null) {
            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null)
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        } else
            lock.owner = new String();
    }

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

    if (lockRequestType == LOCK_CREATION) {
        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if (exists && object instanceof Folder && lock.depth == INFINITY)
            // Locking a collection (and all its member resources)
            lock.tokens.addElement(lockToken);
        else {
            // Locking a single resource
            lock.tokens.addElement(lockToken);
            // Add the Lock-Token header as by RFC 2518 8.10.1
            // - only do this for newly created locks
            resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");

        }
    }

    if (lockRequestType == LOCK_REFRESH) {

    }

    // Set the status, then generate the XML response containing
    // the lock information.
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);
    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);
    lock.toXML(generatedXML);
    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);
    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();
}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * LOCK Method./* w w  w .jav a 2  s .  c o m*/
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    WebdavServlet.LockInfo lock = new WebdavServlet.LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                resp.setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            WebdavServlet.LockInfo presentLock = (WebdavServlet.LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        WebdavServlet.LockInfo toRenew = (WebdavServlet.LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (WebdavServlet.LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * LOCK Method./*from   w  ww. j  a  v a  2 s  .  c  o m*/
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
        return;
    }

    LockInfo lock = new LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

        } else {
            // Bad request
            resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

        } else {
            // Bad request
            resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

            // contribute feeds us an owner that looks
            // like <A:href>...</A:href>. Since we'll put it
            // back with a different namespace prefix, we
            // don't want to save it that way.

            lock.owner = lock.owner.replaceAll("<(/?)[^>]+:([hH][rR][eE][fF])>", "<$1$2>");
            // System.out.println("lock.owner: " + lock.owner);

        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);
    String lockToken = null;

    lock.path = path;

    // Retrieve the resources
    // DirContext resources = getResources();
    DirContextSAKAI resources = getResourcesSAKAI();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    // We don't want to allow just anyone to lock a resource.
    // It seems reasonable to allow it only for someone who
    // is allowed to modify it.
    if (prohibited(path) || !(exists ? contentHostingService.allowUpdateResource(adjustId(path))
            : contentHostingService.allowAddResource(adjustId(path)))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN, path);
        return;
    }

    Enumeration<LockInfo> locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        lockToken = MD5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector<String> lockPaths = new Vector<String>();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration<String> lockPathsList = lockPaths.elements();

                resp.setStatus(SakaidavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement("D", "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement("D", "response", XMLWriter.OPENING);
                    generatedXML.writeElement("D", "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + SakaidavStatus.SC_LOCKED + " "
                            + SakaidavStatus.getStatusText(SakaidavStatus.SC_LOCKED));
                    generatedXML.writeElement("D", "status", XMLWriter.CLOSING);

                    generatedXML.writeElement("D", "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;

            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(SakaidavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(SakaidavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }

            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }

        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            LockInfo presentLock = (LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(SakaidavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector<String> lockNulls = lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector<String>();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }

            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null)
            ifHeader = "";

        // Checking resource locks

        LockInfo toRenew = (LockInfo) resourceLocks.get(path);
        Enumeration<String> tokenList = null;
        if ((lock != null) && (toRenew != null) && (toRenew.tokens != null)) {
            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }
        }

        // Checking inheritable collection locks

        Enumeration<LockInfo> collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement("D", "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML, true);

    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement("D", "prop", XMLWriter.CLOSING);

    /* the RFC requires this header in response to lock creation */

    if (lockRequestType == LOCK_CREATION)
        resp.addHeader("Lock-Token", "opaquelocktoken:" + lockToken);

    resp.setStatus(exists ? SakaidavStatus.SC_OK : SakaidavStatus.SC_CREATED);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:org.ecocean.servlet.AdoptionAction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String adopterName = "";
    String adopterAddress = "";
    String adopterEmail = "";
    String adopterImage;/*from www. j a v  a2s .c o m*/
    String adoptionStartDate = "";
    String adoptionEndDate = "";
    String adopterQuote = "";
    String adoptionManager = "";
    String shark = "";
    String encounter = "";
    String notes = "";
    String adoptionType = "";
    String number = "";
    String text = "";

    // Saved to the selected shark, not the adoption.
    String newNickName = "";

    // Storing the customer ID here makes the subscription cancellation process easier to do in less moves.
    String stripeCustomerID = "";

    // Stores some wack response string from google recaptcha.
    String gresp = "";

    boolean adoptionSuccess = true;
    String failureMessage = "";

    //set UTF-8
    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession(true);
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.setAction("AdoptionAction.class");
    System.out.println("in context " + context);
    //request.getSession()getServlet().getServletContext().getRealPath("/"));
    String rootDir = getServletContext().getRealPath("/");
    System.out.println("rootDir=" + rootDir);

    // This value is only stored in the email specific edit form.
    Boolean emailEdit = false;
    if ((Boolean) session.getAttribute("emailEdit") != false) {
        emailEdit = (Boolean) session.getAttribute("emailEdit");
        number = (String) session.getAttribute("sessionAdoptionID");
    }
    //setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
    //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();}
    File adoptionsDir = new File(shepherdDataDir.getAbsolutePath() + "/adoptions");
    if (!adoptionsDir.exists()) {
        adoptionsDir.mkdirs();
    }

    //get the form to read data from
    // AdoptionForm theForm = (AdoptionForm) form;

    //set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String fileName = "None";
    String username = "None";
    String fullPathFilename = "";

    String id = "";

    boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end)
    String doneMessage = "";
    List<String> filesOK = new ArrayList<String>();
    HashMap<String, String> filesBad = new HashMap<String, String>();

    List<FileItem> formFiles = new ArrayList<FileItem>();

    Calendar date = Calendar.getInstance();

    long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context);
    long maxSizeBytes = maxSizeMB * 1048576;

    //set form value hashmap
    HashMap fv = new HashMap();

    //else {
    id = "adpt" + (new Integer(date.get(Calendar.DAY_OF_MONTH))).toString()
            + (new Integer(date.get(Calendar.MONTH) + 1)).toString()
            + (new Integer(date.get(Calendar.YEAR))).toString()
            + (new Integer(date.get(Calendar.HOUR_OF_DAY))).toString()
            + (new Integer(date.get(Calendar.MINUTE))).toString()
            + (new Integer(date.get(Calendar.SECOND))).toString();
    //}

    System.out.println("Starting an adoption submission...");
    Calendar todayDate = Calendar.getInstance();

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            upload.setHeaderEncoding("UTF-8");
            List<FileItem> multiparts = upload.parseRequest(request);
            //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (item.isFormField()) { //plain field
                    fv.put(item.getFieldName(),
                            ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon
                    //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")");

                } else { //file
                    //System.out.println("content type???? " + item.getContentType());   TODO note, the helpers only check extension
                    if (item.getSize() > maxSizeBytes) {
                        filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB");
                    } else if (myShepherd.isAcceptableImageFile(item.getName())
                            || myShepherd.isAcceptableVideoFile(item.getName())) {
                        formFiles.add(item);
                        filesOK.add(item.getName());

                    } else {
                        filesBad.put(item.getName(), "invalid type of file");
                    }
                }
            }

            doneMessage = "File Uploaded Successfully";
            fileSuccess = true;

        } catch (Exception ex) {
            doneMessage = "File Upload Failed due to " + ex;
        }

    } else {
        doneMessage = "Sorry this Servlet only handles file upload request";
    }

    session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray())));
    String badmsg = "";
    for (String key : filesBad.keySet()) {
        badmsg += key + " (" + getVal(filesBad, key) + ") ";
    }
    if (badmsg.equals("")) {
        badmsg = "none";
    }
    session.setAttribute("filesBadMessage", badmsg);

    boolean isEdit = false;

    if (fileSuccess) {

        if ((fv.get("number") != null) && !fv.get("number").toString().equals("")) {

            //handle adoption number processing
            number = fv.get("number").toString();
            if ((number != null) && (!number.equals(""))) {
                isEdit = true;
                System.out.println("Ping! Hit adoption number recieved by action servlet.");
                //myShepherd.beginDBTransaction();
            }

            //end adoption number/id processing
        }

        if ((fv.get("adopterName") != null) && !fv.get("adopterName").toString().equals("")) {
            adopterName = fv.get("adopterName").toString().trim();
        }
        if ((fv.get("adopterAddress") != null) && !fv.get("adopterAddress").toString().equals("")) {
            adopterAddress = fv.get("adopterAddress").toString().trim();
        }
        if ((fv.get("adopterEmail") != null) && !fv.get("adopterEmail").toString().equals("")) {
            adopterEmail = fv.get("adopterEmail").toString().trim();
        }

        if ((fv.get("adoptionStartDate") != null) && !fv.get("adoptionStartDate").toString().equals("")) {
            adoptionStartDate = fv.get("adoptionStartDate").toString().trim();
        }

        if ((fv.get("adoptionEndDate") != null) && !fv.get("adoptionEndDate").toString().equals("")) {
            adoptionEndDate = fv.get("adoptionEndDate").toString().trim();
        }

        if ((fv.get("adopterQuote") != null) && !fv.get("adopterQuote").toString().equals("")) {
            adopterQuote = fv.get("adopterQuote").toString().trim();
        }

        if ((fv.get("adoptionManager") != null) && !fv.get("adoptionManager").toString().equals("")) {
            adoptionManager = fv.get("adoptionManager").toString().trim();
        }

        if ((fv.get("shark") != null) && !fv.get("shark").toString().equals("")) {
            shark = fv.get("shark").toString().trim();
        }

        if ((fv.get("encounter") != null) && !fv.get("encounter").toString().equals("")) {
            encounter = fv.get("encounter").toString().trim();
        }

        if ((fv.get("notes") != null) && !fv.get("notes").toString().equals("")) {
            notes = fv.get("notes").toString().trim();
        }

        if ((fv.get("adoptionType") != null) && !fv.get("adoptionType").toString().equals("")) {
            adoptionType = fv.get("adoptionType").toString().trim();
        }

        if ((fv.get("text") != null) && !fv.get("text").toString().equals("")) {
            text = fv.get("text").toString().trim();
        }

        // New nickname to save to marked individual object.

        if ((fv.get("newNickName") != null) && !fv.get("newNickName").toString().equals("")) {
            newNickName = fv.get("newNickName").toString().trim();
        }

        if ((fv.get("g-recaptcha-response") != null) && !fv.get("g-recaptcha-response").toString().equals("")) {
            gresp = fv.get("g-recaptcha-response").toString().trim();
        }

        if (isEdit) {
            id = number;
        }

        // Grab the stripe customer out of session.

        stripeCustomerID = (String) session.getAttribute("stripeID");

        File thisAdoptionDir = new File(adoptionsDir.getAbsolutePath() + "/" + id);
        if (!thisAdoptionDir.exists()) {
            thisAdoptionDir.mkdirs();
        }

        String baseDir = ServletUtilities.dataDir(context, rootDir);
        ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>();
        for (FileItem item : formFiles) {
            /* this will actually write file to filesystem (or [FUTURE] wherever)
               TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc. */
            //try {
            //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir);
            //SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir);

            try {

                //retrieve the file data
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = item.getInputStream();
                //System.out.println(writeFile);
                //if ((!(file[iter].getFileName().equals(""))) && (file[iter].getFileSize() > 0)) {
                //write the file to the file specified
                //String writeName=file[iter].getFileName().replace('#', '_').replace('-', '_').replace('+', '_').replaceAll(" ", "_");
                //String writeName=forHTMLTag(file[iter].getFileName());
                String writeName = "adopter.jpg";

                //String writeName=URLEncoder.encode(file[iter].getFileName(), "UTF-8");
                //while (writeName.indexOf(".") != writeName.lastIndexOf(".")) {
                //  writeName = writeName.replaceFirst("\\.", "_");
                // }
                //System.out.println(writeName);

                OutputStream bos = new FileOutputStream(new File(thisAdoptionDir, writeName));
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.close();
                //data = "The file has been written to \"" + id + "\\" + writeName + "\"";
                adopterImage = writeName;
                // }
                //close the stream
                stream.close();
                baos.close();
            } catch (FileNotFoundException fnfe) {
                System.out.println("File not found exception.\n");
                fnfe.printStackTrace();
                //return null;
            } catch (IOException ioe) {
                System.out.println("IO Exception.\n");
                ioe.printStackTrace();
                //return null;
            }

        }

        // This verifies the user being logged in or passing the recapture.
        boolean loggedIn = false;
        try {
            if (request.getUserPrincipal() != null) {
                loggedIn = true;
            }
        } catch (NullPointerException ne) {
            System.out.println("Got a null pointer checking for logged in user.");
        }
        boolean validCaptcha = false;
        if (loggedIn != true) {
            String remoteIP = request.getRemoteAddr();
            validCaptcha = ServletUtilities.captchaIsValid(context, gresp, remoteIP);
            System.out.println("Results from captchaIsValid(): " + validCaptcha);
        }
        if ((validCaptcha == true) || (loggedIn == true)) {
            System.out.println("Ping! Hit the Adoption creation section.");
            try {
                Adoption ad = new Adoption(id, adopterName, adopterEmail, adoptionStartDate, adoptionEndDate);
                if (isEdit || emailEdit) {
                    ad = myShepherd.getAdoption(number);
                    ad.setAdopterName(adopterName);
                    ad.setAdopterEmail(adopterEmail);
                    ad.setAdoptionEndDate(adoptionEndDate);
                    ad.setAdoptionStartDate(adoptionStartDate);
                }

                ad.setAdopterQuote(adopterQuote);
                ad.setAdoptionManager(adoptionManager);
                ad.setIndividual(shark);
                ad.setEncounter(encounter);
                ad.setNotes(notes);
                ad.setAdoptionType(adoptionType);
                ad.setAdopterAddress(adopterAddress);
                ad.setStripeCustomerId(stripeCustomerID);

                if ((filesOK != null) && (filesOK.size() > 0)) {
                    ad.setAdopterImage(filesOK.get(0));
                }

                myShepherd.beginDBTransaction();

                if (adoptionSuccess && !isEdit) {
                    try {
                        myShepherd.storeNewAdoption(ad, id);
                    } catch (Exception e) {
                        adoptionSuccess = false;
                        failureMessage += "Failed to presist the new adoption.<br>";
                    }
                }

                // New logic to change marked individual nickname if necessary in adoption.
                MarkedIndividual mi = myShepherd.getMarkedIndividual(shark);
                if (!newNickName.equals("")) {
                    if (adoptionSuccess && !isEdit) {
                        try {
                            mi.setNickName(newNickName);
                            mi.setNickNamer(adopterName);
                        } catch (Exception e) {
                            failureMessage += "Retrieving shark to set nickname failed.<br>";
                        }
                    }
                }

                // Sends a confirmation email to a a new adopter with cancellation and update information.
                if (emailEdit == false) {
                    try {
                        String emailContext = "context0";
                        String langCode = "en";
                        String to = ad.getAdopterEmail();
                        String type = "adoptionConfirmation";
                        System.out.println("About to email new adopter.");
                        // Retrieve background service for processing emails
                        ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService();
                        Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, mi, ad);
                        NotificationMailer mailer = new NotificationMailer(emailContext, langCode, to, type,
                                tagMap);
                        NotificationMailer adminMailer = new NotificationMailer(emailContext, langCode,
                                CommonConfiguration.getNewSubmissionEmail(emailContext), type, tagMap);
                        es.execute(mailer);
                        es.execute(adminMailer);
                    } catch (Exception e) {
                        System.out.println("Error in sending email confirmation of adoption.");
                        e.printStackTrace();
                    }
                }

                if ((adoptionSuccess && isEdit) || (emailEdit == true)) {
                    myShepherd.commitDBTransaction();
                }

            } catch (Exception e) {
                System.out.println("The recaptcha passed but something went wrong saving the adoption.");
                e.printStackTrace();
            }

        }

    }
    // Sets adoption paid to false to allow multiple adoptions
    session.setAttribute("paid", false);

    //return a forward to display.jsp
    System.out.println("Ending adoption data submission.");
    //if((submitterID!=null)&&(submitterID.equals("deepblue"))) {
    if ((adoptionSuccess) && (emailEdit == false)) {
        response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/adoptions/adoptionSuccess.jsp?id=" + id);
    } else if ((adoptionSuccess) && (emailEdit == true)) {
        response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/adoptions/editSuccess.jsp");
    } else {
        response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/adoptions/adoptionFailure.jsp?message=" + failureMessage);
    }

    //}

    myShepherd.closeDBTransaction();

}