Example usage for javax.servlet.http HttpServletRequest getServerName

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

Introduction

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

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

From source file:com.mockey.model.RequestFromClient.java

/**
 * 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...//  w ww .  j  av a  2  s  .com
 * */

private void parseCookies(HttpServletRequest rawRequest) {
    javax.servlet.http.Cookie[] cookies = rawRequest.getCookies();
    if (cookies != null) {
        // ******************
        // This doesn't seem right.
        // We have to map javax Cookies to httpclient Cookies?!?!
        // 
        // ******************
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = rawRequest.getServerName();
            }
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = rawRequest.getContextPath();
            }
            BasicClientCookie basicClientCookie = new BasicClientCookie(c.getName(), c.getValue());
            basicClientCookie.setDomain(domain);
            if (c.getMaxAge() > -1) {
                int seconds = c.getMaxAge();
                long currentTime = System.currentTimeMillis();
                Date expiryDate = new Date(currentTime + (seconds * 1000));
                basicClientCookie.setExpiryDate(expiryDate);
            }
            this.httpClientCookies.add(basicClientCookie);
        }
    }

}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarCreateNewAccountHtml.java

protected void sendConfirmationEMail(HttpServletRequest request, ICFAstSecUserObj confirmUser,
        ICFAstClusterObj cluster) throws IOException, MessagingException, NamingException {
    final String S_ProcName = "sendConfirmationEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID confirmationUUID = confirmUser.getOptionalEMailConfirmationUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a new account for login " + confirmUser.getRequiredLoginId() + " with "
            + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to confirm your email address:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">"
            + baseURI + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString()
            + "</A>\n" + "<p>" + "Or click on the following link to cancel the request for a new account:<br>\n"
            + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID="
            + confirmationUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    CFAstSMWarUtil warUtil = new CFAstSMWarUtil();
    warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody);
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

private static String generateURL(HttpServletRequest request, HttpServletResponse response, String Servlet) {
    HttpSession session = request.getSession();
    String publicURL = WebConfiguration.getPublicURL();
    String dataURL = null;//from w ww  . j  a  va  2  s .  c  o m
    if (publicURL != null) {
        dataURL = publicURL + Servlet + ";jsessionid=" + session.getId();
    } else {
        if ((request.getScheme().equals("http") && request.getServerPort() == 80)
                || (request.getScheme().equals("https") && request.getServerPort() == 443)) {
            dataURL = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + Servlet
                    + ";jsessionid=" + session.getId();
        } else {
            dataURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath() + Servlet + ";jsessionid=" + session.getId();
        }
    }
    logger.debug("Generated URL: " + dataURL);
    return dataURL;
}

From source file:de.thm.arsnova.controller.LoginController.java

@RequestMapping(value = { "/auth/dialog" }, method = RequestMethod.GET)
@ResponseBody//  w  ww.  j  ava 2  s .c  om
public View dialog(@RequestParam("type") final String type,
        @RequestParam(value = "successurl", defaultValue = "/") String successUrl,
        @RequestParam(value = "failureurl", defaultValue = "/") String failureUrl,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    View result = null;

    /* Use URLs from a request parameters for redirection as long as the
     * URL is not absolute (to prevent abuse of the redirection). */
    if (UrlUtils.isAbsoluteUrl(successUrl)) {
        successUrl = "/";
    }
    if (UrlUtils.isAbsoluteUrl(failureUrl)) {
        failureUrl = "/";
    }

    String serverUrl = request.getScheme() + "://" + request.getServerName();
    /* Handle proxy
     * TODO: It might be better, to support the proposed standard: http://tools.ietf.org/html/rfc7239 */
    int port = "".equals(request.getHeader("X-Forwarded-Port"))
            ? Integer.valueOf(request.getHeader("X-Forwarded-Port"))
            : request.getServerPort();
    if ("https".equals(request.getScheme())) {
        if (443 != port) {
            serverUrl = serverUrl + ":" + String.valueOf(port);
        }
    } else {
        if (80 != port) {
            serverUrl = serverUrl + ":" + String.valueOf(port);
        }
    }

    request.getSession().setAttribute("ars-login-success-url", serverUrl + successUrl);
    request.getSession().setAttribute("ars-login-failure-url", serverUrl + failureUrl);

    if ("cas".equals(type)) {
        casEntryPoint.commence(request, response, null);
    } else if ("twitter".equals(type)) {
        final String authUrl = twitterProvider.getAuthorizationUrl(new HttpUserSession(request));
        result = new RedirectView(authUrl);
    } else if ("facebook".equals(type)) {
        facebookProvider.setFields("id,link");
        facebookProvider.setScope("");
        final String authUrl = facebookProvider.getAuthorizationUrl(new HttpUserSession(request));
        result = new RedirectView(authUrl);
    } else if ("google".equals(type)) {
        final String authUrl = googleProvider.getAuthorizationUrl(new HttpUserSession(request));
        result = new RedirectView(authUrl);
    }

    return result;
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

@SuppressWarnings("unchecked")
public ReturnResponse handleReturnResponse(HttpSession httpSession, String userId,
        Map<String, Attribute> attributes, SecretKey secretKey, PublicKey publicKey, String rpTargetUrl,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    LOG.debug("handleReturnResponse");
    ServerManager serverManager = getServerManager(request);
    RealmVerifier realmVerifier = serverManager.getRealmVerifier();
    ParameterList parameterList = retrieveParameterList(httpSession);
    AuthRequest authRequest = AuthRequest.createAuthRequest(parameterList, realmVerifier);

    String location = "https://" + request.getServerName();
    if (request.getServerPort() != 443) {
        location += ":" + request.getServerPort();
    }//from   w ww.j  ava2 s  .com
    location += "/eid-idp/endpoints/" + getPath();

    String userIdentifier = location + "?" + userId;
    LOG.debug("user identifier: " + userIdentifier);
    UrlIdentifier urlIdentifier = new UrlIdentifier(userIdentifier);
    userIdentifier = urlIdentifier.getIdentifier();
    LOG.debug("normalized user identifier: " + userIdentifier);

    Message message = serverManager.authResponse(parameterList, userIdentifier, userIdentifier, true, false);

    if (message instanceof AuthSuccess) {
        AuthSuccess authSuccess = (AuthSuccess) message;

        // Attribute Exchange Extension
        if (authRequest.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authRequest.getExtension(AxMessage.OPENID_NS_AX);

            if (messageExtension instanceof FetchRequest) {
                FetchRequest fetchRequest = (FetchRequest) messageExtension;

                Map<String, String> requiredAttributes = fetchRequest.getAttributes(true);
                Map<String, String> optionalAttributes = fetchRequest.getAttributes(false);

                FetchResponse fetchResponse = FetchResponse.createFetchResponse();

                // required attributes
                for (Map.Entry<String, String> requiredAttribute : requiredAttributes.entrySet()) {
                    String alias = requiredAttribute.getKey();
                    String typeUri = requiredAttribute.getValue();

                    LOG.debug("required attribute alias: " + alias);
                    LOG.debug("required attribute typeUri: " + typeUri);

                    String value = findAttribute(typeUri, attributes);
                    if (null != value) {
                        fetchResponse.addAttribute(alias, typeUri, value);
                    }
                }

                // optional attributes
                for (Map.Entry<String, String> optionalAttribute : optionalAttributes.entrySet()) {
                    String alias = optionalAttribute.getKey();
                    String typeUri = optionalAttribute.getValue();

                    LOG.debug("optional attribute alias: " + alias);
                    LOG.debug("optional attribute typeUri: " + typeUri);

                    String value = findAttribute(typeUri, attributes);
                    if (null != value) {
                        fetchResponse.addAttribute(alias, typeUri, value);
                    }
                }

                authSuccess.addExtension(fetchResponse, "ax");
                authSuccess.setSignExtensions(new String[] { AxMessage.OPENID_NS_AX });
            }
        }

        // PaPe extension
        PapeResponse papeResponse = PapeResponse.createPapeResponse();
        papeResponse.setAuthTime(new Date());

        switch (getAuthenticationFlow()) {

        case IDENTIFICATION:
            papeResponse.setAuthPolicies(PapeResponse.PAPE_POLICY_PHISHING_RESISTANT);
            break;
        case AUTHENTICATION:
            papeResponse.setAuthPolicies(PapeResponse.PAPE_POLICY_MULTI_FACTOR_PHYSICAL);
            break;
        case AUTHENTICATION_WITH_IDENTIFICATION:
            papeResponse.addAuthPolicy(PapeResponse.PAPE_POLICY_PHISHING_RESISTANT);
            papeResponse.addAuthPolicy(PapeResponse.PAPE_POLICY_MULTI_FACTOR_PHYSICAL);
            break;
        }

        authSuccess.addExtension(papeResponse, "pape");
        /*
         * We manually sign the auth response as we also want to add our own
         * attributes.
         */
        serverManager.sign(authSuccess);
    }

    String destinationUrl = rpTargetUrl;
    if (null == destinationUrl) {
        destinationUrl = authRequest.getReturnTo();
    }
    LOG.debug("destination URL: " + destinationUrl);
    Map<String, String> parameters = message.getParameterMap();
    ReturnResponse returnResponse = new ReturnResponse(destinationUrl);
    for (String paramKey : parameters.keySet()) {
        String paramValue = parameters.get(paramKey);
        returnResponse.addAttribute(paramKey, paramValue);
    }
    return returnResponse;
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadTemplates(HttpServletRequest request) throws ServletException {

    if (templateLodaded) {
        return;// www  . j  av  a2s. co m
    }

    templateLodadedStarted = true;

    try {
        for (TemplateBean template : TemplateConfig.templates) {
            if (template.path.startsWith(";")) {
                template.path = template.path.substring(1);
            }

            boolean firstCharIsUnecessarySeparator = template.path.startsWith("/")
                    || template.path.startsWith("\\");
            template.path = (firstCharIsUnecessarySeparator) ? template.path.substring(1) : template.path;

            loadHTMLInfo(template, request.getServerName(), request.getServerPort(),
                    request.getProtocol().contains("HTTPS"), request);

        }
    } catch (Exception e) {
        templateLodaded = false;
        templateLodadedStarted = false;

        throw new ServletException("Exception:" + e.getMessage(), e);
    }

    templateLodaded = true;
}

From source file:csiro.pidsvc.mappingstore.action.ActionProxy.java

@Override
public void run() {
    HttpClient httpClient = new DefaultHttpClient();
    try {//from w  w  w.  j a va 2 s.  c  om
        HttpServletRequest originalHttpRequest = _controller.getRequest();
        HttpServletResponse originalHttpResponse = _controller.getResponse();
        HttpGet httpGet = new HttpGet(getExpandedActionValue());

        if (isTraceMode())
            trace(httpGet.getRequestLine().toString());

        // Pass-through HTTP headers.
        HashMap<String, String> hmHeaders = _controller.getHttpHeaders();
        for (String header : hmHeaders.keySet()) {
            httpGet.addHeader(header, hmHeaders.get(header));
            if (isTraceMode())
                trace("\t" + header + ": " + hmHeaders.get(header));
        }

        // Handle X-Original-URI HTTP header.
        if (!hmHeaders.containsKey("X-Original-URI")) {
            String originalUri = originalHttpRequest.getScheme() + "://" + originalHttpRequest.getServerName();
            if (originalHttpRequest.getServerPort() != 80)
                originalUri += ":" + originalHttpRequest.getServerPort();
            originalUri += _controller.getUri().getOriginalUriAsString();

            httpGet.addHeader("X-Original-URI", originalUri);
            if (isTraceMode())
                trace("\tX-Original-URI: " + originalUri);
        }

        // Get the data.
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (isTraceMode())
            trace(response.getStatusLine().toString());

        // Pass HTTP headers through.
        if (!isTraceMode())
            originalHttpResponse.setStatus(response.getStatusLine().getStatusCode());
        if (entity.getContentType() != null) {
            if (isTraceMode()) {
                trace("\tContent-Type: " + entity.getContentType().getValue());
                trace("\tContent-Length: " + EntityUtils.toString(entity).getBytes().length);
            } else
                originalHttpResponse.setContentType(entity.getContentType().getValue());
        }

        String headerName;
        for (Header header : response.getAllHeaders()) {
            headerName = header.getName();
            if (headerName.equalsIgnoreCase("Expires") || headerName.equalsIgnoreCase("Cache-Control")
                    || headerName.equalsIgnoreCase("Content-Type") || headerName.equalsIgnoreCase("Set-Cookie")
                    || headerName.equalsIgnoreCase("Transfer-Encoding"))
                continue;
            if (isTraceMode())
                trace("\t" + header.getName() + ": " + header.getValue());
            else
                originalHttpResponse.addHeader(header.getName(), header.getValue());
        }

        // Pass content through.
        if (!isTraceMode())
            originalHttpResponse.getWriter().write(EntityUtils.toString(entity));
    } catch (Exception e) {
        _logger.trace("Exception occurred while proxying HTTP request.", e);
        if (isTraceMode()) {
            Throwable cause = e.getCause();
            trace("Set response status: 500; exception: "
                    + (cause == null ? e.getMessage() : cause.getMessage()));
        } else
            Http.returnErrorCode(_controller.getResponse(), 500, e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.aimluck.eip.modules.actions.ALSessionValidator.java

/**
 *
 * @param data//from w w  w .  j av a 2 s.c o  m
 * @throws Exception
 */
@Override
public void doPerform(RunData data) throws Exception {

    try {
        super.doPerform(data);
    } catch (Throwable other) {
        setOrgParametersForError(data);
        data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR));
        return;
    }

    // not login and can not connect database
    if (checkDbError(data)) {
        setOrgParametersForError(data);
        data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE);
        return;
    }

    // ?
    // Cookie?ID????????
    if (data.getRequest().isRequestedSessionIdFromURL()) {
        JetspeedLink jsLink = JetspeedLinkFactory.getInstance(data);
        String url = jsLink.getHomePage().toString().replaceAll(";.*", "");
        data.setRedirectURI(url);
        return;
    }

    JetspeedUser loginuser = (JetspeedUser) data.getUser();

    if (isLogin(loginuser)) {
        try {
            JetspeedSecurityCache.load(loginuser.getUserName());
        } catch (Exception e1) {
            // login and can not connect database
            String message = e1.getMessage();
            if (message != null && message.indexOf(ALConstants.DB_ERROR_DETECT) != -1) {
                setOrgParametersForError(data);
                String template = data.getParameters().get("template");
                if (template.endsWith("DBError")) {
                    data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE);
                } else {
                    ALEipUtils.redirectDBError(data);
                }
                return;
            }
        }
    }

    if (ALSessionUtils.isImageRequest(data)) {
        if (isLogin(loginuser)) {
            return;
        }
    }

    if (ALSessionUtils.isJsonScreen(data)) {
        if (isLogin(loginuser)) {
            return;
        }
    }

    if (data.getRequest().getAttribute(ALDigestAuthenticationFilter.REQUIRE_DIGEST_AUTH) != null) {
        HttpServletRequest hreq = data.getRequest();
        HttpServletResponse hres = data.getResponse();
        if (!isLogin(loginuser)) {
            String auth = hreq.getHeader("Authorization");

            if (auth == null) {
                requireAuth(hres);
                return;

            } else {
                try {
                    String decoded = decodeAuthHeader(auth);

                    int pos = decoded.indexOf(":");
                    String username = decoded.substring(0, pos);
                    String password = decoded.substring(pos + 1);

                    JetspeedUser juser = JetspeedSecurity.login(username, password);
                    if (juser != null && "F".equals(juser.getDisabled())) {
                        JetspeedSecurity.saveUser(juser);
                    } else {
                        requireAuth(hres);
                        return;
                    }

                } catch (RuntimeException ex) {
                    // RuntimeException
                    requireAuth(hres);
                    return;
                } catch (Exception ex) {
                    requireAuth(hres);
                    return;

                }
            }
        }

        if (isICalRequest(data)) {
            data.setScreenTemplate("ScheduleiCalScreen");
            return;
        } else {
            hres.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    Context context = org.apache.turbine.services.velocity.TurbineVelocity.getContext(data);
    // for switching theme org by org
    setOrgParameters(data, context);
    // for preventing XSS on user name
    context.put("utils", new ALCommonUtils());

    context.put("l10n", ALLocalizationUtils.createLocalization(data));

    // Cookie?????????
    if (!isLogin(loginuser) && !data.getParameters().get("template").equals("CookieError")) {
        String username = data.getParameters().getString("username", "");
        String password = data.getParameters().getString("password", "");
        if (username.length() > 0) {

            if (ALCellularUtils.isSmartPhone(data) && "admin".equals(username)) {
                data.setUser(JetspeedSecurity.getAnonymousUser());
                data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_LOGIN_ONLY_PC"));
                data.getUser().setHasLoggedIn(Boolean.FALSE);
            } else {

                try {
                    loginuser = JetspeedSecurity.login(username, password);
                    if (loginuser != null && "F".equals(loginuser.getDisabled())) {
                        JetspeedSecurity.saveUser(loginuser);
                    } else {
                        data.setUser(JetspeedSecurity.getAnonymousUser());
                        data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_INVALIDATION_USER"));
                        data.getUser().setHasLoggedIn(Boolean.FALSE);
                    }
                } catch (LoginException e) {
                }
            }
        }
    }

    String externalLoginUrl = ALConfigService.get(Property.EXTERNAL_LOGIN_URL);

    boolean isScreenTimeout = false;
    if (!isLogin(loginuser) && JetspeedResources.getBoolean("automatic.logon.enable", false)) {

        if (data.getRequest().getCookies() != null) {
            String userName = data.getCookies().getString("username", "");
            String loginCookieValue = data.getCookies().getString("logincookie", "");

            if (userName.length() > 0 && loginCookieValue.length() > 0) {
                try {
                    loginuser = JetspeedSecurity.getUser(userName);
                    if (loginuser.getPerm("logincookie", "").equals(loginCookieValue)) {
                        data.setUser(loginuser);
                        loginuser.setHasLoggedIn(Boolean.TRUE);
                        loginuser.updateLastLogin();
                        data.save();
                    }
                } catch (LoginException noSuchUser) {
                } catch (org.apache.jetspeed.services.security.UnknownUserException unknownUser) {
                    logger.warn("Username from the cookie was not found: " + userName);
                } catch (Exception other) {
                    logger.error("ALSessionValidator.doPerform", other);
                }
            }
        }

    } else if (!isLogin(loginuser) && !JetspeedResources.getBoolean("automatic.logon.enable", false)) {

        // ? ?????????
        // ???????????
        String uri = data.getRequest().getRequestURI().trim();

        String template = data.getScreenTemplate();

        Class<?> cls = null;
        try {
            cls = Class.forName(
                    new StringBuffer().append("com.aimluck.eip.modules.screens.").append(template).toString());
        } catch (Exception e) {
            cls = null;
        }
        String newTemplate = null;
        if (cls != null) {
            if (Class.forName("com.aimluck.eip.modules.screens.ALJSONScreen").isAssignableFrom(cls)) {
                newTemplate = "ALJSONTimeoutScreen";
            } else if (Class.forName("com.aimluck.eip.modules.screens.ALVelocityScreen")
                    .isAssignableFrom(cls)) {
                newTemplate = "ALVelocityTimeoutScreen";
            }
        }
        if (newTemplate != null) {
            isScreenTimeout = true;
            data.setScreenTemplate(newTemplate);
            // ?
            if (data.getSession() != null) {
                try {
                    data.getSession().invalidate();
                } catch (IllegalStateException ex) {
                    logger.debug("???????");
                }
            }

        } else {
            String contextPath = ServletContextLocator.get().getContextPath();
            if ("/".equals(contextPath)) {
                contextPath = "";
            }
            String portalPath = contextPath + "/portal";
            if (!uri.equals(portalPath + "/") && !uri.equals(portalPath)) {
                data.setScreenTemplate("Timeout");

                if (!"".equals(externalLoginUrl)) {
                    // ??
                    data.setRedirectURI(externalLoginUrl);
                }

                StringBuffer sb = new StringBuffer(uri);
                int count = 0;
                String key = null;
                Enumeration<?> enu = data.getRequest().getParameterNames();
                if (enu.hasMoreElements()) {
                    sb.append("?");
                }
                while (enu.hasMoreElements()) {
                    if (count != 0) {
                        sb.append("&");
                    }
                    key = (String) enu.nextElement();
                    sb.append(key).append("=").append(data.getRequest().getParameter(key));
                    count = count + 1;
                }

                if (data.getUser() != null) {
                    data.getUser().setTemp("redirect", StringEscapeUtils.escapeHtml(sb.toString()));
                    context.put("alEipUtils", new ALEipUtils());
                    context.put("alEipManager", ALEipManager.getInstance());
                }

                // ?
                if (data.getSession() != null) {
                    try {
                        data.getSession().invalidate();
                    } catch (IllegalStateException ex) {
                        logger.debug("???????");
                    }
                }
            }
        }
    }

    JetspeedRunData jdata = null;
    try {
        jdata = (JetspeedRunData) data;
    } catch (ClassCastException e) {
        logger.error("The RunData object does not implement the expected interface, "
                + "please verify the RunData factory settings", e);
        return;
    }
    String language = data.getRequest().getParameter("js_language");

    if (null != language) {
        loginuser.setPerm("language", language);
    }

    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    Locale locale = locService.getLocale(data);

    if (locale == null) {
        locale = new Locale(TurbineResources.getString("locale.default.language", "en"),
                TurbineResources.getString("locale.default.country", "US"));
    }

    if (loginuser != null) {
        loginuser.setTemp("locale", locale);
    }

    String paramPortlet = jdata.getParameters().getString("js_peid");
    if (paramPortlet != null && paramPortlet.length() > 0) {
        jdata.setJs_peid(paramPortlet);
    }

    // Ajax????????
    if (!isScreenTimeout && !"".equals(externalLoginUrl)) {
        HttpServletRequest request = data.getRequest();
        if (!isLogin(loginuser)) {
            StringBuilder buf = new StringBuilder();
            buf.append(request.getScheme()).append("://").append(request.getServerName());
            if (request.getServerPort() == 80 || request.getServerPort() == 443) {
                //
            } else {
                buf.append(":").append(request.getServerPort());
            }

            buf.append(request.getRequestURI());
            String queryString = request.getQueryString();
            if (queryString != null && !"".equals(queryString)) {
                buf.append("?").append(queryString);
            }
            String url = buf.toString();
            if (!url.equals(externalLoginUrl)) {
                data.setRedirectURI(externalLoginUrl);
            }
        }
    }

    if (isLogin(loginuser)) {

        ALPreExecuteService.migratePsml(data, context);

        boolean hasMessage = false;
        Map<String, Entry> portlets = ALEipUtils.getGlobalPortlets(data);
        Entry entry = portlets.get("Message");
        if (entry != null) {
            if (entry.getId().equals(jdata.getJs_peid())) {
                hasMessage = true;
            }
        }
        String client = ALEipUtils.getClient(data);

        boolean push = (!"IPHONE".equals(client)) || hasMessage;

        HttpServletRequest request = ((JetspeedRunData) data).getRequest();
        String requestUrl = request.getRequestURL().toString();

        String checkActivityUrl = ALConfigService.get(Property.CHECK_ACTIVITY_URL);
        String interval = ALConfigService.get(Property.CHECK_ACTIVITY_INTERVAL);

        ALEipUser eipUser = ALEipUtils.getALEipUser(data);
        String orgId = Database.getDomainName();
        String viewer = new StringBuilder(orgId).append(":").append(eipUser.getName().getValue()).toString();

        ALGadgetContext gadgetContext = new ALGadgetContext(data, viewer, "1", "/", 0);

        String relayUrl = ALConfigService.get(Property.CHECK_ACTIVITY_RELAY_URL);
        String rpctoken = String.valueOf(System.nanoTime());
        String checkUrl = new StringBuilder("".equals(checkActivityUrl) ? "check.html" : checkActivityUrl)
                .append("?").append("st=").append(gadgetContext.getSecureToken()).append("&parent=")
                .append(URLEncoder.encode(requestUrl, "utf-8")).append("&interval=").append(interval)
                .append("&push=").append(push ? 1 : 0).append("#rpctoken=").append(rpctoken).toString();
        if (data.getSession() != null
                && Boolean.parseBoolean((String) data.getSession().getAttribute("changeToPc"))) { // PC?
            context.put("client", ALEipUtils.getClient(data));

        }

        context.put("requestUrl", requestUrl);
        context.put("relayUrl", relayUrl);
        context.put("rpctoken", rpctoken);
        context.put("checkUrl", checkUrl);
        context.put("st", gadgetContext.getSecureToken());
        context.put("hasAuthorityCustomize",
                ALEipUtils.getHasAuthority(data, context, ALAccessControlConstants.VALUE_ACL_UPDATE));
    }
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.web.rest.AccountResource.java

/**
 * POST  /register -> register the user.
 *//*ww  w.j av a 2  s .  c o m*/
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {
    return userRepository.findOneByLogin(userDTO.getLogin())
            .map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
                                userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
                                userDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort(); // "80"

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:com.imagelake.uploads.Servlet_Upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Date d = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
    String date = sm.format(d);/*from   w w  w .j  ava2s.  co m*/

    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    UserDAOImp udi = new UserDAOImp();
    // gets values of text fields
    PrintWriter out = response.getWriter();

    String cat, imgtit, imgname, dominate, price, dimention, col1, col2, col3, col4, col5, col6, col7, col8,
            col9, size_string, uid;
    System.out.println("server name====" + request.getServerName());

    uid = request.getParameter("uid");
    imgname = request.getParameter("imgname");
    imgtit = request.getParameter("tit");
    cat = request.getParameter("cat");
    dimention = request.getParameter("dimention");
    dominate = request.getParameter("dominate");
    col1 = request.getParameter("col-1");
    col2 = request.getParameter("col-2");
    col3 = request.getParameter("col-3");
    col4 = request.getParameter("col-4");
    col5 = request.getParameter("col-5");
    col6 = request.getParameter("col-6");
    col7 = request.getParameter("col-7");
    col8 = request.getParameter("col-8");
    col9 = request.getParameter("col-9");
    size_string = request.getParameter("size");
    long size = 0;

    System.out.println(cat + " " + imgname + " " + col1 + " " + col2 + " " + col3 + " " + col4 + " " + col5
            + " " + col6 + " " + col7 + " " + col8 + " " + col9 + " //" + dominate + " " + size_string);
    System.out.println(request.getParameter("tit") + "bbbbb" + request.getParameter("cat"));
    InputStream inputStream = null; // input stream of the upload file

    System.out.println("woooooooooo" + imgtit.trim() + "hooooooooo");

    if (imgtit.equals("") || imgtit.equals(null) || cat.equals("") || cat.equals(null) || cat.equals("0")
            || dimention.equals("") || dimention.equals(null) && dominate.equals("")
            || dominate.equals(null) && col1.equals("") || col1.equals(null) && col2.equals("")
            || col2.equals(null) && col3.equals("") || col3.equals(null) && col4.equals("")
            || col4.equals(null) && col5.equals("") && col5.equals(null) && col6.equals("")
            || col6.equals(null) && col7.equals("") || col7.equals(null) && col8.equals("")
            || col8.equals(null) && col9.equals("") || col9.equals(null)) {
        System.out.println("error");

        out.write("error");
    } else {

        // obtains the upload file part in this multipart request 
        try {
            Part filePart = request.getPart("photo");

            if (filePart != null) {
                // prints out some information for debugging
                System.out.println("NAME:" + filePart.getName());
                System.out.println(filePart.getSize());
                size = filePart.getSize();
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
                System.out.println(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Connection conn = null; // connection to the database
        String message = null; // message will be sent back to client
        String fileName = null;
        try {

            // gets absolute path of the web application
            String applicationPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
            System.out.println("Upload File Directory2=" + fileSaveDir.getAbsolutePath() + "/" + imgname);

            //Get all the parts from request and write it to the file on server
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                if (!fileName.equals(null) || !fileName.equals("")) {
                    try {
                        part.write(uploadFilePath + File.separator + fileName);
                    } catch (Exception e) {
                        break;
                    }
                }

            }

            //GlassFish File Upload

            System.out.println(inputStream);

            if (inputStream != null) {

                // int id=new ImagesDAOImp().checkImagesId(dominate, col1, col2, col3, col4, col5, col6, col7, col8, col9);
                //   if(id==0){
                boolean sliceImage = new CreateImages().sliceImages(col1, col2, col3, col4, col5, col6, col7,
                        col8, col9, dominate, imgname, dimention, imgtit, cat, uid, date);
                if (sliceImage) {
                    AdminNotification a = new AdminNotification();
                    a.setUser_id(Integer.parseInt(uid));
                    a.setDate(timeStamp);

                    a.setShow(1);
                    a.setType(1);
                    String not = "New Image has uploaded by " + udi.getUn(Integer.parseInt(uid));
                    a.setNotification(not);

                    int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);

                    boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.listAdminsIDs(), an,
                            1);
                    if (kl) {
                        out.write("ok");
                    } else {
                        System.out.println("error in sliceimage");
                        out.write("error");
                    }
                } else {
                    System.out.println("error in sliceimage");
                    out.write("error");
                }
                // }
                /*else{
                              System.out.println("error in id");
                        out.write("error");
                    }*/

            }

            // sends the statement to the database server

        } catch (Exception ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

        }

    }

    //out.write("ok");
    //else code          

}