Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

In this page you can find the example usage for java.security PrivilegedAction PrivilegedAction.

Prototype

PrivilegedAction

Source Link

Usage

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Marshal objects by type/*from  w  w  w.j av a2  s .  c o  m*/
 * 
 * @param b Object that can be rendered as an element, but the element name is not known to the
 * schema (i.e. rpc)
 * @param m Marshaller
 * @param writer XMLStreamWriter
 * @param type Class
 * @param isList true if this is an XmlList
 * @param ctype CONSTRUCTION_TYPE
 * @param optimize boolean set to true if optimization directly to 
 * outputstream should be attempted.
 */
private void marshalByType(final Object b, final Marshaller m, final XMLStreamWriter writer, final Class type,
        final boolean isList, final JAXBUtils.CONSTRUCTION_TYPE ctype, final boolean optimize)
        throws WebServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Enter marshalByType b=" + getDebugName(b) + " type=" + type + " marshaller=" + m + " writer="
                + writer + " isList=" + isList + " ctype=" + ctype + " optimize=" + optimize);

    }
    if (isOccurrenceArray(b)) {
        marshalOccurrenceArray((JAXBElement) b, m, writer);
        return;
    }
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                // NOTE
                // Example:
                // <xsd:simpleType name="LongList">
                // <xsd:list>
                // <xsd:simpleType>
                // <xsd:restriction base="xsd:unsignedInt"/>
                // </xsd:simpleType>
                // </xsd:list>
                // </xsd:simpleType>
                // <element name="myLong" nillable="true" type="impl:LongList"/>
                //
                // LongList will be represented as an int[]
                // On the wire myLong will be represented as a list of integers
                // with intervening whitespace
                // <myLong>1 2 3</myLong>
                //
                // Unfortunately, we are trying to marshal by type. Therefore
                // we want to marshal an element (foo) that is unknown to schema.
                // If we use the normal marshal code, the wire will look like
                // this (which is incorrect):
                // <foo><item>1</item><item>2</item><item>3</item></foo>
                //
                // The solution is to detect this situation and marshal the
                // String instead. Then we get the correct wire format:
                // <foo>1 2 3</foo>
                Object jbo = b;
                if (DEBUG_ENABLED) {
                    log.debug("check if marshalling list or array object, type = "
                            + ((b != null) ? b.getClass().getName() : "null"));
                }
                if (isList) {
                    if (DEBUG_ENABLED) {
                        log.debug("marshalling type which is a List");
                    }

                    // This code assumes that the JAXBContext does not understand
                    // the array or list. In such cases, the contents are converted
                    // to a String and passed directly.

                    if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH) {
                        QName qName = XMLRootElementUtil.getXmlRootElementQNameFromObject(b);
                        String text = XSDListUtils.toXSDListString(getTypeEnabledObject(b));
                        if (DEBUG_ENABLED) {
                            log.debug("marshalling [context path approach] " + "with xmllist text = " + text);
                        }
                        jbo = new JAXBElement(qName, String.class, text);
                    } else if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY) {
                        // Some versions of JAXB have array/list processing built in.
                        // This code is a safeguard because apparently some versions
                        // of JAXB don't.
                        QName qName = XMLRootElementUtil.getXmlRootElementQNameFromObject(b);
                        String text = XSDListUtils.toXSDListString(getTypeEnabledObject(b));
                        if (DEBUG_ENABLED) {
                            log.debug("marshalling [class array approach] " + "with xmllist text = " + text);
                        }
                        jbo = new JAXBElement(qName, String.class, text);
                    }
                }
                // When JAXBContext is created using a context path, it will not include Enum
                // classes.
                // These classes have @XmlEnum annotation but not @XmlType/@XmlElement, so the
                // user will see MarshallingEx, class not known to ctxt.
                // 
                // This is a jax-b defect, for now this fix is in place to pass CTS. This only
                // fixes the
                // situation where the enum is the top-level object (e.g., message-part in
                // rpc-lit scenario)
                //
                // Sample of what enum looks like:
                // @XmlEnum public enum EnumString {
                // @XmlEnumValue("String1") STRING_1("String1"),
                // @XmlEnumValue("String2") STRING_2("String2");
                // ... }
                if (type.isEnum()) {
                    if (b != null) {
                        if (DEBUG_ENABLED) {
                            log.debug("marshalByType. Marshaling " + type.getName() + " as Enum");
                        }
                        JAXBElement jbe = (JAXBElement) b;
                        String value = XMLRootElementUtil.getEnumValue((Enum) jbe.getValue());

                        jbo = new JAXBElement(jbe.getName(), String.class, value);
                    }
                }

                // If the output stream is available, marshal directly to it
                OutputStream os = (optimize) ? getOutputStream(writer, m) : null;
                if (os == null) {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByType.  " + "Marshaling to an XMLStreamWriter. Object is "
                                + getDebugName(jbo));
                    }
                    m.marshal(jbo, writer);
                } else {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByType.  " + "Marshaling to an OutputStream. Object is "
                                + getDebugName(jbo));
                    }
                    m.marshal(jbo, os);
                }

            } catch (OMException e) {
                throw e;
            } catch (Throwable t) {
                throw new OMException(t);
            }
            return null;
        }
    });
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

/**
 * Edit product//from w ww .jav a  2s . com
 * 
 * @param ID
 * @param map
 * @return
 */
@RequestMapping(value = ("/editproduct"), method = RequestMethod.GET)
public String editProduct(@RequestParam(value = "Id", required = true) String ID, ModelMap map) {
    logger.debug("### editProduct method starting...(GET)");
    Product product = productService.locateProductById(ID);
    ProductForm productForm = new ProductForm(product);
    productForm.setCurrencyPresicion(
            Integer.parseInt(config.getValue(Names.com_citrix_cpbm_portal_appearance_currency_precision)));
    productForm.setCategoryID(product.getCategory().getId().toString());
    map.addAttribute("productForm", productForm);

    ProductRevision productRevision = productService.getProductRevision(product,
            channelService.getFutureRevision(null).getStartDate(), null);
    List<MediationRule> mediationRules = productRevision.getMediationRules();
    Map<ServiceUsageType, Set<MediationRuleDiscriminator>> usgaeTypeForWhichDiscValesAreToBeGotAndDiscsMap = new HashMap<ServiceUsageType, Set<MediationRuleDiscriminator>>();
    for (MediationRule mediationRule : mediationRules) {
        if (mediationRule.getMediationRuleDiscriminators().size() > 0) {
            usgaeTypeForWhichDiscValesAreToBeGotAndDiscsMap.put(mediationRule.getServiceUsageType(),
                    mediationRule.getMediationRuleDiscriminators());
        }
    }

    Set<String> serviceUsageTypeNames = new HashSet<String>();
    Set<String> discrimintaorNames = new HashSet<String>();
    for (ServiceUsageType serviceUsageType : product.getServiceInstance().getService().getServiceUsageTypes()) {
        serviceUsageTypeNames.add(serviceUsageType.getUsageTypeName());
        for (ServiceDiscriminator serviceDiscriminator : product.getServiceInstance().getService()
                .getServiceUsageTypeDiscriminator(serviceUsageType)) {
            discrimintaorNames.add(serviceDiscriminator.getDiscriminatorName());
        }
    }
    map.addAttribute("serviceName", product.getServiceInstance().getService().getServiceName());
    map.addAttribute("serviceUsageTypeNames", serviceUsageTypeNames);
    map.addAttribute("discrimintaorNames", discrimintaorNames);

    List<Category> categories = productService.getAllCategories();
    map.addAttribute("categories", categories);

    Map<String, Object> mediationRuleMap = new HashMap<String, Object>();
    Map<String, Object> usageTypeDiscMap = new HashMap<String, Object>();
    try {
        for (final MediationRule mediationRule : mediationRules) {
            Map<String, Object> mediationRuleEntitiesMap = new HashMap<String, Object>();
            mediationRuleEntitiesMap.put("usageType", mediationRule.getServiceUsageType().getUsageTypeName());
            mediationRuleEntitiesMap.put("conversionFactor", productService
                    .getConversionFactor(mediationRule.getConversionFactor(), mediationRule.isMonthly()));
            mediationRuleEntitiesMap.put("operator", mediationRule.getOperator().toString().toLowerCase());
            mediationRuleEntitiesMap.put("uom",
                    mediationRule.getServiceUsageType().getServiceUsageTypeUom().getName());
            mediationRuleEntitiesMap.put("productUom", product.getUom());
            mediationRuleEntitiesMap.put("usageTypeId", mediationRule.getServiceUsageType().getId());
            mediationRuleEntitiesMap.put("discrete", mediationRule.getServiceUsageType().getDiscrete());
            Map<String, Object> medDiscsMap = new HashMap<String, Object>();
            for (MediationRuleDiscriminator mediationRuleDiscriminator : mediationRule
                    .getMediationRuleDiscriminators()) {
                Map<String, Object> medRuleDisEntitiesMap = new HashMap<String, Object>();
                medRuleDisEntitiesMap.put("discriminatorType",
                        mediationRuleDiscriminator.getServiceDiscriminator().getDiscriminatorName());
                medRuleDisEntitiesMap.put("discrimniatorValue",
                        mediationRuleDiscriminator.getDiscriminatorValue());
                medRuleDisEntitiesMap.put("operator",
                        mediationRuleDiscriminator.getOperator().toString().toLowerCase());
                medRuleDisEntitiesMap.put("discriminatorTypeId",
                        mediationRuleDiscriminator.getServiceDiscriminator().getId());

                medDiscsMap.put(mediationRuleDiscriminator.getId().toString(), medRuleDisEntitiesMap);
            }

            mediationRuleEntitiesMap.put("discriminators", medDiscsMap);
            mediationRuleMap.put(mediationRule.getId().toString(), mediationRuleEntitiesMap);

            if (medDiscsMap.size() > 0) {
                try {
                    final ServiceInstance serviceInstance = product.getServiceInstance();
                    final ServiceUsageType serviceUsageType = mediationRule.getServiceUsageType();
                    // Loop over usage types to get the discriminator values
                    // TODO: Need a call to directly get a Service Usage Type from its id
                    // Loop over usage discriminators to get the values
                    Map<String, Object> discValueMap = privilegeService
                            .runAsPortal(new PrivilegedAction<Map<String, Object>>() {

                                @Override
                                public Map<String, Object> run() {
                                    Map<String, Object> discValueMap = new HashMap<String, Object>();
                                    Set<ServiceDiscriminator> usageTypeDiscriminators = serviceInstance
                                            .getService().getServiceUsageTypeDiscriminator(serviceUsageType);
                                    for (ServiceDiscriminator usageTypeDiscriminator : usageTypeDiscriminators) {
                                        Map<String, String> discriminatorValMap = new HashMap<String, String>();
                                        discriminatorValMap = ((CloudConnector) connectorManagementService
                                                .getServiceInstance(serviceInstance.getUuid()))
                                                        .getMetadataRegistry().getDiscriminatorValues(
                                                                usageTypeDiscriminator.getDiscriminatorName());
                                        // Create map of discriminator to its values
                                        Map<String, Object> discVals = new HashMap<String, Object>();
                                        discVals.put("name", usageTypeDiscriminator.getDiscriminatorName());
                                        discVals.put("discriminatorValues", discriminatorValMap);
                                        discValueMap.put(usageTypeDiscriminator.getId().toString(), discVals);
                                    }
                                    return discValueMap;
                                }
                            });
                    // Add entries to the service Usage type map
                    Map<String, Object> usageTypeMap = new HashMap<String, Object>();
                    usageTypeMap.put("name", serviceUsageType.getUsageTypeName());
                    usageTypeMap.put("discriminators", discValueMap);
                    usageTypeDiscMap.put(serviceUsageType.getId().toString(), usageTypeMap);
                } catch (Exception e) {
                    logger.error("Error in creating the usage discriminator map...", e);
                }
            } else {
                usageTypeDiscMap.put(mediationRule.getServiceUsageType().getId().toString(),
                        new HashMap<String, Object>());
            }
        }
    } catch (Exception e) {
        logger.error("Error in creating the usage discriminator map...", e);
    }

    String jsonUsageTypeDiscriminatorMap = "";
    try {
        jsonUsageTypeDiscriminatorMap = JSONUtils.toJSONString(usageTypeDiscMap);
    } catch (Exception e) {
        logger.error("Error in creating json string from the usage discriminator map ...", e);
    }

    String jsonMediationRuleMap = "";
    try {
        jsonMediationRuleMap = JSONUtils.toJSONString(mediationRuleMap);
    } catch (Exception e) {
        logger.error("Error in creating json string from the mediation Rule Discriminator Map ...", e);
    }

    map.addAttribute("jsonUsageTypeDiscriminatorMap", jsonUsageTypeDiscriminatorMap);
    map.addAttribute("jsonMediationRuleMap", jsonMediationRuleMap);
    map.addAttribute("serviceName", product.getServiceInstance().getService().getServiceName());
    map.addAttribute("serviceInstanceName", product.getServiceInstance().getName());

    logger.debug("### editProduct method end");
    return "products.edit";
}

From source file:org.apache.axis2.deployment.util.Utils.java

private static DeploymentClassLoader createDeploymentClassLoader(final URL[] urls,
        final ClassLoader serviceClassLoader, final List embeddedJars, final boolean isChildFirstClassLoading) {
    return (DeploymentClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new DeploymentClassLoader(urls, embeddedJars, serviceClassLoader, isChildFirstClassLoading);
        }/*from ww  w.ja  v a 2  s.c om*/
    });
}

From source file:org.apache.ws.scout.registry.RegistryImpl.java

/**
 * //w ww .  ja v a 2s.c  o  m
 * @param name
 * @return The class object for the name given
 * @throws ClassNotFoundException
 * @throws NoClassDefFoundError
 */
public static Class getClassForName(String name) throws ClassNotFoundException, NoClassDefFoundError {
    Class clazz = null;

    try {
        // log.info("Using the Context ClassLoader");
        ClassLoader ccl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }
        });

        clazz = Class.forName(name, true, ccl);
    } catch (Exception e) {
        log.debug("Failed to load the class " + name + " with context class loader " + e);
    }

    if (null == clazz) {
        ClassLoader scl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return ClassLoader.getSystemClassLoader();
            }
        });

        try {
            clazz = Class.forName(name, true, scl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return clazz;
}

From source file:org.apache.axis2.wsdl.util.WSDLWrapperReloadImpl.java

private static String getExplicitURI(URL wsdlURL) throws WSDLException {

    if (isDebugEnabled) {
        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + ") ");
    }// w ww . j  av a 2  s  . co m

    String explicitURI = null;

    ClassLoader classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });

    try {
        URL url = wsdlURL;
        String filePath = null;
        boolean isFileProtocol = (url != null && "file".equals(url.getProtocol())) ? true : false;

        if (isFileProtocol) {
            filePath = (url != null) ? url.getPath() : null;

            URI uri = null;
            if (url != null) {
                uri = new URI(url.toString());
            }

            // Check if the uri has relative path 
            // ie path is not absolute and is not starting with a "/" 
            boolean isRelativePath = (filePath != null && !new File(filePath).isAbsolute()) ? true : false;

            if (isRelativePath) {
                if (isDebugEnabled) {
                    log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): WSDL URL has a relative path");
                }

                // Lets read the complete WSDL URL for relative path from class loader
                // Use relative path of url to fetch complete URL.              
                url = getAbsoluteURL(classLoader, filePath, wsdlURL);

                if (url == null) {
                    if (isDebugEnabled) {
                        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                                + "WSDL URL for relative path not found in ClassLoader");
                        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                                + "Unable to read WSDL from relative path, check the relative path");
                        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                                + "Relative path example: file:/WEB-INF/wsdl/<wsdlfilename>");
                        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                                + "Using relative path as default wsdl URL to load wsdl Definition.");
                    }
                    url = wsdlURL;
                } else {
                    if (isDebugEnabled) {
                        log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                                + "WSDL URL found for relative path: " + filePath + " scheme: "
                                + uri.getScheme());
                    }
                }
            }
        }

        URLConnection urlCon = url.openConnection();
        InputStream is = null;
        try {
            is = getInputStream(urlCon);
        } catch (IOException e) {
            if (isDebugEnabled) {
                log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                        + "Could not open url connection. Trying to use " + "classloader to get another URL.");
            }

            if (filePath != null) {

                url = getAbsoluteURL(classLoader, filePath, wsdlURL);
                if (url == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not locate URL for wsdl. Reporting error");
                    }
                    throw new WSDLException("WSDL4JWrapper : ", e.getMessage(), e);
                } else {
                    urlCon = url.openConnection();
                    if (log.isDebugEnabled()) {
                        log.debug("Found URL for WSDL from jar");
                    }
                }
            } else {
                if (isDebugEnabled) {
                    log.debug(myClassName + ".getExplicitURI(" + wsdlURL + "): "
                            + "Could not get URL from classloader. Reporting " + "error due to no file path.");
                }
                throw new WSDLException("WSDLWrapperReloadImpl : ", e.getMessage(), e);
            }
        }
        if (is != null) {
            is.close();
        }

        explicitURI = urlCon.getURL().toString();

    } catch (Exception ex) {
        throw new WSDLException("WSDLWrapperReloadImpl : ", ex.getMessage(), ex);
    }

    return explicitURI;
}

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Marshal array objects by type/*from  w ww .  j a v a 2 s.c  om*/
 * 
 * Invoke marshalByType for each element in the array
 * 
 * @param jaxb_in JAXBElement containing a value that is a List or array
 * @param m_in Marshaller
 * @param writer_in XMLStreamWriter
 */
private void marshalOccurrenceArray(final JAXBElement jbe_in, final Marshaller m_in,
        final XMLStreamWriter writer_in) {

    if (log.isDebugEnabled()) {
        log.debug("Enter marshalOccurrenceArray");
        log.debug("  Marshaller = " + JavaUtils.getObjectIdentity(m_in));
    }

    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                Marshaller m = m_in;
                JAXBContext newJBC = null;
                if (getConstructionType() != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                    // Rebuild JAXBContext
                    // There may be a preferred classloader that should be used
                    if (log.isDebugEnabled()) {
                        log.debug("Building a JAXBContext with array capability");
                    }
                    ClassLoader cl = getClassLoader();
                    newJBC = getJAXBContext(cl, true);
                    m = JAXBUtils.getJAXBMarshaller(newJBC);
                    if (log.isDebugEnabled()) {
                        log.debug("The new JAXBContext was constructed with " + getConstructionType());
                    }
                }

                OccurrenceArray occurArray = (OccurrenceArray) jbe_in.getValue();

                // Create a new JAXBElement.
                // The name is the name of the individual occurence elements
                // Type type is Object[]
                // The value is the array of Object[] representing each element
                JAXBElement jbe = new JAXBElement(jbe_in.getName(), Object[].class, occurArray.getAsArray());

                // The jaxb marshal command cannot write out a list/array
                // of occurence elements.  So we marshal it as a single
                // element containing items...and then put a filter on the
                // writer to transform it into a stream of occurence elements
                XMLStreamWriterArrayFilter writer = new XMLStreamWriterArrayFilter(writer_in);

                m.marshal(jbe, writer);

                if (newJBC != null) {
                    JAXBUtils.releaseJAXBMarshaller(newJBC, m);
                }

                return null;
            } catch (OMException e) {
                throw e;
            } catch (Throwable t) {
                throw new OMException(t);
            }
        }
    });

    if (log.isDebugEnabled()) {
        log.debug("Exit marshalOccurrenceArray");
    }

}

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Preferred way to unmarshal objects/*from ww w  .j a  v a2 s .c  o m*/
 * 
 * @param u Unmarshaller
 * @param reader XMLStreamReader
 * @return Object that represents an element
 * @throws WebServiceException
 */
public static Object unmarshalByElement(final Unmarshaller u, final XMLStreamReader reader)
        throws WebServiceException {
    try {
        if (DEBUG_ENABLED) {
            log.debug("Invoking unMarshalByElement");
        }
        return AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return u.unmarshal(reader);
                } catch (OMException e) {
                    throw e;
                } catch (Throwable t) {
                    throw new OMException(t);
                }
            }
        });

    } catch (OMException e) {
        throw e;
    } catch (Throwable t) {
        throw new OMException(t);
    }
}

From source file:org.apache.axis2.wsdl.util.WSDLWrapperReloadImpl.java

private static URL getAbsoluteURL(final ClassLoader classLoader, final String filePath, URL wURL)
        throws WSDLException {
    URL url = (URL) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return classLoader.getResource(filePath);
        }/*from   ww w.j  a v a2s .c o  m*/
    });
    if (url == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not get URL from classloader. Looking in a jar.");
        }
        if (classLoader instanceof URLClassLoader) {
            URLClassLoader urlLoader = (URLClassLoader) classLoader;
            url = getURLFromJAR(urlLoader, wURL);
        }
    }
    return url;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSubscriptionController.java

@RequestMapping(value = ("/view_catalog"), method = RequestMethod.GET)
public String previewCatalog(@RequestParam(value = "channelParam", required = false) String channelParam,
        ModelMap map, @RequestParam(value = "tenant", required = false) final String tenantParam,
        @RequestParam(value = "serviceInstanceUUID", required = false) final String serviceInstanceUUID,
        @RequestParam(value = "subscriptionId", required = false) String subscriptionId,
        @RequestParam(value = "revision", required = false) String revision,
        @RequestParam(value = "revisionDate", required = false) String revisionDate,
        @RequestParam(value = "dateFormat", required = false) String dateFormat,
        @RequestParam(value = "currencyCode", required = false) String currencyCode,
        @RequestParam(value = "resourceType", required = false) final String resourceType,
        final HttpServletRequest request) throws ConnectorManagementServiceException {
    logger.debug("### viewCatalog method starting...(GET)");
    Channel channel = null;//from   ww  w.j ava 2  s  . c  om
    String successView = "channels.catalog.view";
    if (channelParam != null && !channelParam.equals("null") && channelParam != "") {
        channel = channelService.getChannelById(channelParam);
    } else {
        channel = channelService.getDefaultServiceProviderChannel();
    }
    final Catalog catalog = channel.getCatalog();
    List<CurrencyValue> currencies = catalog.getSupportedCurrencyValuesByOrder();
    map.addAttribute("channel", channel);
    map.addAttribute("currencies", currencies);
    map.addAttribute("viewChannelCatalog", true);
    map.addAttribute("revision", revision);
    map.addAttribute("revisionDate", revisionDate);
    map.addAttribute("dateFormat", dateFormat);
    if (StringUtils.isNotBlank(currencyCode)) {
        CurrencyValue currency = currencyValueService.locateBYCurrencyCode(currencyCode);
        map.addAttribute("selectedCurrency", currency);
    } else {
        map.addAttribute("selectedCurrency", currencies.get(0));
    }

    final Tenant tenant = tenantService.getSystemTenant();
    final String finalView = successView;
    final Channel catalogChannel = channel;
    Map<String, Object> finalMap = privilegeService.runAsPortal(new PrivilegedAction<Map<String, Object>>() {

        @Override
        public Map<String, Object> run() {
            ModelMap modelMap = new ModelMap();
            try {
                getResourceComponentsAndFilterData(tenant, tenantParam, serviceInstanceUUID, null, resourceType,
                        modelMap, request, finalView, catalogChannel.getName());
            } catch (ConnectorManagementServiceException e) {
                logger.debug("Error occured ", e);
            }
            return modelMap;
        }
    });
    map.addAllAttributes(finalMap);
    // preview catalog will have default UI Because in cutom UI SSO happens which can leads to
    // security threats
    map.addAttribute("customEditorTag", null);
    map.addAttribute("customComponentSelector", null);
    return finalView;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java

/**
 * This method is used for Register.// www  .  j av  a2  s .  c om
 * 
 * @param registration
 * @param result
 * @param captchaChallenge
 * @param captchaResponse
 * @param map
 * @param channelParam
 * @param sessionStatus
 * @param request
 * @return String
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid @ModelAttribute("registration") final UserRegistration registration,
        final BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String captchaChallenge,
        @RequestParam(value = "recaptcha_response_field", required = false) String captchaResponse,
        final ModelMap map, @ModelAttribute("channelParam") final String channelParam,
        SessionStatus sessionStatus, HttpServletRequest request) {
    logger.debug("###Entering in register( method @POST");
    map.addAttribute("page", Page.HOME);
    map.addAttribute("registration", registration);
    addFraudProfilingHostToSession(map);
    IPtoCountry iPtoCountry = super.getGeoIpToCountry(request);
    List<Country> filteredCountryList = getFilteredCountryList(registration.getCountryList());
    map.addAttribute("filteredCountryList", filteredCountryList);
    if (registration.getUser().getAddress().getCountry().length() > 0) {
        map.addAttribute("ipToCountryCode", registration.getUser().getAddress().getCountry());
    } else {
        map.addAttribute("ipToCountryCode", iPtoCountry.getCountryCode());
    }
    map.addAttribute(Page.HOME.getLevel1().name(), "on");
    map.addAttribute("allowSecondaryCheckBox",
            registration.getTenant().getAccountType().isEnableSecondaryAddress());
    if (!registration.getPhoneVerificationEnabled()
            && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) {
        try {
            verifyCaptcha(captchaChallenge, captchaResponse, getRemoteUserIp(request), captchaService);
        } catch (CaptchaFailureException ex) {
            map.addAttribute("registrationError", "captcha.error");
            map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey());
            map.addAttribute("showCaptcha", true);
            result.reject("errors.registration.captcha", null, null);
            map.addAttribute("allowSecondaryCheckBox",
                    registration.getTenant().getAccountType().isEnableSecondaryAddress());
            return "register.moreuserinfo";
        }
    }

    registration.getUser().setPhone(registration.getUser().getPhone().replaceAll(PHONE_NUMBER_REGEX, ""));

    TelephoneVerificationService telephoneVerificationService = (TelephoneVerificationService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION);
    if (telephoneVerificationService != null && telephoneVerificationService.isEnabled()) {
        String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin")
                .toString();
        String actualPhoneNumber = request.getSession().getAttribute("phoneNumber").toString();
        if (!registration.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin)
                || !areDigitsInPhoneNosEqual(registration.getUser().getPhone(), actualPhoneNumber)) {
            map.addAttribute("registrationError", "phoneVerfication.error");
            result.reject("errors.registration.user.phone", null, null);
            return "register.phoneverification";
        }
    }
    if (result.hasErrors()) {
        displayErrors(result);
        parseResult(result, map);
        return "register.userinfo";
    }

    // Device intelligence and fraud detection
    ReviewStatus fraudStatus = null;
    DeviceFraudDetectionAudit log = null;
    DeviceFraudDetectionService deviceFraudDetectionService = (DeviceFraudDetectionService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL);
    if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) {
        fraudStatus = assessAccountCreationRisk(registration, request);

        if (fraudStatus == ReviewStatus.FAIL) {
            return "register.fail";
        }

        log = ((DeviceFraudDetectionService) connectorManagementService
                .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL))
                        .getLastLog(request.getSession().getId(), registration.getUser().getUsername());

        String message = "device.fraud";
        Tenant tenant = tenantService.getSystemTenant();
        String messageArguments = registration.getUser().getUsername();
        Event event = null;

        switch (fraudStatus) {
        case REJECT:
            context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(),
                    new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(),
                            registration.getUser().getEmail(), registration.getUser().getPhone(),
                            registration.getUser().getFirstName(), registration.getUser().getLastName())));
            event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT,
                    Category.ACCOUNT, Severity.CRITICAL, true);
            eventService.createEvent(event, false);
            return "register.fail";

        case REVIEW:
            // account to be manual activated
            registration.getTenant().setIsManualActivation(true);

            context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(),
                    new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(),
                            registration.getUser().getEmail(), registration.getUser().getPhone(),
                            registration.getUser().getFirstName(), registration.getUser().getLastName())));
            event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT,
                    Category.ACCOUNT, Severity.ALERT, true);
            eventService.createEvent(event, false);

            // Model should know fraud has been detected
            map.put("deviceFraudDetected", true);
        default:
            break;
        }

    }
    // This checks whether the trial code is valid or not
    map.addAttribute("supportEmail", config.getValue(Names.com_citrix_cpbm_portal_addressbook_helpDeskEmail));
    map.addAttribute("supportPhone", config.getValue(Names.com_citrix_cpbm_portal_settings_helpdesk_phone));

    // post processing for trial code
    if (!StringUtils.isEmpty(registration.getTrialCode())) {
        String promoCode = registration.getTrialCode();
        String channelCode = channelService.getChannel(channelParam).getCode();

        if (!promotionService.isValidPromotion(promoCode, channelCode)) {
            logger.debug("Invalid promo code " + promoCode + " for channel code " + channelCode);
            return "register.fail";
        }

        // preempt trial account type creation if NOT supported [TA10428]
        CampaignPromotion cp = promotionService.locatePromotionByToken(promoCode);
        AccountType requestedAccountType = registrationService
                .getAccountTypeById(registration.getAccountTypeId());

        if (requestedAccountType.equals(registrationService.getTrialAccountType()) && !cp.isTrial()) {
            logger.debug("Invalid promo code " + promoCode + " for account type " + requestedAccountType);

            return "register.fail";
        }
    }

    registration.getTenant().setAddress(registration.getUser().getAddress());
    if (!registration.isAllowSecondary()) {
        registration.getTenant().setSecondaryAddress(null);
    } else {
        registration.getTenant().setSecondaryAddress(registration.getSecondaryAddress());
    }
    registration.getTenant().setSyncBillingAddress(true);
    // to store error messages
    List<String> errorMsgList = new ArrayList<String>();
    try {

        final com.citrix.cpbm.access.User owner = registration.getUser();
        if (registration.getCountryCode() == null || registration.getCountryCode().equals("")) {
            Country country = countryService
                    .locateCountryByCode(registration.getUser().getAddress().getCountry());
            registration.setCountryName(country.getName());
            registration.setCountryCode(country.getIsdCode());
        }
        String phoneNo = registration.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
                + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + owner.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
        // Set the phone number
        owner.setPhone(phoneNo);

        owner.setLocale(registration.getUser().getLocale());
        registration.getTenant().setRemoteAddress(getRemoteUserIp(request));

        // set currency
        for (CurrencyValue cv : registration.getCurrencyValueList()) {
            if (cv.getCurrencyCode().equals(registration.getCurrency())) {
                registration.getTenant().setCurrency(cv);
                break;
            }
        }

        privilegeService.runAsPortal(new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                AccountType requestedAccountType = registrationService
                        .getAccountTypeById(registration.getAccountTypeId());
                if (requestedAccountType.equals(registrationService.getTrialAccountType())) {
                    TrialAccount account = null;
                    try {
                        account = registrationService.registerTrialAccount(registration.getTrialCode(),
                                registration.getTenant(), owner, channelParam);
                    } catch (TrialCodeInvalidException e) {
                        logger.debug("Invalid Trial Code", e);
                    } catch (ConnectorManagementServiceException e) {
                        logger.debug("Cannot find service instance", e);
                    }
                    map.addAttribute("trial", account);
                    return null;
                } else {
                    try {
                        registrationService.registerTenant(registration.getTenant(), owner, channelParam,
                                registration.getTrialCode(), result);
                    } catch (ConnectorManagementServiceException e) {
                        logger.debug("Cannot find service instance", e);
                    }
                }
                if (!result.hasErrors()) {
                    Tenant t = tenantService.get(registration.getTenant().getUuid());
                    t.setAccountType(registrationService.getAccountTypeById(registration.getAccountTypeId()));
                    t.getTenantExtraInformation()
                            .setPaymentMode(requestedAccountType.getSupportedPaymentModes().get(0));
                    tenantService.save(t);
                    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(t));
                }
                return null;

            }
        });
        if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) {
            log.setUserId(registration.getTenant().getOwner().getId());
        }

        map.addAttribute("tenant", registration.getTenant());
        String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url);
        String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url);
        if (homeUrl != null) {
            map.addAttribute("homeUrl", homeUrl);
        }
        if (cloudmktgUrl != null) {
            map.addAttribute("cloudmktgUrl", cloudmktgUrl);
        }
    } catch (DataAccessException ex) {
        logger.error(ex);
        result.reject("errors.registration", new Object[] { ex.getMessage() }, null);
        errorMsgList.add("You must accept the terms and conditions to use this service");
    } catch (TrialCodeInvalidException ex) {
        result.rejectValue("trialCode", "errors.registration.invalid_trial_code", null);
        map.addAttribute("trialCode", "errors.registration.invalid_trial_code");
        logger.debug("registrationError " + ex.getMessage());
    } catch (TrialMaxAccountReachedException ex) {
        result.rejectValue("trialCode", "errors.registration.max_trial_reached", null);
        map.addAttribute("trialCode", "errors.registration.max_trial_reached");
        logger.debug("registrationError " + ex.getMessage());
    } catch (Exception ex) {
        logger.error("registrationError ", ex);
        return "redirect:/portal/errors/error";
    }
    if (result.hasErrors()) {
        displayErrors(result);
        parseResult(result, map);
        registration.reset();
        registration.setCurrency(config.getValue(Names.com_citrix_cpbm_portal_settings_default_currency));
        if (errorMsgList.size() > 0) {
            map.addAttribute("errorMsgList", errorMsgList);
            map.addAttribute("errormsg", true);
        }
        logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse,"
                + "map,sessionStatus,request) method @POST");
        map.addAttribute("allowSecondaryCheckBox",
                registration.getTenant().getAccountType().isEnableSecondaryAddress());
        if (!Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) {
            map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey());
            map.addAttribute("showCaptcha", true);
        }
        return "register.moreuserinfo";
    } else {
        sessionStatus.setComplete(); // clean up parameters in session.
        logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse,"
                + "map,sessionStatus,request) method @POST");
        map.addAttribute("user", registration.getUser());
        return "register.registration_success";
    }
}