Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

From source file:org.apache.jsp.communities_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
          HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);
      String result = "";
      try {//from  w w  w. ja v  a  2  s  .c  o  m
          URLConnection connection = new URL(API_ROOT + addr).openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              connection.setDoInput(true);
          }
          connection.setDoOutput(true);
          connection.setRequestProperty("Accept-Charset", "UTF-8");

          // Post JSON string to URL
          OutputStream os = connection.getOutputStream();
          byte[] b = data.getBytes("UTF-8");
          os.write(b);

          // Receive results back from API
          InputStream is = connection.getInputStream();
          result = IOUtils.toString(is, "UTF-8");

          String newCookie = getConnectionInfiniteCookie(connection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
      } catch (Exception e) {
          //System.out.println("Exception: " + e.getMessage());
      }
      return result;
  }

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

public static String getPublisherURL(javax.servlet.http.HttpServletRequest request, boolean absolute) {

    if (absolute) {
        String protocol = request.getProtocol().substring(0, request.getProtocol().indexOf("/")).toLowerCase();
        if (protocol.equals("http") && request.isSecure()) {
            protocol = "https";
        }//w w  w .  ja v  a  2s .  c o m

        int port = request.getServerPort();
        if (port != -1) {
            if (protocol.equals("http") && port == 80) {
                port = -1;
            } else if (protocol.equals("https") && port == 443) {
                port = -1;
            }
        }

        return protocol + "://" + request.getServerName() + (port != -1 ? ":" + port : "")
                + request.getContextPath();
    } else {
        return request.getContextPath();
    }

}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//*from ww w . j ava2s .co m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    httpMethodProxyRequest.setFollowRedirects(false);
    String port = "" + httpServletRequest.getSession().getAttribute("civserverport");
    String host = "" + httpServletRequest.getSession().getAttribute("civserverhost");
    String username = "" + httpServletRequest.getSession().getAttribute("username");
    httpMethodProxyRequest.addRequestHeader("civserverport", port);
    httpMethodProxyRequest.addRequestHeader("civserverhost", host);
    httpMethodProxyRequest.addRequestHeader("username", username);
    int intProxyResponseCode = 0;
    // Execute the request
    try {
        intProxyResponseCode = client.executeMethod(httpMethodProxyRequest);
    } catch (IOException ioErr) {
        //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. 
        //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        httpServletResponse.setStatus(502);
        outputStreamClientResponse
                .write("Freeciv web client proxy not responding (most likely died).".getBytes());
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            httpMethodProxyRequest.releaseConnection();
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
        httpMethodProxyRequest.releaseConnection();
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
    int intNextByte;
    while ((intNextByte = bufferedInputStream.read()) != -1) {
        outputStreamClientResponse.write(intNextByte);
    }
    httpMethodProxyRequest.releaseConnection();
}

From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java

/**
 * Perform the login action via API calls.
 *
 * @param request/*from  w  w w .  j  a  va2 s . c  om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void login(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    String responseType = request.getParameter(RESPONSE_TYPE);
    if (responseType == null) {
        responseType = RESPONSE_TYPE_TOKEN;
    }
    String customerId = request.getParameter(CUSTOMER_ID);

    // create a POST method to execute the login request
    HttpPost post;
    List<NameValuePair> values = new ArrayList<NameValuePair>();
    if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_TOKEN);
    } else {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_CODE);
    }
    if (StringUtils.isNotBlank(customerId)) {
        values.add(new BasicNameValuePair(CUSTOMER_ID, customerId));
    }
    if (request.getParameter(CLIENT_ID) != null) {
        values.add(new BasicNameValuePair(CLIENT_ID, request.getParameter(CLIENT_ID)));
    }

    // get login and pwd either from the request or from the session
    HttpSession session = request.getSession(false);
    String login = request.getParameter(LOGIN);
    if ((session != null) && (login == null)) {
        login = (String) session.getAttribute(LOGIN);
        session.setAttribute(LOGIN, null);
    }
    String password = request.getParameter(PASSWORD);
    if ((session != null) && (password == null)) {
        password = (String) session.getAttribute(PASSWORD);
        session.setAttribute(PASSWORD, null);
    }

    boolean isSso = false;
    String redirectUri = null;
    if (request.getParameter(REDIRECT_URI) != null) {
        redirectUri = request.getParameter(REDIRECT_URI).trim();
        values.add(new BasicNameValuePair(REDIRECT_URI, redirectUri));
        isSso = isSso(request, redirectUri);
    }

    if (isSso == false && ((login == null) || (password == null))) {
        showLogin(request, response);
    } else {
        if (isSso == false) {
            values.add(new BasicNameValuePair(LOGIN, login));
            values.add(new BasicNameValuePair(PASSWORD, password));
        } else {
            String uri = request.getScheme() + "://" + request.getServerName()
                    + ("http".equals(request.getScheme()) && request.getServerPort() == 80
                            || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? ""
                                    : ":" + request.getServerPort());
            post = new HttpPost(uri + V4_RS_SSO_TOKEN);
            if (values != null) {
                URL url = new URL(redirectUri);
                values = getQueryPairs(getRedirectParameters(url.getQuery()));
            }
        }
        post.setEntity(new UrlEncodedFormEntity(values));
        try {
            String redirectUrl = redirectUri;
            // T489 remove any trailing #
            if (redirectUrl.endsWith("#")) {
                redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1);
            }
            if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
                // token type
                // execute the login request
                AccessToken token = RequestHelper.processRequest(AccessToken.class, request, post);
                String tokenId = token.getId().getTokenId();
                // redirect URL
                if (redirectUrl.contains(ACCESS_TOKEN_PARAM_PATTERN)) {
                    // replace access_token parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, ACCESS_TOKEN_PARAM_PATTERN, tokenId);
                } else {
                    // append access_token anchor
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += ACCESS_TOKEN + "=" + tokenId;
                }
            } else {
                // auth code type
                // execute the login request
                AuthCode codeObj = RequestHelper.processRequest(AuthCode.class, request, post);
                String code = codeObj.getCode();
                if (redirectUrl.contains(AUTH_CODE_PARAM_PATTERN)) {
                    // replace code parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, AUTH_CODE_PARAM_PATTERN, code);
                } else {
                    // append code param
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += AUTH_CODE + "=" + code;
                }
            }
            response.sendRedirect(redirectUrl);
        } catch (ServerUnavailableException e1) {
            // Authentication server unavailable
            logger.error(e1.getLocalizedMessage());
            request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE);
            showLogin(request, response);
            return;
        } catch (ServiceException e2) {
            WebServicesException exception = e2.getWsException();
            if (exception != null) {
                if (exception.getCustomers() != null) {
                    // multiple customers found
                    request.setAttribute(DUPLICATE_USER_ERROR, Boolean.TRUE);
                    request.setAttribute(CUSTOMERS_LIST, exception.getCustomers());
                    // save the credentials for later use
                    request.getSession().setAttribute(LOGIN, login);
                    request.getSession().setAttribute(PASSWORD, password);
                } else {
                    String errorMessage = exception.getError();
                    if (!errorMessage.contains("Password")) {
                        request.setAttribute(ERROR, exception.getError());
                    } else {
                        request.setAttribute(ERROR, Boolean.TRUE);
                    }
                }
            } else {
                request.setAttribute(ERROR, Boolean.TRUE);
            }
            // forward to login page
            showLogin(request, response);
            return;
        } catch (SSORedirectException error) {
            response.sendRedirect(error.getRedirectURL());
        }

    }
}

From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java

/**
  * Builds the model to pass to the rendering engine.
  *///from  w w  w .  j  av  a  2s  .c om
protected Map<QName, Object> buildModel(final FormInstanceData formInstanceData, final Rendition rendition)
        throws IOException, SAXException {
    final String formInstanceDataAvmPath = formInstanceData.getPath();
    final String renditionAvmPath = rendition.getPath();
    final String parentPath = AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[0];
    final String sandboxUrl = AVMUtil.getPreviewURI(AVMUtil.getStoreName(formInstanceDataAvmPath));
    final String webappUrl = AVMUtil.buildWebappUrl(formInstanceDataAvmPath);
    final HashMap<QName, Object> model = new HashMap<QName, Object>();
    // add simple scalar parameters
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "date", namespacePrefixResolver), new Date());
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "avm_sandbox_url", namespacePrefixResolver),
            sandboxUrl);
    model.put(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER,
            new RenderingEngine.TemplateResourceResolver() {
                public InputStream resolve(final String name) {
                    final NodeService nodeService = RenderingEngineTemplateImpl.this.getServiceRegistry()
                            .getNodeService();
                    final NodeRef parentNodeRef = nodeService
                            .getPrimaryParent(RenderingEngineTemplateImpl.this.getNodeRef()).getParentRef();

                    if (logger.isDebugEnabled()) {
                        logger.debug("request to resolve resource " + name + " webapp url is " + webappUrl
                                + " and data dictionary workspace is " + parentNodeRef);
                    }

                    final NodeRef result = nodeService.getChildByName(parentNodeRef,
                            ContentModel.ASSOC_CONTAINS, name);
                    if (result != null) {
                        final ContentService contentService = RenderingEngineTemplateImpl.this
                                .getServiceRegistry().getContentService();
                        try {
                            if (logger.isDebugEnabled()) {
                                logger.debug("found " + name + " in data dictonary: " + result);
                            }

                            return contentService.getReader(result, ContentModel.PROP_CONTENT)
                                    .getContentInputStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    if (name.startsWith(WEBSCRIPT_PREFIX)) {
                        try {
                            final FacesContext facesContext = FacesContext.getCurrentInstance();
                            final ExternalContext externalContext = facesContext.getExternalContext();
                            final HttpServletRequest request = (HttpServletRequest) externalContext
                                    .getRequest();

                            String decodedName = URLDecoder.decode(name.substring(WEBSCRIPT_PREFIX.length()));
                            String rewrittenName = decodedName;

                            if (decodedName.contains("${storeid}")) {
                                rewrittenName = rewrittenName.replace("${storeid}",
                                        AVMUtil.getStoreName(formInstanceDataAvmPath));
                            } else {
                                if (decodedName.contains("{storeid}")) {
                                    rewrittenName = rewrittenName.replace("{storeid}",
                                            AVMUtil.getStoreName(formInstanceDataAvmPath));
                                }
                            }

                            if (decodedName.contains("${ticket}")) {
                                AuthenticationService authenticationService = Repository
                                        .getServiceRegistry(facesContext).getAuthenticationService();
                                final String ticket = authenticationService.getCurrentTicket();
                                rewrittenName = rewrittenName.replace("${ticket}", ticket);
                            } else {
                                if (decodedName.contains("{ticket}")) {
                                    AuthenticationService authenticationService = Repository
                                            .getServiceRegistry(facesContext).getAuthenticationService();
                                    final String ticket = authenticationService.getCurrentTicket();
                                    rewrittenName = rewrittenName.replace("{ticket}", ticket);
                                }
                            }

                            final String webscriptURI = (request.getScheme() + "://" + request.getServerName()
                                    + ':' + request.getServerPort() + request.getContextPath() + "/wcservice/"
                                    + rewrittenName);

                            if (logger.isDebugEnabled()) {
                                logger.debug("loading webscript: " + webscriptURI);
                            }

                            final URI uri = new URI(webscriptURI);
                            return uri.toURL().openStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    try {
                        final String[] path = (name.startsWith("/") ? name.substring(1) : name).split("/");
                        for (int i = 0; i < path.length; i++) {
                            path[i] = URLEncoder.encode(path[i]);
                        }

                        final URI uri = new URI(webappUrl + '/' + StringUtils.join(path, '/'));

                        if (logger.isDebugEnabled()) {
                            logger.debug("loading " + uri);
                        }

                        return uri.toURL().openStream();
                    } catch (Exception e) {
                        logger.warn(e);
                        return null;
                    }
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "form_instance_data_file_name",
            namespacePrefixResolver), AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[1]);
    model.put(
            QName.createQName(NamespaceService.ALFRESCO_PREFIX, "rendition_file_name", namespacePrefixResolver),
            AVMNodeConverter.SplitBase(renditionAvmPath)[1]);
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver),
            parentPath);
    final FacesContext fc = FacesContext.getCurrentInstance();
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "request_context_path",
            namespacePrefixResolver), fc.getExternalContext().getRequestContextPath());

    // add methods
    final FormDataFunctions fdf = this.getFormDataFunctions();

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to encodeQuotes.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String text = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath);
                    }

                    final String result = fdf.encodeQuotes(text);
                    return result;
                }
            });

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to parseXMLDocument.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String path = (String) arguments[0];
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocument('" + path + "'), parentPath = " + parentPath);
                    }

                    final Document d = fdf.parseXMLDocument(path);
                    return d != null ? d.getDocumentElement() : null;
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length > 2) {
                        throw new IllegalArgumentException("expected exactly one or two arguments to "
                                + "parseXMLDocuments.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    if (arguments.length == 2 && !(arguments[1] instanceof String)) {
                        throw new ClassCastException("expected arguments[1] to be a " + String.class.getName()
                                + ".  got a " + arguments[1].getClass().getName() + ".");
                    }

                    String path = arguments.length == 2 ? (String) arguments[1] : "";
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                    final String formName = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocuments('" + formName + "','" + path + "'), parentPath = "
                                + parentPath);
                    }

                    final Map<String, Document> resultMap = fdf.parseXMLDocuments(formName, path);

                    if (logger.isDebugEnabled()) {
                        logger.debug("received " + resultMap.size() + " documents in " + path
                                + " with form name " + formName);
                    }

                    // create a root document for rooting all the results.  we do this
                    // so that each document root element has a common parent node
                    // and so that xpath axes work properly
                    final Document rootNodeDocument = XMLUtil.newDocument();
                    final Element rootNodeDocumentEl = rootNodeDocument.createElementNS(
                            NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list");
                    rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                            NamespaceService.ALFRESCO_URI);
                    rootNodeDocument.appendChild(rootNodeDocumentEl);

                    final List<Node> result = new ArrayList<Node>(resultMap.size());
                    for (Map.Entry<String, Document> e : resultMap.entrySet()) {
                        final Element documentEl = e.getValue().getDocumentElement();
                        documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                                NamespaceService.ALFRESCO_URI);
                        documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI,
                                NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey());
                        final Node n = rootNodeDocument.importNode(documentEl, true);
                        rootNodeDocumentEl.appendChild(n);
                        result.add(n);
                    }
                    return result.toArray(new Node[result.size()]);
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "_getAVMPath", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected one argument to _getAVMPath.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    final String path = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_getAVMPAth('" + path + "'), parentPath = " + parentPath);
                    }

                    return AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                }
            });

    // add the xml document
    model.put(RenderingEngine.ROOT_NAMESPACE, formInstanceData.getDocument());
    return model;
}

From source file:org.apache.jsp.sources_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
           HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);
       String result = "";
       try {//from   ww  w.j  a  v a  2 s  .  c o m
           URLConnection connection = new URL(API_ROOT + addr).openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               connection.setDoInput(true);
           }
           connection.setDoOutput(true);
           connection.setRequestProperty("Accept-Charset", "UTF-8");

           // Post JSON string to URL
           OutputStream os = connection.getOutputStream();
           byte[] b = data.getBytes("UTF-8");
           os.write(b);

           // Receive results back from API
           InputStream is = connection.getInputStream();
           result = IOUtils.toString(is, "UTF-8");

           String newCookie = getConnectionInfiniteCookie(connection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
       } catch (Exception e) {
           //System.out.println("Exception: " + e.getMessage());
       }
       return result;
   }

From source file:eg.agrimarket.controller.ProductController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from ww  w .  jav  a  2  s .  co  m
        PrintWriter out = response.getWriter();
        eg.agrimarket.model.pojo.Product product = new eg.agrimarket.model.pojo.Product();
        Product productJPA = new Product();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    product.setImage(image);
                    productJPA.setImage(image);
                }
            } else {
                switch (item.getFieldName()) {
                case "name":
                    product.setName(item.getString());
                    productJPA.setName(item.getString());
                    System.out.println("name" + item.getString());
                    break;
                case "price":
                    product.setPrice(Float.valueOf(item.getString()));
                    productJPA.setPrice(Float.valueOf(item.getString()));
                    break;
                case "quantity":
                    product.setQuantity(Integer.valueOf(item.getString()));
                    productJPA.setQuantity(Integer.valueOf(item.getString()));
                    break;
                case "desc":
                    product.setDesc(item.getString());
                    productJPA.setDesc(item.getString());
                    System.out.println("desc: " + item.getString());
                    break;
                default:
                    Category category = new Category();
                    category.setId(Integer.valueOf(item.getString()));
                    product.setCategoryId(category);
                    productJPA.setCategoryId(category.getId());
                }
            }
        }

        ProductDao daoImp = new ProductDaoImp();
        boolean check = daoImp.addProduct(product);
        if (check) {
            List<Product> products = (List<Product>) request.getServletContext().getAttribute("products");
            if (products != null) {
                products.add(productJPA);
                request.getServletContext().setAttribute("products", products);

            }
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?success=Successfully#header3-41");
        } else {
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?status=Exist!#header3-41");
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(ProductController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*  www.  ja v a  2s . c  o  m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/SendEmailInviteFriend", method = RequestMethod.POST)
public String SendEmailInviteFriend(HttpServletRequest request, HttpSession session) {
    try {//from www. jav  a2 s  . c  om
        AccountSession account = (AccountSession) session.getAttribute("account");
        int providerID = account.getId();
        String contextPath = request.getContextPath();
        String baseUrl;
        if (contextPath != null || contextPath.isEmpty() || !contextPath.equals("")) {
            baseUrl = String.format("%s://%s:%d" + contextPath, request.getScheme(), request.getServerName(),
                    request.getServerPort());
        } else {
            baseUrl = String.format("%s://%s:%d", request.getScheme(), request.getServerName(),
                    request.getServerPort());
        }
        providerService.sendMail(request, account.getName(), providerID, baseUrl);
        request.setAttribute("emailSent", "Email Sent!");
        return "forward:/Provider/InviteFriend";
    } catch (Exception e) {
        String content = "Function: ProviderController - send email invite friend\n" + "****Error****\n"
                + e.getMessage() + "\n" + "**********";
        return "forward:/Common/Error";
    }
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/SendEmailReferral", method = RequestMethod.POST)
public @ResponseBody String SendEmailReferral(@RequestBody final String data, HttpServletRequest request,
        HttpSession session) {//  w w w .j  a  v  a 2  s  . co m
    try {
        AccountSession account = (AccountSession) session.getAttribute("account");
        int providerID = account.getId();
        String contextPath = request.getContextPath();
        String baseUrl;
        if (contextPath != null || contextPath.isEmpty() || !contextPath.equals("")) {
            baseUrl = String.format("%s://%s:%d" + contextPath, request.getScheme(), request.getServerName(),
                    request.getServerPort());
        } else {
            baseUrl = String.format("%s://%s:%d", request.getScheme(), request.getServerName(),
                    request.getServerPort());
        }
        providerService.sendEmailReferral(data, providerID, baseUrl);
        request.setAttribute("emailSent", "Email Sent!");
        return "{\"result\": \"success\"}";
    } catch (Exception e) {
        String content = "Function: ProviderController - send email invite friend\n" + "****Error****\n"
                + e.getMessage() + "\n" + "**********";
        return "forward:/Common/Error";
    }
}