Example usage for javax.servlet.http HttpServletRequest getLocalPort

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

Introduction

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

Prototype

public int getLocalPort();

Source Link

Document

Returns the Internet Protocol (IP) port number of the interface on which the request was received.

Usage

From source file:cz.zcu.kiv.eegdatabase.logic.controller.myaccount.ApplyForWritingPermissionController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    log.debug("Processing the form");
    ApplyForWritingPermissionCommand afwpc = (ApplyForWritingPermissionCommand) command;

    log.debug("Loading Person object of actual logged user from database");
    Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());

    log.debug("Composing e-mail message");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);
    mail.setFrom(user.getEmail());//from  ww w  .  jav  a  2s  .c  o m

    log.debug("Loading list of supervisors");
    List<Person> supervisors = personDao.getSupervisors();
    String[] emails = new String[supervisors.size()];
    int i = 0;
    for (Person supervisor : supervisors) {
        emails[i++] = supervisor.getEmail();
    }
    mail.setTo(emails);

    log.debug("Setting subject to e-mail message");
    mail.setSubject(mail.getSubject() + " - Write permission request from user " + user.getUsername());

    String messageBody = "User " + user.getUsername()
            + " has requested permission for adding data into EEGbase system.\n" + "Reason is: "
            + afwpc.getReason() + "\n" + "Use the address below to grant the write permission.\n";
    String linkAddress = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath() + "/system/grant-permission.html?id=" + user.getPersonId();
    log.debug("Address is: " + linkAddress);
    messageBody += linkAddress;
    mail.setText(messageBody);

    String mavName = "";
    try {
        log.debug("Sending message");
        mailSender.send(mail);
        log.debug("Mail was sent");
        mavName = getSuccessView();
    } catch (MailException e) {
        log.debug("Mail was not sent");
        mavName = getFailView();
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(mavName);
    return mav;
}

From source file:org.bibalex.wamcp.storage.WAMCPStorage.java

public/* synchronized */void release(Document metadataXml, Element metaAlbum)
        throws BAGException, WAMCPException, WFSVNArtifactLoadingException, WFSVNLockedException {
    this.guardArtifactLoaded();

    // JdbcTemplate locksDBTempl =
    // this.svnClient.getWfProcess().getJdbcTempl();

    String releasedMetaGallUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(),
            BAGGalleryAbstract.FILENAME_GALLERY_METADATA_XML);

    try {/*from  w w w  .  jav  a  2 s  .  co m*/
        XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setEncoding("UTF-8"));

        this.svnClient.getWfProcess().lockUrlStr(releasedMetaGallUrlStr, this.sessionBBean.getUserName());

        try {
            SAXBuilder saxBuilder = new SAXBuilder();

            saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
            saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
            saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            // Unsupported:
            // saxBuilder.setFeature("http://xml.org/sax/features/xmlns-uris",
            // false);

            Document metaGalleryXml;

            ByteArrayOutputStream remoteFileOS = new ByteArrayOutputStream();
            ByteArrayInputStream metaGalleryIn = null;
            try {
                BAGStorage.readRemoteFile(releasedMetaGallUrlStr, remoteFileOS);

                metaGalleryIn = new ByteArrayInputStream(remoteFileOS.toByteArray());

                metaGalleryXml = saxBuilder.build(metaGalleryIn);

            } finally {
                try {
                    remoteFileOS.close();
                    metaGalleryIn.close();
                } catch (IOException e) {
                    throw new BAGException(e);
                }
            }
            XPath oldMetaAlbumXP = XPath
                    .newInstance("//album[@name='" + metaAlbum.getAttributeValue("name") + "']");

            Element metaGalleryRoot = metaGalleryXml.getRootElement();
            for (Object oldMetaAlbum : oldMetaAlbumXP.selectNodes(metaGalleryRoot)) {
                ((Element) oldMetaAlbum).detach();
            }

            metaGalleryRoot.addContent(metaAlbum);

            File metaGalleryTempFile = File
                    .createTempFile(FileUtils.makeSafeFileName(this.sessionBBean.getUserName()), "metagallery");
            FileOutputStream metaGalleryOut = new FileOutputStream(metaGalleryTempFile);

            outputter.output(metaGalleryXml, metaGalleryOut);

            metaGalleryOut.flush();
            metaGalleryOut.close();

            String releasedXMLUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(),
                    "XML", filenameForShelfMark(this.artifact.getArtifactName()) + ".tei.xml");

            File msDescTempFile = File.createTempFile(
                    FileUtils.makeSafeFileName(this.sessionBBean.getUserName()), "msDescReleased");
            FileOutputStream msDescOut = new FileOutputStream(msDescTempFile);

            outputter.output(metadataXml, msDescOut);

            msDescOut.flush();
            msDescOut.close();

            // BAGStorage.copyFile(msDescTempFile.toURI().toString(),
            // releasedXMLUrlStr);
            // BAGStorage.copyFile(metaGalleryTempFile.toURI().toString(),
            // releasedMetaGallUrlStr);
            // TODO be DRY

            if (!BAGStorage.putFile(releasedXMLUrlStr, msDescTempFile, null)) {
                throw new WAMCPGeneralCorrectableException("Could not upload tei file to release destination");
            }

            if (!BAGStorage.putFile(releasedMetaGallUrlStr, metaGalleryTempFile, null)) {
                throw new WAMCPGeneralCorrectableException(
                        "Could not upload meta gallery file to release destination");
            }

            generateMARCFile(msDescTempFile, this.artifact.getArtifactName(),
                    this.galleryBean.getGalleryRootUrlStr());

            // generate html file for the manuscript on release
            // both versions are generated (full and DIV)
            // also generate html for metadata print
            // also generate pdf for images of manuscript
            // Yasmine20110508 {
            // Yasmine20110621{

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequest();
            String uri = request.getRequestURL().toString();
            String[] splited = uri.split("/");
            // host = http://172.16.0.17:80/
            //              String host = splited[0]+"//"+splited[2]+"/";
            String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

            int statusCode = 0;
            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(this.artifact.getArtifactName());
            String url = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=html";
            statusCode = myGetHttp(url);
            System.out.println(url + " ==> status code: " + statusCode);

            String urlDivOpt = host + "BAG-API/rest/desc/" + oaiId + "/transform?divOpt=true&type=html";
            statusCode = myGetHttp(urlDivOpt);
            System.out.println(urlDivOpt + " ==> status code: " + statusCode);

            String urlMetadataHtml = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=meta";
            statusCode = myGetHttp(urlMetadataHtml);
            System.out.println(urlMetadataHtml + " ==> status code: " + statusCode);

            //            String rootUrlStr = this.galleryBean.getGalleryRootUrlStr();
            //            String tempUserName = this.sessionBBean.getUserName();
            //            System.out.println("rootUrlStr: "+rootUrlStr);
            //            System.out.println("tempUserName: "+tempUserName);
            //            transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  filenameForShelfMark(this.artifact.getArtifactName()),
            //                  false);
            //            transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  filenameForShelfMark(this.artifact.getArtifactName()),
            //                  true);
            // } Yasmine20110621
            // } Yasmine20110508
        } finally {
            this.svnClient.getWfProcess().unlockUrlStr(releasedMetaGallUrlStr, this.sessionBBean.getUserName());
        }
    } catch (DataIntegrityViolationException e) {
        throw new WAMCPGeneralCorrectableException(
                "Another user is releasing at the moment, try again in a few seconds");
    } catch (JDOMException e) {
        throw new WAMCPException(e);
    } catch (IOException e) {
        throw new WAMCPException(e);
    }

}

From source file:siddur.solidtrust.site.APIController.java

@RequestMapping(value = "/car_manual")
public @ResponseBody Object carManual(@RequestParam("brand") String brand, @RequestParam("model") String model,
        HttpServletRequest request, HttpServletResponse resp) {
    resp.setHeader("Access-Control-Allow-Origin", "*");
    AccessItem ai = new AccessItem();
    ai.setRequest(brand + " " + model);
    ai.setIp(request.getRemoteHost());//from  ww w  .j  a v a2  s .co  m
    ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
    ai.setService(Product.CAR_MANUAL.getId());

    final String address = request.getLocalAddr();
    final int port = request.getLocalPort();
    String portStr = port == 80 ? "" : ":" + port;
    String prex = "http://" + address + portStr + "/solidtrust/images/";

    Object result = null;
    try {
        List<Manual> list = manualRep.findByBrandAndModel(brand, model);
        if (list.size() > 0) {
            siddur.solidtrust.manual.Car car = new siddur.solidtrust.manual.Car();
            Manual m = list.get(0);
            car.setAcceleration(m.getAcceleration());
            car.setAverageMileage(m.getAverageMileage());
            car.setBrand(m.getBrand());
            car.setBuildFrom(m.getBuildFrom());
            car.setBuildTo(m.getBuildTo());
            car.setImage(prex + m.getImage() + "_1.jpg");
            car.setModel(m.getModel());
            car.setNewPrice(m.getNewPrice());
            car.setRoadTax(m.getRoadTax());
            car.setTireSize(m.getTireSize());
            car.setTopspeed(m.getTopspeed());
            for (Manual manual : list) {
                String[] files = manual.getManual().split(";");
                for (String f : files) {
                    ManualItem mi = new ManualItem();
                    mi.setBuildYear(manual.getBuild());
                    mi.setImage(prex + manual.getImage() + "_1.jpg");
                    mi.setUrl(f);
                    car.getManual().add(mi);
                }
            }
            result = car;
        }
    } catch (Exception e) {
        ai.setStatus(-1);
        log4j.info(e.getMessage(), e);
    }
    if (result == null) {
        result = "no data";
        ai.setStatus(0);
    }
    ai.setResponse(result + "");
    free.save(ai);
    return result;
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//from www .  java 2 s.co m
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as was sent in the
 * given {@link HttpServletRequest}./*from  w  w w. j  av a  2 s  . com*/
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest        The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 */
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

        // Replace more completely if destination server is https :
        if (targetSsl) {
            clientUrl = "http://" + clientUrl;
            serverUrl = "https://" + serverUrl;
        }
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace("POST Content Type: {} Encoding: {} Content: {}",
            new Object[] { contentType, encoding, postContent });
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:com.esd.cs.statistics.ReportController.java

/**
 * /*w  w  w.  j  ava2 s .  c  o m*/
 * 
 * @param type
 * @param year
 * @param request
 * @return
 */
@RequestMapping(value = "/export/{type}/{year}", method = RequestMethod.POST)
@ResponseBody
public String export(@PathVariable(value = "type") String type, @PathVariable(value = "year") String year,
        HttpServletRequest request, HttpSession session) {

    List<ReportViewModel> list = null;
    // ??
    String url = request.getServletContext().getRealPath("/");
    // 
    CommonUtil.chineseFolder(url, uploadPath, companyPath);
    // ??
    String uuid = UUID.randomUUID().toString();
    // ?
    String exportPath = url + uploadPath + File.separator + companyPath + File.separator + uuid + ".xls";

    // ???
    ReportModel model = new ReportModel();
    model.setCreateCompany(createTabCompany);// ?
    model.setCreateData("" + CommonUtil.formatData());// 
    model.setCreatePeople("" + session.getAttribute(Constants.USER_REAL_NAME).toString());// 

    // 
    // ??
    if (StringUtils.equals("nature", type)) {
        list = reportViewService.getByCompanyType(year);
        model.setType("??");// 
        model.setTitle("??");// 
    }
    // 
    if (StringUtils.equals("area", type)) {
        list = reportViewService.getByArea(year);
        model.setType("");// 
        model.setTitle("");// 
    }
    // ?
    if (StringUtils.equals("economytype", type)) {
        list = reportViewService.getByArea(year);
        model.setType("?");// 
        model.setTitle("?");// 
    }

    // ?
    PoiCreateExcel.createRepeaExcel(exportPath, list, model);

    String destPath = request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath();
    // ?
    String loaddown = "http://" + destPath + "/" + uploadPath + "/" + companyPath + "/" + uuid + ".xls";
    return loaddown;
}

From source file:org.sipfoundry.voicemail.MailboxServlet.java

public void doIt(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SipxIvrConfiguration ivrConfig = (SipxIvrConfiguration) request
            .getAttribute(SipxIvrServletHandler.IVR_CONFIG_ATTR);
    ValidUsers validUsers = (ValidUsers) request.getAttribute(SipxIvrServletHandler.VALID_USERS_ATTR);
    Map<String, String> depositMap = (Map<String, String>) request
            .getAttribute(SipxIvrServletHandler.DEPOSIT_MAP_ATTR);
    MailboxManager mailboxManager = (MailboxManager) request
            .getAttribute(SipxIvrServletHandler.MAILBOX_MANAGER);
    Mwi mwiManager = (Mwi) request.getAttribute(SipxIvrServletHandler.MWI_MANAGER);

    String method = request.getMethod().toUpperCase();

    String pathInfo = request.getPathInfo();
    String[] subDirs = pathInfo.split("/");
    if (subDirs.length < 3) {
        response.sendError(404); // path not found
        return;//from w w w .j av a2 s. c o m
    }

    // The first element is empty (the leading slash)
    // The second element is the mailbox
    String mailboxString = subDirs[1];
    // The third element is the "context" (either mwi, message)
    String context = subDirs[2];

    User user = validUsers.getUser(mailboxString);
    // only superadmin and mailbox owner can access this service
    // TODO allow all admin user to access it

    if (user != null && ServletUtil.isForbidden(request, user.getUserName(), request.getLocalPort(),
            ivrConfig.getHttpPort())) {
        response.sendError(403); // Send 403 Forbidden
        return;
    }

    // delete mailbox could come only from a internal port, when user already deleted from
    // mongo
    if (context.equals("delete")) {
        if (ivrConfig.getHttpPort() == request.getLocalPort()) {
            if (method.equals(METHOD_PUT)) {
                try {
                    mailboxManager.deleteMailbox(mailboxString);
                } catch (Exception ex) {
                    response.sendError(500);
                }
            } else {
                response.sendError(405);
            }
        }
    } else {
        if (user != null) {
            PrintWriter pw = response.getWriter();
            LOG.info(String.format("MailboxServlet::doIt %s %s", method, pathInfo));
            // determine the message counts for the mailbox
            // (Okay, worry about this one. It walks the mailstore directories counting .xml
            // and
            // .sta files.)
            if (context.equals("message")) {
                if (subDirs.length >= 5) {
                    String messageId = subDirs[3];
                    String action = subDirs[4];
                    if (action.equals("heard")) {
                        if (method.equals(METHOD_DELETE)) {
                            mailboxManager.markMessageUnheard(user, messageId);
                        } else if (method.equals(METHOD_PUT)) {
                            mailboxManager.markMessageHeard(user, messageId);
                        } else if (method.equals(METHOD_GET)) {
                            try {
                                response.setContentType("text/xml");
                                pw.format("<heard>%s</heard>\n",
                                        mailboxManager.isMessageUnHeard(user, messageId) ? "false" : "true");
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("delete")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                mailboxManager.deleteMessage(user, messageId);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("subject")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                String subject = IOUtils.toString(request.getInputStream());
                                mailboxManager.updateMessageSubject(user, messageId, subject);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                    if (action.equals("move")) {
                        if (method.equals(METHOD_PUT)) {
                            try {
                                String destinationFolder = subDirs[5];
                                mailboxManager.moveMessageToFolder(user, messageId, destinationFolder);
                                MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                                mwiManager.sendMWI(user, mailbox);
                            } catch (MessageNotFoundException ex) {
                                response.sendError(404, "messageId not found");
                            }
                        }
                    }

                } else {
                    response.sendError(400, "messageId missing");
                }
            } else if (context.equals("mwi")) {
                if (method.equals(METHOD_PUT)) {
                    MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                    mwiManager.sendMWI(user, mailbox);
                } else if (method.equals(METHOD_GET)) {
                    response.setContentType(Mwi.MessageSummaryContentType);
                    String accountUrl = "sip:" + user.getIdentity();
                    MailboxDetails mailbox = mailboxManager.getMailboxDetails(user.getUserName());
                    pw.write(Mwi.formatRFC3842(mailbox, accountUrl));
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("uuid")) {
                response.setContentType("text/xml");
                String uuid = depositMap.get(user.getUserName());
                if (uuid == null) {
                    pw.write("<uuid></uuid>\n");
                } else {
                    pw.format("<uuid>%s</uuid>\n", uuid);
                }

            } else if (context.equals("rename")) {
                if (subDirs.length >= 4) {
                    String oldMailbox = subDirs[3];
                    if (method.equals(METHOD_PUT)) {
                        try {
                            mailboxManager.renameMailbox(user, oldMailbox);
                        } catch (Exception ex) {
                            response.sendError(500);
                        }
                    } else {
                        response.sendError(405);
                    }
                } else {
                    response.sendError(400, "destination missing");
                }

            } else if (context.equals("messages")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    List<VmMessage> inboxMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.INBOX);
                    List<VmMessage> savedMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.SAVED);
                    List<VmMessage> deletedMessages = mailboxManager.getMessages(user.getUserName(),
                            Folder.DELETED);
                    listMessages(inboxMessages, "inbox", pw);
                    listMessages(savedMessages, "saved", pw);
                    listMessages(deletedMessages, "deleted", pw);
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("inbox")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.INBOX,
                                    messageId, false), "inbox", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.INBOX), "inbox",
                                pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("saved")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.SAVED,
                                    messageId, false), "saved", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.SAVED), "saved",
                                pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("deleted")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.DELETED,
                                    messageId, false), "deleted", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.DELETED),
                                "deleted", pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else if (context.equals("conference")) {
                if (method.equals(METHOD_GET)) {
                    response.setContentType("text/xml");
                    pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
                    pw.write("<messages>\n");
                    if (subDirs.length >= 4) {
                        String messageId = subDirs[3];
                        try {
                            listFullMessage(mailboxManager.getVmMessage(user.getUserName(), Folder.CONFERENCE,
                                    messageId, false), "conference", pw);
                        } catch (MessageNotFoundException ex) {
                            response.sendError(404, "messageId not found");
                        }
                    } else {
                        listFullMessages(mailboxManager.getMessages(user.getUserName(), Folder.CONFERENCE),
                                "conference", pw);
                    }
                    pw.write("</messages>");
                } else {
                    response.sendError(405);
                }
            } else {
                response.sendError(400, "context not understood");
            }
            pw.close();
        } else {
            response.sendError(404, "Mailbox not found");
            LOG.info(String.format("MailboxServlet::doIt %s not found", mailboxString));
        }
    }

}

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

private void testGeneralAccess(javax.servlet.http.HttpServletRequest request)
        throws HttpErrorException, AdminLoginNeededException {

    Boolean updated = (Boolean) database.getAttribute(WGDatabase.ATTRIB_UPDATED);
    if (updated != null) {
        if (updated.booleanValue() == true) {
            throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "This application is currently being updated. Please try again later.", getDatabaseKey());
        }//from  w  w w .  j  a v  a2 s  .c  o m
    }

    boolean allowPublishing = database.getBooleanAttribute(WGACore.DBATTRIB_ALLOW_PUBLISHING, true);
    if (!allowPublishing) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                "The application '" + database.getDbReference() + "' is not published", null);
    }

    boolean authoringApp = database.getBooleanAttribute(WGACore.DBATTRIB_AUTHORING_APP, false);
    if (authoringApp && !core.isAuthoringPort(request.getLocalPort())) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                "Access to authoring applications is disabled", null);
    }

    boolean adminApp = database.getBooleanAttribute(WGACore.DBATTRIB_ADMIN_APP, false);
    if (adminApp) {
        if (!core.isAdministrativePort(request.getLocalPort())) {
            throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                    "Access to administrative applications is disabled", null);
        }

        if (!core.isAdminLoggedIn(request)) {
            throw new AdminLoginNeededException();
        }
    }

    if (this.pathType != TYPE_CSS && this.pathType != TYPE_JS && this.pathType != TYPE_FILE) {
        if (!database.getSessionContext().getUserAccess().mayAccessDirectly()) {
            throw new IllegalDirectAccessException(database.getDbReference());
        }
    }

}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generatePrintableMetadataHTMLFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();// w ww . j a v a 2 s .  c o m
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            System.out.println("oaiId: " + oaiId);

            String urlMetadataHtml = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=meta";
            statusCode = WAMCPStorage.myGetHttp(urlMetadataHtml);
            System.out.println(urlMetadataHtml + " ==> status code: " + statusCode);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generatePortletHTMLFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*w ww . j  a  v a 2 s  .  c o m*/
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            System.out.println("oaiId: " + oaiId);
            String url = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=html";
            statusCode = WAMCPStorage.myGetHttp(url);
            System.out.println(url + " ==> status code: " + statusCode);

            //            System.out.println(oaiId+" {Html}: "+statusCode);
            String urlDivOpt = host + "BAG-API/rest/desc/" + oaiId + "/transform?divOpt=true&type=html";
            statusCode = WAMCPStorage.myGetHttp(urlDivOpt);
            //            System.out.println(oaiId+" {Html, div}: "+statusCode);
            System.out.println(urlDivOpt + " ==> status code: " + statusCode);

            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, true);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, false);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}