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:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generateMARCFiles(ActionEvent ev) {

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

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from w w w  .jav  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;
        String XMLFilePath;
        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            XMLFilePath = URLPathStrUtils.appendParts(dirUrlStr, childStr);

            //File XMLfile = new File(XMLFilePath);
            //   FileObject imageFO;

            //   imageFO = VFS.getManager().resolveFile(XMLFilePath);

            File XMLfile = null;
            try {
                XMLfile = File.createTempFile(FileUtils.makeSafeFileName(childStr), "msDescReleased");

                BAGStorage.readRemoteFile(XMLFilePath, new FileOutputStream(XMLfile));
            } catch (IOException e1) {
                this.handleException(e1);
            }

            //   URL url = new URL(XMLFilePath);
            //   InputStream is = url.openStream();

            try {
                WAMCPStorage.generateMARCFile(XMLfile, childStr, this.galleryBean.getGalleryRootUrlStr());
            } catch (WAMCPGeneralCorrectableException e) {
                // TODO Auto-generated catch block
                this.handleException(e);
            } catch (IOException e) {
                this.handleException(e);
            }

            //            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) {
        this.handleException(e);
    }
}

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

public void generateImagePdfFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");
    //      System.out.println("dirUrlStr: "+dirUrlStr);

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from   ww  w . j av a  2 s .c om
    String uri = request.getRequestURL().toString();
    //        System.out.println("uri: "+uri);
    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() + "/";

    //        System.out.println("Host: "+host);

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        //         String rootUrlStr = this.galleryBean.getGalleryRootUrlStr();
        //         String tempUserName = this.wamcpSessionBBean.getUserName();
        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 urlImagesPdf = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=img";
            statusCode = WAMCPStorage.myGetHttp(urlImagesPdf);
            System.out.println(urlImagesPdf + " ==> 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();
    }
}

From source file:com.esd.ps.RegListController.java

/**
 * ??//from w ww. ja  va 2s.  com
 * 
 * @param idArr
 * @param request
 * @return
 */
@RequestMapping(value = "/export", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> export(String beginDate, String endDate, HttpServletRequest request,
        HttpSession session) {
    Map<String, Object> map = new HashMap<>();
    boolean b = true;
    String FileDownloadPath = "null";
    int districtId = Integer.parseInt(session.getAttribute(Constants.ID).toString());
    SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
    SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_HAVE_LINE);
    try {
        // 
        String url = request.getSession().getServletContext().getRealPath("/");
        // 
        File downloadPath = new File(url + Constants.EXCELTEMP);
        if (!(downloadPath.exists())) {
            downloadPath.mkdir();
        }
        // ??File.separator
        // String uuid = UUID.randomUUID().toString();
        String pinyin = session.getAttribute(Constants.PINYIN).toString();
        String exportPath = null, fileName = null;

        if (beginDate.isEmpty() || beginDate == null || beginDate.trim().length() == 0) {
            fileName = pinyin + "_" + sdf.format(new Date());
        } else {
            fileName = sdf.format(sdf.parse(beginDate)) + "-" + sdf.format(sdf.parse(endDate)) + "_" + pinyin
                    + "_" + sdf.format(new Date());
            Date myDate = formatter.parse(endDate);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.DATE, 1);
            myDate = c.getTime();
            endDate = sdf.format(myDate);
        }
        exportPath = downloadPath + File.separator + fileName + ".xls";
        List<Registration> list = registrationService.getAllByTimeAndDistrictId(districtId, beginDate, endDate);
        // 
        b = PoiCreateExcel.createRegistrationExcel(exportPath, list);
        if (b) {
            String destPath = request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath();
            FileDownloadPath = "http://" + destPath + "/" + Constants.EXCELTEMP + "/" + fileName + ".xls";
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    map.clear();
    map.put(Constants.WRONGPATH, FileDownloadPath);
    return map;
}

From source file:org.apache.hadoop.gateway.service.test.ServiceTestResource.java

private String buildXForwardBaseURL(HttpServletRequest req) {
    final String X_Forwarded = "X-Forwarded-";
    final String X_Forwarded_Context = X_Forwarded + "Context";
    final String X_Forwarded_Proto = X_Forwarded + "Proto";
    final String X_Forwarded_Host = X_Forwarded + "Host";
    final String X_Forwarded_Port = X_Forwarded + "Port";
    final String X_Forwarded_Server = X_Forwarded + "Server";

    String baseURL = "";

    //    Get Protocol
    if (req.getHeader(X_Forwarded_Proto) != null) {
        baseURL += req.getHeader(X_Forwarded_Proto) + "://";
    } else {/*from w w  w.j a v  a 2  s. c  o  m*/
        baseURL += req.getProtocol() + "://";
    }

    //    Handle Server/Host and Port Here
    if (req.getHeader(X_Forwarded_Host) != null && req.getHeader(X_Forwarded_Port) != null) {
        //        Double check to see if host has port
        if (req.getHeader(X_Forwarded_Host).contains(req.getHeader(X_Forwarded_Port))) {
            baseURL += req.getHeader(X_Forwarded_Host);
        } else {
            //        If there's no port, add the host and port together;
            baseURL += req.getHeader(X_Forwarded_Host) + ":" + req.getHeader(X_Forwarded_Port);
        }
    } else if (req.getHeader(X_Forwarded_Server) != null && req.getHeader(X_Forwarded_Port) != null) {
        //      Tack on the server and port if they're available. Try host if server not available
        baseURL += req.getHeader(X_Forwarded_Server) + ":" + req.getHeader(X_Forwarded_Port);
    } else if (req.getHeader(X_Forwarded_Port) != null) {
        //      if we at least have a port, we can use it.
        baseURL += req.getServerName() + ":" + req.getHeader(X_Forwarded_Port);
    } else {
        //      Resort to request members
        baseURL += req.getServerName() + ":" + req.getLocalPort();
    }

    //    Handle Server context
    if (req.getHeader(X_Forwarded_Context) != null) {
        baseURL += req.getHeader(X_Forwarded_Context);
    } else {
        baseURL += req.getContextPath();
    }

    return baseURL;
}

From source file:org.apache.nifi.web.api.DataTransferResource.java

private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
        final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {/*from   w w w .ja  va  2s  . c o  m*/
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream,
            outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}

From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java

/**
 * Handles the service page showing information about a specific service, like all its methods.
 *
 * @param html    The HTMLWriter to write to.
 * @param service The service to show information about.
 * @param req     The HTTPServletRequest.
 * @throws IOException/*from   ww  w. j av  a  2  s . c  om*/
 */
private void handleServicePage(HTMLWriter html, String service, HttpServletRequest req) throws IOException {
    Set<String> methodNames = this.externalProtocolService.getAvailableServiceFunctionNames(service);

    html.tag("html");
    {
        html.tag("body", "", BG_COLOR);
        {
            html.tagc("h1",
                    "ApplicationPlatformServices (APS) Remote service call over HTTP transport provider");
            html.tagc("p",
                    "Here the service and all its methods are displayed. Each method is clickable for details on the method.");

            html.tagc("h2", "Service");
            if (!methodNames.isEmpty()) {
                html.tagc("h3", service + " {");
                html.tag("ul");
                for (String method : methodNames) {
                    APSExternallyCallable<Object> callable = this.externalProtocolService.getCallable(service,
                            method);

                    //                        String params = "";
                    //                        String comma = "";
                    //                        for (DataTypeDescription parameter : callable.getParameterDataDescriptions()) {
                    //                            params = params + comma + toTypeName(parameter);
                    //                            comma = ", ";
                    //                        }

                    html.tagc("h4", toMethodDecl(callable, service, method));
                }
                html.tage("ul");
                html.tagc("h3", "}");

                html.tagc("h2", "Protocol URLs");
                html.tagc("p",
                        "Please note that even though these urls include the service, not all protocols require the service in "
                                + "the URL!");

                for (StreamedRPCProtocol protocol : this.externalProtocolService.getAllStreamedProtocols()) {
                    html.tagc("h3",
                            protocol.getServiceProtocolName() + " : " + protocol.getServiceProtocolVersion());

                    html.tagc("p",
                            "http://" + req.getLocalName() + ":" + req.getLocalPort() + "/apsrpc/"
                                    + protocol.getServiceProtocolName() + "/"
                                    + protocol.getServiceProtocolVersion() + "/" + service + "/");
                }

            } else {
                html.tagc("h2", "Service '" + service + "' not found!");
            }
        }
        html.tage("body");
    }
    html.tage("html");
}

From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest req = context.getHreq();
    HttpServletResponse res = context.getHres();

    String requestURI = getRequestURI(req);
    String qs = req.getQueryString();
    if (qs != null) {
        requestURI = new StringBuffer(requestURI).append("?").append(qs).toString();
    }/*w w w .j  a  v a 2 s .c  o  m*/

    URL url = null;
    try {
        url = new URL("http", uri.getHost(), uri.getPort(), requestURI);
        if (_log.isTraceEnabled())
            _log.trace("proxying to: " + url);
    } catch (MalformedURLException e) {
        if (_log.isWarnEnabled())
            _log.warn("bad proxy url: " + url, e);
        throw new IrrecoverableException("bad proxy url", e);
    }

    long startTime = System.currentTimeMillis();

    HttpURLConnection huc = null;
    String m = req.getMethod();
    try {
        huc = (HttpURLConnection) url.openConnection(); // IOException
        huc.setRequestMethod(m); // ProtocolException
    } catch (ProtocolException e) {
        if (_log.isWarnEnabled())
            _log.warn("unsupported http method: " + m, e);
        throw new IrrecoverableException("unsupported HTTP method: " + m, e);
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy IO problem", e);
        throw new RecoverableException("could not open proxy connection", e);
    }

    huc.setAllowUserInteraction(false);
    huc.setInstanceFollowRedirects(false);

    // check connection header
    // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers - inefficient, but we are constrained by servlet API
    {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String hdr = (String) e.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ?
                continue;
            // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option
            if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header...
                continue; // strip this out - we may be being spoofed

            for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) {
                String val = (String) f.nextElement();
                if (val != null) {
                    huc.addRequestProperty(hdr, val);
                }
            }
        }
    }

    // content ?
    boolean hasContent = false;
    {
        int contentLength = 0;
        String tmp = huc.getRequestProperty("Content-Length");
        if (tmp != null) {
            try {
                contentLength = Integer.parseInt(tmp);
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }

        if (contentLength > 0)
            hasContent = true;
        else
            hasContent = (huc.getRequestProperty("Content-Type") != null);
    }

    // proxy
    {
        huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ?
        huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain...
        // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ?
    }

    // cache-control
    {
        String cacheControl = huc.getRequestProperty("Cache-Control");
        if (cacheControl != null
                && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0))
            huc.setUseCaches(false);
    }

    // confidentiality
    {
        if (req.isSecure()) {
            huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString());
        }

        // at the other end, if this header is present we must :

        // wrap the request so that req.isSecure()=true, before processing...
        // mask the header - so it is never seen by the app.

        // the code for the other end should live in this class.

        // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member...
    }
    // customize Connection
    huc.setDoInput(true);

    // client->server
    int client2ServerTotal = 0;
    {
        if (hasContent) {
            huc.setDoOutput(true);

            OutputStream toServer = null;
            try {
                InputStream fromClient = req.getInputStream(); // IOException
                toServer = huc.getOutputStream(); // IOException
                client2ServerTotal = copy(fromClient, toServer, 8192);
            } catch (IOException e) {
                new IrrecoverableException("problem proxying client request to server", e);
            } finally {
                if (toServer != null) {
                    try {
                        toServer.close(); // IOException
                    } catch (IOException e) {
                        _log.warn("problem closing server request stream", e);
                    }
                }
            }
        }
    }

    // Connect
    try {
        huc.connect(); // IOException
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy connection problem: " + url, e);
        throw new RecoverableException("could not connect to proxy target", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 0;
    if (huc == null) {
        try {
            fromServer = huc.getInputStream(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring client output", e);
        }
    } else {
        code = 502;
        //         String message="Bad Gateway: could not read server response code or message";
        try {
            code = huc.getResponseCode(); // IOException
            //            message=huc.getResponseMessage(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring http server response code/message", e);
        } finally {
            //            res.setStatus(code, message); - deprecated
            res.setStatus(code);
        }

        if (code < 400) {
            // 1XX:continue, 2XX:successful, 3XX:multiple-choices...
            try {
                fromServer = huc.getInputStream(); // IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem acquiring http client output", e);
            }
        } else {
            // 4XX:client, 5XX:server error...
            fromServer = huc.getErrorStream(); // why does this not throw IOException ?
            // TODO - do we need to use sendError()?
        }
    }

    // clear response defaults.
    res.setHeader("Date", null);
    res.setHeader("Server", null);

    // set response headers
    if (false) {
        int h = 0;
        String hdr = huc.getHeaderFieldKey(h);
        String val = huc.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = (hdr != null) ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                res.addHeader(hdr, val);

            // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val);

            h++;
            hdr = huc.getHeaderFieldKey(h);
            val = huc.getHeaderField(h);
        }
    } else {
        // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
        // Try this inside Tomcat...
        String key;
        for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) {
            key = key.toLowerCase();
            String val = huc.getHeaderField(i);
            if (val != null && !_DontProxyHeaders.contains(key)) {
                res.addHeader(key, val);
            }
        }
    }

    // do we need another Via header in the response...

    // server->client
    int server2ClientTotal = 0;
    {
        if (fromServer != null) {
            try {
                OutputStream toClient = res.getOutputStream();// IOException
                server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem proxying server response back to client", e);
            } finally {
                try {
                    fromServer.close();
                } catch (IOException e) {
                    // well - we did our best...
                    _log.warn("problem closing server response stream", e);
                }
            }
        }
    }

    huc.disconnect();

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled())
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", url:" + url);
}

From source file:com.nec.harvest.controller.SuihController.java

/**
 * Render page with path variables mapping
 * /{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}
 * //from  w  ww.  ja va2 s  . com
 * @param userOrgCode
 *            Logged-in user's code
 * @param businessDay
 *            Actual business day
 * @param proGNo
 *            A path variable user's group code
 * @param unitLevel
 *            A path variable classify's code
 * @param unitDept
 *            A path variable department level2's code
 * @param deptCode
 *            A path variable department selected on page view
 * @param year
 *            A path variable year
 * @param quarter
 *            A path variable quarter
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo,
        @PathVariable String unitLevel, @PathVariable String unitDept, @PathVariable String deptCode,
        @PathVariable String year, @PathVariable String quarter, final HttpServletRequest request,
        final Model model) {
    logger.info(
            "Loading profit and loss manager in a quarter data by full path [/suih/{unitLevel}/{unitDept}/{deptCode}/{year}/{quarter}]");

    Date currentYear = null;
    int currentQuarter = 0;

    // cast year, quarter
    try {
        currentYear = DateFormatUtil.parse(year, DateFormat.DATE_YEAR);
        currentQuarter = Integer.parseInt(quarter);
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    try {
        /* Get classify list */
        List<Division> divisions;
        try {
            divisions = divisionService.findByKbnId(DEFAULT_KBN_ID);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // Set divisions is empty
            divisions = Collections.emptyList();
        }

        // set list classifies first drop down list
        final String CLASSIFIES = "classifies";
        model.addAttribute(CLASSIFIES, divisions);

        // set value selected first drop down list
        final String UNIT_LEVEL = "unitLevel";
        model.addAttribute(UNIT_LEVEL, selectedClassify(divisions, unitLevel));

        List<Organization> departments = null;
        try {
            // Get the list of organizations level 2
            departments = organizationService.findByKaisoBango(unitLevel);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());
        }

        // set attribute list departments for drop down list level2
        final String DEPARTMENTS = "departments";
        model.addAttribute(DEPARTMENTS, departments);

        // set attribute name selected for drop down list level2
        final String UNIT_DEPT = "unitDeptName";
        model.addAttribute(UNIT_DEPT, selectedDepartment(departments, unitDept));

        final String UNIT_DEPT_CODE = "unitDeptCode";
        model.addAttribute(UNIT_DEPT_CODE, unitDept);

        // set attribute department code
        final String DEPT_CODE = "deptCode";
        boolean isTotalCalculation = unitDept.equals(deptCode);
        model.addAttribute(DEPT_CODE, isTotalCalculation ? unitDept : deptCode);

        // set attribute current quarter of business
        final String CURRENT_QUARTER = "currentQuarter";
        model.addAttribute(CURRENT_QUARTER, year.concat("/").concat(quarter));

        InputStreamReader in = null;
        try {
            UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                    request.getContextPath() + Constants.PAGINATION_PATH + "/{unitDept}/{deptCode}/{pageindex}")
                    .build();
            URI uri = uriComponents.expand(proGNo, unitDept, deptCode, 0).encode().toUri();

            // initial HttpHost, HttpGet
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpHost httpHost = new HttpHost(request.getServerName(), request.getLocalPort(),
                    request.getScheme());
            HttpGet httpGet = new HttpGet(uri.toString());
            HttpResponse httpResp = httpClient.execute(httpHost, httpGet);
            if (httpResp.getStatusLine().getStatusCode() != 200) {
                // Release the connection
                httpClient.close();
                httpClient = null;

                // call rest paging error
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResp.getStatusLine().getStatusCode());
            }

            // read pagination 
            in = new InputStreamReader(httpResp.getEntity().getContent(),
                    HttpServletContentType.DEFAULT_ENCODING);
            BufferedReader rd = new BufferedReader(in);
            StringBuilder textView = new StringBuilder();

            String line = "";
            while ((line = rd.readLine()) != null) {
                textView.append(line);
            }

            // set attribute pagination
            final String HTML_PAGINATION = "pagination";
            model.addAttribute(HTML_PAGINATION, textView);

            // Release the connection
            httpClient.close();
            httpClient = null;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    logger.warn(ex.getMessage());
                }
            }
        }
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR, true);
        model.addAttribute(ERROR_MESSAGE, getSystemError());
    }

    // 
    return processingSuih(userOrgCode, businessDay, unitDept, deptCode, currentYear, currentQuarter, model);
}

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

private void doLogin(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response)
        throws HttpErrorException, IOException, MalformedURLException, ServletException, WGException {

    // Get the necessary fields
    String domain = request.getParameter("domain");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String redirect = request.getParameter("redirect");
    String referer = request.getHeader("Referer");

    // Some basic validating
    if (domain == null) {
        throw new HttpErrorException(500, "Missing parameter \"domain\". (Hint: Field name must be lower case)",
                null);/*w w w  .  j av  a2s  . co m*/
    }
    if (username == null) {
        throw new HttpErrorException(500,
                "Missing parameter \"username\". (Hint: Field name must be lower case)", null);
    }
    if (password == null) {
        throw new HttpErrorException(500,
                "Missing parameter \"password\". (Hint: Field name must be lower case)", null);
    }
    if (username == null || password == null) {
        request.setAttribute(WGACore.ATTRIB_LOGINERROR,
                "Invalid login for domain " + domain + ". Username or password is null.");
        username = "Anonymous";
        password = "";
    }

    boolean isLoginSuccessful = false;
    try {
        if (WGACore.DOMAIN_ADMINLOGINS.equals(domain)) {
            if (!_core.isAdministrativePort(request.getLocalPort())) {
                throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                        "Access to administrative applications is disabled", null);
            }

            isLoginSuccessful = _core.doAdminLogin(username, password, request);
        } else {
            isLoginSuccessful = _core.login(username, password, domain, request, response);
        }
    } catch (LoginException e) {
        throw new ServletException("Login Error", e);
    }

    // React on login success
    if (isLoginSuccessful) {

        if (redirect != null) {
            sendRedirect(request, response, redirect);
        } else if (referer != null) {
            request.setAttribute(WGACore.ATTRIB_LOGINERROR, "No redirect specified.");
            de.innovationgate.utils.URLBuilder builder = new de.innovationgate.utils.URLBuilder(
                    new java.net.URL(referer));
            builder.setParameter("loginerror", "2");
            sendRedirect(request, response, builder.build(false));
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    } else {

        if (WGACore.DOMAIN_ADMINLOGINS.equals(domain)) {
            request.setAttribute(WGACore.ATTRIB_LOGINERROR,
                    "Invalid administrative login. Please verify username and password.");
        } else {
            request.setAttribute(WGACore.ATTRIB_LOGINERROR,
                    "Invalid login for domain " + domain + ". Please verify username and password.");
        }

        if (request.getParameter("flag") != null) {
            response.setContentType("text/html");
            request.getRequestDispatcher("login.jsp").include(request, response);
        } else if (referer != null) {
            de.innovationgate.utils.URLBuilder builder = new de.innovationgate.utils.URLBuilder(
                    new java.net.URL(referer));
            builder.setParameter("loginerror", "1");
            sendRedirect(request, response, builder.build(false).toString());
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid login");
        }
    }
    return;
}

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();/* w  w  w .j  a v a2  s. c o  m*/
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}