From: ramprasad kotagiri Date: Thu, 7 Mar 2019 20:55:26 +0000 (-0500) Subject: Latest code base X-Git-Tag: 1.1.0~15 X-Git-Url: https://gerrit.onap.org/r/gitweb?a=commitdiff_plain;h=2e98a6c64dcdc0891f3729abb045115b790a2c54;p=ccsdk%2Fdashboard.git Latest code base Change-Id: I9549091ebeeabcef2d7af7d91cc394d8371e496b Issue-ID: CCSDK-1011 Signed-off-by: ramprasad kotagiri --- diff --git a/.gitignore b/.gitignore index 064c22b..4268b15 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ ccsdk-app-common/ccsdk-app-common.iml ccsdk-app-os/ccsdk-app-os.iml ccsdk-app-overlay/ccsdk-app-overlay.iml +.project +.settings diff --git a/ccsdk-app-common/pom.xml b/ccsdk-app-common/pom.xml index be05119..e7a58c6 100644 --- a/ccsdk-app-common/pom.xml +++ b/ccsdk-app-common/pom.xml @@ -15,11 +15,13 @@ 4.2.0.RELEASE 4.3.11.Final 1.0.0 - 2.1.0 + 2.5.1 https://nexus.onap.org - /content/repositories/snapshots/ - /content/repositories/releases/ - true + content/repositories/snapshots/ + content/repositories/releases/ + /content/repositories/staging/ + false + 0.7.6.201602180812 @@ -35,6 +37,12 @@ OpenECOMP - Snapshot Repository ${nexusproxy}/${snapshotNexusPath} + + + onap-staging + ONAP - Staging Repository + ${nexusproxy}${stagingNexusPath} + @@ -115,7 +123,6 @@ - org.apache.maven.plugins @@ -125,12 +132,53 @@ true - + + + org.jacoco + jacoco-maven-plugin + ${jacocoVersion} + + + prepare-agent + + prepare-agent + + + ${project.build.directory}/code-coverage/jacoco-ut.exec + + + + post-unit-test + test + + report + + + ${project.build.directory}/code-coverage/jacoco-ut.exec + ${project.basedir}/target/site/jacoco + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.build.directory}/code-coverage/jacoco-ut.exec + + + + + javax.ws.rs + javax.ws.rs-api + 2.0 + org.apache.httpcomponents @@ -168,17 +216,27 @@ com.fasterxml.jackson.core jackson-annotations - 2.6.3 + 2.9.0 com.fasterxml.jackson.core jackson-core - 2.6.3 + 2.9.0 com.fasterxml.jackson.core jackson-databind - 2.6.3 + 2.9.0 + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + 2.9.0 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + 2.9.0 com.mchange @@ -237,6 +295,13 @@ spring-webmvc ${springframework.version} + + + org.jacoco + org.jacoco.agent + ${jacocoVersion} + runtime + diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java new file mode 100644 index 0000000..149708f --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.web.support.AppUtils; + +public class Authorizer { + + private static Authorizer authorizer = new Authorizer(); + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(Authorizer.class); + private static final String AUTH_PROP_FILE_NAME = "authorizer.properties"; + private static final String DCAE_ROLES_KEY = "dcae_roles"; + + public static Authorizer getAuthorizer() { + return authorizer; + } + + public boolean isAuthorized(HttpServletRequest request) { + final String method = request.getMethod(); + final String resource = request.getRequestURI(); + + final Set authorizedRoles = getAuthorizedRoles(method, resource); + + // Anybody can access this page, no need to check + if (authorizedRoles.contains(Role.ANY)) { + return true; + } + + final Set roles = getRoles(request); + final Set intersection = new HashSet<> (roles); + + intersection.retainAll(authorizedRoles); // Removes all roles in roles that aren't contained in authorizedRoles. + + return !intersection.isEmpty(); //If the intersection is not empty, then this user is authorized + } + + // Helper method to set roles + public void putRoles(HttpServletRequest request, Set roles) { + request.getSession().setAttribute(DCAE_ROLES_KEY, roles); + } + + // Returns roles for the current user making the request + @SuppressWarnings("unchecked") + private Set getRoles(HttpServletRequest request) { + + // If roles is empty, then write the user's roles to the session + if (request.getSession().getAttribute(DCAE_ROLES_KEY) == null) { + + // HashSet to be used to for putRoles + HashSet roles = new HashSet<>(); + roles.add(Role.READER); + + // Get roles and turn into list of role objects + HttpSession session = AppUtils.getSession(request); + String roleType = (String)session.getAttribute("auth_role"); + if (roleType != null) { + switch (roleType) { + case "ADMIN": roles.add(Role.ADMIN); + break; + case "WRITE": roles.add(Role.WRITER); + break; + case "READ": roles.add(Role.READER); + break; + default: roles.add(Role.READER); + break; + } + } + // Write user roles + putRoles(request, roles); + } + + // Check if attribute DCAE_ROLES_KEY is valid + final Object rawRoles = request.getSession().getAttribute(DCAE_ROLES_KEY); + + if (!(rawRoles instanceof Set)) { + throw new RuntimeException("Unrecognized object found in session for key=" + DCAE_ROLES_KEY); + } + + return (Set) request.getSession().getAttribute(DCAE_ROLES_KEY); + } + + // Returns roles authorized to perform the requested method (i.e. getAuthorizedRoles("POST", "/ecd-app-att/deployments")) + private Set getAuthorizedRoles(String method, String resource) { + final Properties resourceRoles = new Properties(); + + try { + resourceRoles.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(AUTH_PROP_FILE_NAME)); + + final String[] splitMethodResourceKey = (method + resource.replace("/", ".")).split("\\.",0); + final String methodResourceKey = splitMethodResourceKey[0] + "." + splitMethodResourceKey[2]; + + if (!resourceRoles.containsKey(methodResourceKey)) { + LOGGER.warn(AUTH_PROP_FILE_NAME + " does not contain roles for " + methodResourceKey + "; defaulting " + Authorizer.Role.ANY); + return new HashSet<> (Collections.singleton(Role.ANY)); + } + + final String[] rawAuthorizedRoles = ((String) resourceRoles.get(methodResourceKey)).split(","); + final Set authorizedRoles = new HashSet<> (); + + for (String rawAuthorizedRole : rawAuthorizedRoles) { + authorizedRoles.add(Authorizer.Role.valueOf(rawAuthorizedRole)); + } + + return authorizedRoles; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public enum Role { + ADMIN, + READER, + WRITER, + ANY, + NONE; + } + + +} \ No newline at end of file diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java index 7b05841..d7cdc6f 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java @@ -1,637 +1,1376 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import com.fasterxml.jackson.core.JsonProcessingException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; -import org.onap.ccsdk.dashboard.model.CloudifyDeployment; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.ccsdk.dashboard.model.RestResponseError; -import org.onap.ccsdk.dashboard.model.RestResponsePage; -import org.onap.ccsdk.dashboard.rest.IControllerRestClient; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.client.HttpStatusCodeException; - -/** - * Controller for Cloudify features: blueprints, deployments, executions. - * Methods serve Ajax requests made by Angular scripts on pages that show - * content. - */ -@Controller -@RequestMapping("/") -public class CloudifyController extends DashboardRestrictedBaseController { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyController.class); - - /** - * Enum for selecting an item type. - */ - public enum CloudifyDataItem { - BLUEPRINT, DEPLOYMENT, EXECUTION; - } - - private static final String BLUEPRINTS_PATH = "blueprints"; - private static final String VIEW_BLUEPRINTS_PATH = "viewblueprints"; - private static final String DEPLOYMENTS_PATH = "deployments"; - private static final String EXECUTIONS_PATH = "executions"; - - /** - * Supports sorting blueprints by ID - */ - private static Comparator blueprintComparator = Comparator.comparing(o -> o.id); - - /** - * Supports sorting deployments by ID - */ - private static Comparator deploymentComparator = Comparator.comparing(o -> o.id); - - /** - * Supports sorting executions by ID - */ - private static Comparator executionComparator = Comparator.comparing(o -> o.id); - - /** - * Gets one page of objects and supporting information via the REST client. - * On success, returns a PaginatedRestResponse object as String. - * - * @param option - * Specifies which item list type to get - * @param pageNum - * Page number of results - * @param pageSize - * Number of items per browser page - * @return JSON block as String, see above. - * @throws DashboardControllerException - * On any error; e.g., Network failure. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - private String getItemListForPage(long userId, CloudifyDataItem option, int pageNum, int pageSize) - throws DashboardControllerException, JsonProcessingException { - IControllerRestClient restClient = getControllerRestClient(userId); - List itemList; - switch (option) { - case BLUEPRINT: - itemList = restClient.getBlueprints().items; - itemList.sort(blueprintComparator); - break; - case DEPLOYMENT: - itemList = restClient.getDeployments().items; - itemList.sort(deploymentComparator); - break; - default: - throw new DashboardControllerException( - "getItemListForPage failed: unimplemented case: " + option.name()); - } - - // Shrink if needed - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (totalItems > pageSize) { - itemList = getPageOfList(pageNum, pageSize, itemList); - } - RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); - return objectMapper.writeValueAsString(model); - } - - /** - * Gets one page of the specified items. This method traps exceptions and - * constructs an appropriate JSON block to report errors. - * - * @param request - * Inbound request - * @param option - * Item type to get - * @return JSON with one page of objects; or an error. - */ - protected String getItemListForPageWrapper(HttpServletRequest request, CloudifyDataItem option) { - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { - throw new DashboardControllerException("getItemListForPageWrapper: Failed to get application user"); - } - int pageNum = getRequestPageNumber(request); - int pageSize = getRequestPageSize(request); - outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception", ex); - RestResponseError result; - if (ex instanceof HttpStatusCodeException) { - result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); - } else { - result = new RestResponseError("Failed to get " + option.name(), ex); - } - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } - return outboundJson; - } - - /** - * Serves one page of blueprints - * - * @param request - * HttpServletRequest - * @return List of CloudifyBlueprint objects - */ - @RequestMapping(value = {BLUEPRINTS_PATH}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getBlueprintsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - String json = getItemListForPageWrapper(request, CloudifyDataItem.BLUEPRINT); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return json; - } - - /** - * Serves one page of deployments - * - * @param request - * HttpServletRequest - * @return List of CloudifyDeployment objects - */ - @RequestMapping(value = {DEPLOYMENTS_PATH}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDeploymentsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - String json = getItemListForPageWrapper(request, CloudifyDataItem.DEPLOYMENT); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return json; - } - - /** - * Gets the specified blueprint metadata. - * - * @param id - * Blueprint ID - * @param request - * HttpServletRequest - * @return Blueprint as JSON; or error. - * @throws JsonProcessingException - * on serialization error - * - */ - @RequestMapping(value = {BLUEPRINTS_PATH + "/{id}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getBlueprintById(@PathVariable("id") String id, HttpServletRequest request) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getBlueprint(id); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("getBlueprintById failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Gets the specified blueprint content for viewing. - * - * @param id - * Blueprint ID - * @param request - * HttpServletRequest - * @return Blueprint as YAML; or error. - * @throws JsonProcessingException - * on serialization error - * - */ - @RequestMapping(value = { - VIEW_BLUEPRINTS_PATH + "/{id}"}, method = RequestMethod.GET, produces = "application/yaml") - @ResponseBody - public String viewBlueprintContentById(@PathVariable("id") String id, HttpServletRequest request) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.viewBlueprint(id); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("getBlueprintContentById failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to upload a blueprint from a remote server. - * - * @param request - * HttpServletRequest - * @param blueprint - * Cloudify blueprint - * @return Blueprint as uploaded; or error. - * @throws JsonProcessingException - * on serialization error - */ - @RequestMapping(value = {BLUEPRINTS_PATH}, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String uploadBlueprint(HttpServletRequest request, @RequestBody CloudifyBlueprintUpload blueprint) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.uploadBlueprint(blueprint); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("uploadBlueprint failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Deletes the specified blueprint. - * - * @param id - * Blueprint ID - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse - * @return No content on success; error on failure. - * @throws JsonProcessingException - * On serialization failure - */ - @RequestMapping(value = {BLUEPRINTS_PATH + "/{id}"}, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteBlueprint(@PathVariable("id") String id, HttpServletRequest request, - HttpServletResponse response) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - int code = restClient.deleteBlueprint(id); - response.setStatus(code); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("deleteBlueprint failed on ID " + id, t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - if (result == null) { - return null; - } else { - return objectMapper.writeValueAsString(result); - } - } - - /** - * Gets the specified deployment. - * - * @param id - * Deployment ID - * @param request - * HttpServletRequest - * @return Deployment for the specified ID; error on failure. - * @throws JsonProcessingException - * On serialization failure - * - */ - @RequestMapping(value = {DEPLOYMENTS_PATH + "/{id}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDeploymentById(@PathVariable("id") String id, HttpServletRequest request) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getDeployment(id); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("getDeploymentById failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to create a deployment based on a blueprint. - * - * @param request - * HttpServletRequest - * @param deployment - * Deployment to upload - * @return Body of deployment; error on failure - * @throws JsonProcessingException - * On serialization failure - */ - @RequestMapping(value = {DEPLOYMENTS_PATH}, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String createDeployment(HttpServletRequest request, @RequestBody CloudifyDeploymentRequest deployment) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.createDeployment(deployment); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("createDeployment failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Deletes the specified deployment. - * - * @param id - * Deployment ID - * @param ignoreLiveNodes - * Boolean indicator whether to force a delete in case of live - * nodes - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse - * @return Passes through HTTP status code from remote endpoint; no body on - * success - * @throws JsonProcessingException - * on serialization failure - */ - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{id}"}, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDeployment(@PathVariable("id") String id, - @RequestParam(value = "ignore_live_nodes", required = false) Boolean ignoreLiveNodes, - HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - int code = restClient.deleteDeployment(id, ignoreLiveNodes == null ? false : ignoreLiveNodes); - response.setStatus(code); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("deleteDeployment failed on ID " + id, t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - if (result == null) { - return null; - } else { - return objectMapper.writeValueAsString(result); - } - } - - /** - * Gets and serves one page of executions: - *
    - *
  1. Gets all deployments; OR uses the specified deployment ID if the - * query parameter is present - *
  2. Gets executions for each deployment ID - *
  3. Sorts by execution ID - *
  4. Reduces the list to the page size (if needed) - *
  5. If the optional request parameter "status" is present, reduces the - * list to the executions with that status. - *
- * - * @param request - * HttpServletRequest - * @param deployment_id - * Optional request parameter; if found, only executions for that - * deployment ID are returned. - * @param status - * Optional request parameter; if found, only executions with - * that status are returned. - * @return List of CloudifyExecution objects - * @throws JsonProcessingException - * on serialization failure - */ - @SuppressWarnings("unchecked") - @RequestMapping(value = {EXECUTIONS_PATH}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getExecutionsByPage(HttpServletRequest request, - @RequestParam(value = "deployment_id", required = false) String deployment_id, - @RequestParam(value = "status", required = false) String status) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - List itemList = new ArrayList<>(); - IControllerRestClient restClient = getControllerRestClient(request); - List depIds = new ArrayList<>(); - if (deployment_id == null) { - CloudifyDeploymentList depList = restClient.getDeployments(); - for (CloudifyDeployment cd : depList.items) { - depIds.add(cd.id); - } - } else { - depIds.add(deployment_id); - } - for (String depId : depIds) { - CloudifyExecutionList exeList = restClient.getExecutions(depId); - itemList.addAll(exeList.items); - } - // Filter down to specified status as needed - if (status != null) { - itemList.removeIf(ce -> !status.equals(ce.status)); - } - itemList.sort(executionComparator); - - // Paginate - final int pageNum = getRequestPageNumber(request); - final int pageSize = getRequestPageSize(request); - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - // Shrink if needed - if (totalItems > pageSize) { - itemList = getPageOfList(pageNum, pageSize, itemList); - } - result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception t) { - result = new RestResponseError("getExecutionsByPage failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Gets the specified execution for one deployment. - * - * It's not clear why the deployment ID is needed. - * - * @param execution_id - * Execution ID (path variable) - * @param deployment_id - * Deployment ID (query parameter) - * @param request - * HttpServletRequest - * @return CloudifyExecutionList - * @throws JsonProcessingException - * on serialization failure - */ - @RequestMapping(value = {EXECUTIONS_PATH + "/{id}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getExecutionByIdAndDeploymentId(@PathVariable("id") String execution_id, - @RequestParam("deployment_id") String deployment_id, HttpServletRequest request) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getExecutions(deployment_id); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to create an execution based on a deployment. - * - * @param request - * HttpServletRequest - * @param execution - * Execution model - * @return Information about the execution - * @throws JsonProcessingException - * on serialization failure - */ - @RequestMapping(value = {EXECUTIONS_PATH}, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String startExecution(HttpServletRequest request, @RequestBody CloudifyExecutionRequest execution) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.startExecution(execution); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("startExecution failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Cancels an execution. - * - * @param id - * Execution ID - * @param deploymentId - * Deployment ID (not clear why this is needed) - * @param action - * Action to perform (not clear why this is needed) - * @param request - * HttpServletRequest - * @param response - * HttpServletRequest - * @return Passes through HTTP status code from remote endpoint; no body on success - * @throws JsonProcessingException - * on serialization failure - */ - @RequestMapping(value = {EXECUTIONS_PATH + "/{id}"}, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String cancelExecution(@PathVariable("id") String id, - @RequestParam(value = "deployment_id") String deploymentId, @RequestParam(value = "action") String action, - HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - int code = restClient.cancelExecution(id, deploymentId, action); - response.setStatus(code); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("cancelExecution failed on ID " + id, t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - if (result == null) { - return null; - } else { - return objectMapper.writeValueAsString(result); - } - } -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyEvent; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * Controller for Cloudify features: blueprints, deployments, executions. + * Methods serve Ajax requests made by Angular scripts on pages that show + * content. + */ +@Controller +@RequestMapping("/") +public class CloudifyController extends DashboardRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyController.class); + private CloudifyClient restClient; + + /** + * Enum for selecting an item type. + */ + public enum CloudifyDataItem { + BLUEPRINT, DEPLOYMENT, EXECUTION, TENANT; + } + + private static Date begin; + private static Date end; + private static final String BLUEPRINTS_PATH = "blueprints"; + private static final String VIEW_BLUEPRINTS_PATH = "viewblueprints"; + private static final String DEPLOYMENTS_PATH = "deployments"; + private static final String EXECUTIONS_PATH = "executions"; + private static final String TENANTS_PATH = "tenants"; + private static final String NODE_INSTANCES_PATH = "node-instances"; + private static final String UPDATE_DEPLOYMENT_PATH = "update-deployment"; + private static final String SECRETS_PATH = "secrets"; + private static final String EVENTS_PATH = "events"; + private static final String DEP_TENANT_STATUS = "deployment-status"; + + /** + * Supports sorting blueprints by ID + */ + private static Comparator blueprintComparator = new Comparator() { + @Override + public int compare(CloudifyBlueprint o1, CloudifyBlueprint o2) { + return o1.id.compareTo(o2.id); + } + }; + + /** + * Supports sorting deployments by ID + */ + private static Comparator deploymentComparator = new Comparator() { + @Override + public int compare(CloudifyDeployment o1, CloudifyDeployment o2) { + return o1.id.compareTo(o2.id); + } + }; + + /** + * Supports sorting events by timestamp + */ + private static Comparator eventComparator = new Comparator() { + @Override + public int compare(CloudifyEvent o1, CloudifyEvent o2) { + return o1.reported_timestamp.compareTo(o2.reported_timestamp); + } + }; + + /** + * Supports sorting executions by timestamp + */ + private static Comparator executionComparator = new Comparator() { + @Override + public int compare(CloudifyExecution o1, CloudifyExecution o2) { + return o1.created_at.compareTo(o2.created_at); + } + }; + /** + * Gets one page of objects and supporting information via the REST client. + * On success, returns a PaginatedRestResponse object as String. + * + * @param option + * Specifies which item list type to get + * @param pageNum + * Page number of results + * @param pageSize + * Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception + * On any error; e.g., Network failure. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getItemListForPage(long userId, CloudifyDataItem option, int pageNum, int pageSize) + throws Exception { + if (this.restClient == null) { + this.restClient = getCloudifyRestClient(userId); + } + List itemList = null; + switch (option) { + /* + case BLUEPRINT: + itemList = restClient.getBlueprints().items; + Collections.sort(itemList, blueprintComparator); + break; + case DEPLOYMENT: + itemList = restClient.getDeployments().items; + Collections.sort(itemList, deploymentComparator); + break; + */ + case TENANT: + itemList = restClient.getTenants().items; + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); + throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + } +/* + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + String aicPrimTenant = + getAppProperties().getProperty(DashboardProperties.AIC_TENANT_PRIM); + + for (CloudifyTenant ct: (List)itemList) { + if ( ct.name.equals(cloudPrimTenant) ) { + ct.dName = aicPrimTenant; + } else { + ct.dName = ct.name; + } + } + */ + // Shrink if needed + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + + /** + * Gets one page of the specified items. This method traps exceptions and + * constructs an appropriate JSON block to report errors. + * + * @param request + * Inbound request + * @param option + * Item type to get + * @return JSON with one page of objects; or an error. + */ + protected String getItemListForPageWrapper(HttpServletRequest request, CloudifyDataItem option) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("getItemListForPageWrapper: Failed to get application user"); + int pageNum = getRequestPageNumber(request); + int pageSize = getRequestPageSize(request); + outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = null; + if (ex instanceof HttpStatusCodeException) + result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + else + result = new RestResponseError("Failed to get " + option.name(), ex); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } + return outboundJson; + } + + /** + * Serves one page of blueprints + * + * @param request + * HttpServletRequest + * @return List of CloudifyBlueprint objects + */ + @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getBlueprintsByPage(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, CloudifyDataItem.BLUEPRINT); + postLogAudit(request); + return json; + } + + /** + * Serves one page of deployments + * + * @param request + * HttpServletRequest + * @return List of CloudifyDeployment objects + */ + @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDeploymentsByPage(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, CloudifyDataItem.DEPLOYMENT); + postLogAudit(request); + return json; + } + + /** + * gets the tenants list + * + * @param request + * HttpServletRequest + * @return List of CloudifyDeployment objects + */ + @RequestMapping(value = { TENANTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getTenants(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, CloudifyDataItem.TENANT); + postLogAudit(request); + return json; + } + + /** + * Gets the specified blueprint metadata. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @return Blueprint as JSON; or error. + * @throws Exception + * on serialization error + * + */ + @RequestMapping(value = { BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getBlueprintById(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = true) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + restClient = getCloudifyRestClient(request); + result = restClient.getBlueprint(id, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintById caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintById caught exception"); + result = new RestResponseError("getBlueprintById failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the specified blueprint content for viewing. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @return Blueprint as YAML; or error. + * @throws Exception + * on serialization error + * + */ + @RequestMapping(value = { + VIEW_BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/yaml") + @ResponseBody + public String viewBlueprintContentById(@PathVariable("id") String id, HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + restClient = getCloudifyRestClient(request); + result = restClient.viewBlueprint(id); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "viewBlueprintContentById caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "viewBlueprintContentById caught exception"); + result = new RestResponseError("getBlueprintContentById failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Processes request to upload a blueprint from a remote server. + * + * @param request + * HttpServletRequest + * @param blueprint + * Cloudify blueprint + * @return Blueprint as uploaded; or error. + * @throws Exception + * on serialization error + */ + @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String uploadBlueprint(HttpServletRequest request, @RequestBody CloudifyBlueprintUpload blueprint) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.uploadBlueprint(blueprint); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Uploading blueprint failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "uploadBlueprint caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Uploading blueprint failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "uploadBlueprint caught exception"); + result = new RestResponseError("uploadBlueprint failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Deletes the specified blueprint. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return No content on success; error on failure. + * @throws Exception + * On serialization failure + */ + @RequestMapping(value = { BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteBlueprint(@PathVariable("id") String id, HttpServletRequest request, + HttpServletResponse response) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + int code = restClient.deleteBlueprint(id); + response.setStatus(code); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + result = new RestResponseError("deleteBlueprint failed on ID " + id, t); + } finally { + postLogAudit(request); + } + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the specified deployment. + * + * @param id + * Deployment ID + * @param request + * HttpServletRequest + * @return Deployment for the specified ID; error on failure. + * @throws Exception + * On serialization failure + * + */ + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDeploymentById(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = false) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + if (tenant != null && tenant.length() > 0) { + result = restClient.getDeployment(id, tenant); + } else { + result = restClient.getDeployment(id); + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + result = new RestResponseError("getDeploymentById failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Query status and tenant info for deployments + * + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { DEP_TENANT_STATUS }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String getTenantStatusForService( HttpServletRequest request, + @RequestBody String[] serviceList) + throws Exception { + preLogAudit(request); + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getControllerRestClient: Failed to get application user"); + /* + 1) Get all the tenant names + 2) Get the deployment IDs per tenant for all the tenants, aggregate the deployments list + 3) Get the input deployments list (screen input), filter the deployments list from step#2 + 4) For each item in the list from step#3, get the execution status info and generate the final response + */ + ECTransportModel result = null; + HashMap resultMap = new HashMap(); + List tenantList = new ArrayList(); + List cfyExecList = new ArrayList(); + try { + CloudifyClient restClient = getCloudifyRestClient(request); + List cldfyTen = restClient.getTenants().items; + for (CloudifyTenant ct: (List)cldfyTen) { + result = restClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList)result).items); + } + result = null; + List currSrvcTenants = new ArrayList(); + + for (String serviceId : serviceList) { + for (CloudifyDeployedTenant deplTen: tenantList) { + if (serviceId.equals(deplTen.id)) { + currSrvcTenants.add(deplTen); + break; + } + } + } + // Get concise execution status for each of the tenant deployment items + boolean isHelmType = false; + boolean helmStatus = false; + for (CloudifyDeployedTenant deplItem: currSrvcTenants) { + CloudifyExecutionList execResults = restClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); + isHelmType = false; + helmStatus = false; + CloudifyBlueprintList bpList = restClient.getBlueprint(deplItem.id, deplItem.tenant_name); + Map bpPlan = bpList.items.get(0).plan; + Map workflows = (Map)bpPlan.get("workflows"); + Map pluginInfo = ((List>)bpPlan.get("deployment_plugins_to_install")).get(0); + if (pluginInfo.get("name").equals("helm-plugin") ) { + isHelmType = true; + } + if (workflows.containsKey("status")) { + helmStatus = true; + } + /* + for (CloudifyExecution cfyExec: execResults.items) { + if (cfyExec.workflow_id.equalsIgnoreCase("create_deployment_environment")) { + Map pluginInfo = ((List>)cfyExec.parameters.get("deployment_plugins_to_install")).get(0); + if (pluginInfo.get("name").equals("helm-plugin") ) { + isHelmType = true; + } + } + } + */ + for (CloudifyExecution cfyExec: execResults.items) { + if (cfyExec.workflow_id.equalsIgnoreCase("install")) { + cfyExec.is_helm = isHelmType; + cfyExec.helm_status = helmStatus; + cfyExecList.add(cfyExec); + } + } + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); + result = new RestResponseError("getTenantStatusForService failed", t); + } finally { + postLogAudit(request); + } + + return objectMapper.writeValueAsString(cfyExecList); + } + + /** + * Processes request to create a deployment based on a blueprint. + * + * @param request + * HttpServletRequest + * @param deployment + * Deployment to upload + * @return Body of deployment; error on failure + * @throws Exception + * On serialization failure + */ + @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String createDeployment(HttpServletRequest request, @RequestBody CloudifyDeploymentRequest deployment) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.createDeployment(deployment); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Creating deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Creating deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); + result = new RestResponseError("createDeployment failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Deletes the specified deployment. + * + * @param id + * Deployment ID + * @param ignoreLiveNodes + * Boolean indicator whether to force a delete in case of live + * nodes + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return Passes thru HTTP status code from remote endpoint; no body on + * success + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { + DEPLOYMENTS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDeployment(@PathVariable("id") String id, + @RequestParam(value = "ignore_live_nodes", required = false) Boolean ignoreLiveNodes, + HttpServletRequest request, HttpServletResponse response) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + int code = restClient.deleteDeployment(id, ignoreLiveNodes == null ? false : ignoreLiveNodes); + response.setStatus(code); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + result = new RestResponseError("deleteDeployment failed on ID " + id, t); + } finally { + postLogAudit(request); + } + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); + } + + /** + * Gets and serves one page of executions: + *
    + *
  1. Gets all deployments; OR uses the specified deployment ID if the + * query parameter is present + *
  2. Gets executions for each deployment ID + *
  3. Sorts by execution ID + *
  4. Reduces the list to the page size (if needed) + *
  5. If the optional request parameter "status" is present, reduces the + * list to the executions with that status. + *
+ * + * @param request + * HttpServletRequest + * @param deployment_id + * Optional request parameter; if found, only executions for that + * deployment ID are returned. + * @param status + * Optional request parameter; if found, only executions with + * that status are returned. + * @return List of CloudifyExecution objects + * @throws Exception + * on serialization failure + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getExecutionsByPage(HttpServletRequest request, + @RequestParam(value = "deployment_id", required = false) String deployment_id, + @RequestParam(value = "status", required = false) String status, + @RequestParam(value = "tenant", required = false) String tenant) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + List itemList = new ArrayList(); + CloudifyClient restClient = getCloudifyRestClient(request); + List depIds = new ArrayList<>(); + if (deployment_id == null) { + CloudifyDeploymentList depList = restClient.getDeployments(); + for (CloudifyDeployment cd : depList.items) + depIds.add(cd.id); + } else { + depIds.add(deployment_id); + } + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + for (String depId : depIds) { + CloudifyExecutionList exeList = restClient.getExecutions(depId, tenant); + itemList.addAll(exeList.items); + } + // Filter down to specified status as needed + if (status != null) { + Iterator exeIter = itemList.iterator(); + while (exeIter.hasNext()) { + CloudifyExecution ce = exeIter.next(); + if (!status.equals(ce.status)) + exeIter.remove(); + } + } + Collections.sort(itemList, executionComparator); + + // Paginate + final int pageNum = getRequestPageNumber(request); + final int pageSize = getRequestPageSize(request); + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + // Shrink if needed + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + result = new RestResponsePage<>(totalItems, pageCount, itemList); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); + result = new RestResponseError("getExecutionsByPage failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the specified execution for one deployment. + * + * It's not clear why the deployment ID is needed. + * + * @param execution_id + * Execution ID (path variable) + * @param deployment_id + * Deployment ID (query parameter) + * @param request + * HttpServletRequest + * @return CloudifyExecutionList + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getExecutionByIdAndDeploymentId(@PathVariable("id") String execution_id, + @RequestParam("deployment_id") String deployment_id, + @RequestParam(value = "tenant", required = false) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.getExecutions(deployment_id, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions " + execution_id + " for deployment " + deployment_id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions " + execution_id + " for deployment " + deployment_id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the execution events for specified execution ID. + * + * + * @param execution_id + * Execution ID (request parameter) + * @param tenant + * tenant name (query parameter) + * @param request + * HttpServletRequest + * @return CloudifyExecutionList + * @throws Exception + * on serialization failure + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { EVENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getExecutionEventsById(@RequestParam(value = "execution_id", required = false) String execution_id, + @RequestParam(value = "logType", required = false) String isLogEvent, + @RequestParam(value = "tenant", required = false) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + CloudifyEventList eventsList = null; + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(request); + eventsList = restClient.getEventlogs(execution_id, tenant); + // Filter down to specified event type as needed + List itemList = eventsList.items; + if (!isLogEvent.isEmpty() && isLogEvent.equals("false")) { + Iterator exeIter = itemList.iterator(); + while (exeIter.hasNext()) { + CloudifyEvent ce = exeIter.next(); + if (ce.type.equals("cloudify_log")) { + exeIter.remove(); + } + } + } + Collections.sort(itemList, eventComparator); + Collections.reverse(itemList); + final int pageNum = getRequestPageNumber(request); + final int pageSize = getRequestPageSize(request); + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + // Shrink if needed + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + result = new RestResponsePage<>(totalItems, pageCount, itemList); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions " + execution_id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionEventsById caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions " + execution_id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionEventsById failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the cloudify secret data for the specified secret name. + * + * + * @param secret_name + * Secret name (path variable) + * @param request + * HttpServletRequest + * @return CloudifySecret + * @throws Exception + * on serialization failure + */ + /* + @RequestMapping(value = { SECRETS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getSecrets( + @RequestParam(value = "tenant") String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + IControllerRestClient restClient = getControllerRestClient(); + result = restClient.getSecrets(tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting secrets failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting secrets failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); + result = new RestResponseError("getSecret failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the cloudify secret data for the specified secret name. + * + * + * @param secret_name + * Secret name (path variable) + * @param request + * HttpServletRequest + * @return CloudifySecret + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { SECRETS_PATH + "/{secret_name}"}, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getSecret(@PathVariable("secret_name") String secret_name, + @RequestParam(value = "tenant") String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.getSecret(secret_name, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting secret for name " + secret_name + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting secret for name " + secret_name + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); + result = new RestResponseError("getSecret failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Processes request to create secrets in cloudify manager. + * + * @param request + * HttpServletRequest + * @param execution + * Execution model + * @return Information about the execution + * @throws Exception + * on serialization failure + */ +/* + @RequestMapping(value = { SECRETS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String createSecret(HttpServletRequest request, @RequestBody CloudifySecretUpload secret) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + IControllerRestClient restClient = getControllerRestClient(request); + result = restClient.createSecret(secret); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Starting execution failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "startExecution caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Starting execution failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "startExecution caught exception"); + result = new RestResponseError("startExecution failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + */ + /** + * Processes request to create an execution based on a deployment. + * + * @param request + * HttpServletRequest + * @param execution + * Execution model + * @return Information about the execution + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String startExecution(HttpServletRequest request, @RequestBody CloudifyExecutionRequest execution) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + if (!execution.workflow_id.equals("status") && !execution.getParameters().containsKey("node_instance_id")) { + // get the node instance ID for the deployment + String nodeInstId = ""; + CloudifyNodeInstanceIdList nodeInstList = + restClient.getNodeInstanceId(execution.getDeployment_id(), execution.getTenant()); + if (nodeInstList != null) { + nodeInstId = nodeInstList.items.get(0).id; + } + Map inParms = execution.getParameters(); + inParms.put("node_instance_id", nodeInstId); + execution.setParameters(inParms); + } + result = restClient.startExecution(execution); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Starting execution failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "startExecution caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Starting execution failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "startExecution caught exception"); + result = new RestResponseError("startExecution failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Processes request to create an execution based on a deployment. + * + * @param request + * HttpServletRequest + * @param execution + * Execution model + * @return Information about the execution + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { UPDATE_DEPLOYMENT_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String updateDeployment(HttpServletRequest request, @RequestBody CloudifyDeploymentUpdateRequest execution) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.updateDeployment(execution); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + result = new RestResponseError("updateDeployment failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Cancels an execution. + * + * @param id + * Execution ID + * @param deploymentId + * Deployment ID (not clear why this is needed) + * @param action + * Action to perform (not clear why this is needed) + * @param request + * HttpServletRequest + * @param response + * HttpServletRequest + * @return Passes thru HTTP status code from remote endpoint; no body on + * success + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String cancelExecution( + @RequestHeader HttpHeaders headers, + @PathVariable("id") String id, + @RequestBody Map parameters, + HttpServletRequest request, HttpServletResponse response) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + List tenant = null; + try { + tenant = headers.get("tenant"); + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.cancelExecution(id, parameters, tenant.get(0)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + result = new RestResponseError("cancelExecution failed on ID " + id, t); + } finally { + postLogAudit(request); + } + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the specified node-instance-id content for viewing. + * + * @param id + * deployment ID + * @param id + * node ID + * @param request + * HttpServletRequest + * @return Blueprint as YAML; or error. + * @throws Exception + * on serialization error + * + */ + @RequestMapping(value = { + NODE_INSTANCES_PATH + "/{deploymentId}/{nodeId}" }, method = RequestMethod.GET, produces = "application/yaml") + @ResponseBody + public String getNodeInstanceId(@PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant", required = true) String tenant, + @PathVariable("nodeId") String nodeId, HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.getNodeInstanceId(deploymentId, nodeId, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + " and nodeId " + nodeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + " and nodeId " + nodeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); + result = new RestResponseError("getNodeInstanceId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}/revisions"}, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDeploymentRevisions(@PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant") String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(request); + result = restClient.getNodeInstanceVersion(deploymentId, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java new file mode 100644 index 0000000..3c17288 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java @@ -0,0 +1,1226 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Scanner; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.ccsdk.dashboard.domain.EcdComponent; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.model.RestResponseSuccess; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResource; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResourceLinks; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.model.inventory.Blueprint; +import org.onap.ccsdk.dashboard.model.inventory.BlueprintResponse; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeServiceMap; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.ccsdk.dashboard.service.ControllerEndpointService; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +@RestController +@RequestMapping("/ecomp-api") +public class CommonApiController extends DashboardRestrictedBaseController { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); + + private static final String COMPONENTS_PATH = "components"; + private static final String DEPLOYMENTS_PATH = "deployments"; + private static final String SERVICE_TYPES_PATH = "blueprints"; + private static final String EXECUTIONS_PATH = "executions"; + private static final String API_HELP = "docs"; + private static final String DOCS_FILE_NAME = "ecompApiHelp.txt"; + private static final String DEP_IDS_FOR_TYPE = "deployments/typeIds"; + private static final String DEP_TENANT_STATUS = "deployment-status"; + private static final String TENANTS_PATH = "tenants"; + + @Autowired + private ControllerEndpointService controllerEndpointService; + + /** + * Enum for selecting an item type. + */ + public enum InventoryDataItem { + SERVICES, SERVICE_TYPES, SERVICES_GROUPBY; + } + + private static Date begin, end; + + @RequestMapping(value = "/api-docs", method = RequestMethod.GET, produces = "application/json") + public Resource apiDocs() { + return new ClassPathResource("swagger.json"); + } + + @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.POST, produces = "application/json") + public String insertComponent(HttpServletRequest request, @RequestBody EcdComponent newComponent) + throws Exception { + String outboundJson = null; + controllerEndpointService.insertComponent(newComponent); + RestResponseSuccess success = new RestResponseSuccess("Inserted new component with name " + newComponent.getCname()); + outboundJson = objectMapper.writeValueAsString(success); + return outboundJson; + } + + @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + public String getComponents(HttpServletRequest request) throws Exception { + List result = controllerEndpointService.getComponents(); + return objectMapper.writeValueAsString(result); + + } + + /** + * gets the tenants list + * + * @param request + * HttpServletRequest + * @return List of CloudifyDeployment objects + */ + @SuppressWarnings("rawtypes") + @RequestMapping(value = { TENANTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getTenants(HttpServletRequest request) throws Exception { + preLogAudit(request); + CloudifyClient restClient = getCloudifyRestClient(); + List itemList = restClient.getTenants().items; + final int totalItems = itemList.size(); + final int pageSize = 20; + final int pageNum = 1; + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + /** + * Query status and tenant info for deployments + * + */ + @RequestMapping(value = { DEP_TENANT_STATUS }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String getTenantStatusForService( HttpServletRequest request, + @RequestBody String[] serviceList) + throws Exception { + preLogAudit(request); + /* + 1) Get all the tenant names + 2) Get the deployment IDs per tenant for all the tenants, aggregate the deployments list + 3) Get the input deployments list (screen input), filter the deployments list from step#2 + 4) For each item in the list from step#3, get the execution status info and generate the final response + */ + ECTransportModel result = null; + HashMap resultMap = new HashMap(); + List tenantList = new ArrayList(); + List cfyExecList = new ArrayList(); + try { + CloudifyClient restClient = getCloudifyRestClient(); + List cldfyTen = restClient.getTenants().items; + for (CloudifyTenant ct: (List)cldfyTen) { + result = restClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList)result).items); + } + result = null; + List currSrvcTenants = new ArrayList(); + + for (String serviceId : serviceList) { + for (CloudifyDeployedTenant deplTen: tenantList) { + if (serviceId.equals(deplTen.id)) { + currSrvcTenants.add(deplTen); + break; + } + } + } + // Get concise execution status for each of the tenant deployment items + for (CloudifyDeployedTenant deplItem: currSrvcTenants) { + CloudifyExecutionList execResults = restClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); + for (CloudifyExecution cfyExec: execResults.items) { + if (cfyExec.workflow_id.equalsIgnoreCase("install")) { + cfyExecList.add(cfyExec); + } + } + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); + result = new RestResponseError("getTenantStatusForService failed", t); + } finally { + postLogAudit(request); + } + + return objectMapper.writeValueAsString(cfyExecList); + } + + @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.POST, produces = "application/json") + public String createBlueprint(HttpServletRequest request, + @RequestBody ServiceTypeUploadRequest serviceTypeUplReq ) throws Exception { + String json = null; + try { + Blueprint.parse(serviceTypeUplReq.getBlueprintTemplate()); + InventoryClient inventoryClient = getInventoryClient(); + Collection serviceIds = new ArrayList(); + Collection vnfTypes = new ArrayList(); + Collection serviceLocations = new ArrayList(); + Optional asdcServiceId = null; + Optional asdcResourceId = null; + Optional asdcServiceURL = null; + + ServiceTypeRequest invSrvcTypeReq = + new ServiceTypeRequest(serviceTypeUplReq.owner, serviceTypeUplReq.typeName, + serviceTypeUplReq.typeVersion, serviceTypeUplReq.blueprintTemplate, + serviceTypeUplReq.application, serviceTypeUplReq.component, serviceIds, + vnfTypes, serviceLocations, asdcServiceId, asdcResourceId, asdcServiceURL); + ServiceType response = inventoryClient.addServiceType(invSrvcTypeReq); + //RestResponseSuccess success = new RestResponseSuccess("Uploaded new blueprint with name " + serviceTypeUplReq.typeName); + json = objectMapper.writeValueAsString(response); + } catch (BlueprintParseException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.GET, produces = "application/json") + public String getBlueprintsByPage(HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("name"), + request.getParameter("_include")); + postLogAudit(request); + return json; + } + + @RequestMapping(value = { SERVICE_TYPES_PATH + "/findByName" }, method = RequestMethod.GET, produces = "application/json") + public String queryBlueprintFilter(HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("name"), + request.getParameter("_include")); + postLogAudit(request); + return json; + } + + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}"}, method = RequestMethod.GET, produces = "application/json") + public String getDeploymentsByPage(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, deploymentId, + request.getParameter("_include")); + postLogAudit(request); + return json; + } + + @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + public String getAllDeploymentsByPage(HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, request.getParameter("deploymentId"), + request.getParameter("_include")); + postLogAudit(request); + return json; + } + + /** + * Gets one page of the specified items. This method traps exceptions and + * constructs an appropriate JSON block to report errors. + * + * @param request + * Inbound request + * @param option + * Item type to get + * @return JSON with one page of objects; or an error. + */ + protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, String searchBy, + String filters) { + preLogAudit(request); + + String outboundJson = null; + try { + int pageNum = getRequestPageNumber(request); + int pageSize = getRequestPageSize(request); + outboundJson = getItemListForPage(option, pageNum, pageSize, searchBy, filters); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "ECOMP Inventory"); + MDC.put("TargetServiceName", "ECOMP Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = null; + if (ex instanceof HttpStatusCodeException) + result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + else + result = new RestResponseError("Failed to get " + option.name(), ex); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } finally { + postLogAudit(request); + } + return outboundJson; + } + + /** + * Gets one page of objects and supporting information via the REST client. + * On success, returns a PaginatedRestResponse object as String. + * + * @param option + * Specifies which item list type to get + * @param pageNum + * Page number of results + * @param pageSize + * Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception + * On any error; e.g., Network failure. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getItemListForPage(InventoryDataItem option, int pageNum, int pageSize, String searchBy, + String filters) throws Exception { + + InventoryClient inventoryClient = getInventoryClient(); + String outboundJson = ""; + List itemList = null; + + switch (option) { + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + if (searchBy != null) { + itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) + .collect(Collectors.toList()); + } + // Get the tenant names for all the deployments from Cloudify/API handler + ECTransportModel result = null; + List tenantList = new ArrayList(); + try { + CloudifyClient restClient = getCloudifyRestClient(); + List cldfyTen = restClient.getTenants().items; + for (CloudifyTenant ct: (List)cldfyTen) { + result = restClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList)result).items); + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantInfoFromDeploy caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + result = new RestResponseError("getTenantInfoFromDeploy failed", t); + } finally { + + } + + for (Service depl: (List)itemList) { + for (CloudifyDeployedTenant deplTen: tenantList) { + if (depl.getDeploymentRef().equals(deplTen.id)) { + depl.setTenant(deplTen.tenant_name); + break; + } + } + } + break; + case SERVICE_TYPES: + ServiceTypeQueryParams serviceQueryParams = null; + serviceQueryParams = new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); + + itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); + List filterList = new ArrayList(); + + if (searchBy != null && searchBy.length() > 1) { + itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) + .collect(Collectors.toList()); + } + if (filters != null && filters.length() > 0) { + String filterArr[] = filters.split(","); + for (ServiceType bp : (List) itemList) { + BlueprintResponse bpOut = new BlueprintResponse(); + for (String fltr : filterArr) { + switch (fltr) { + case "typeName": + bpOut.setTypeName(bp.getTypeName()); + break; + case "typeId": + bpOut.setTypeId(bp.getTypeId().get()); + break; + case "typeVersion": + bpOut.setTypeVersion(bp.getTypeVersion()); + break; + default: + break; + } + } + filterList.add(bpOut); + } + if (filterList.size() > 0) { + itemList.clear(); + itemList.addAll(filterList); + } + } + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + } + // Shrink if needed + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + outboundJson = objectMapper.writeValueAsString(model); + + return outboundJson; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getBlueprintTypeId(String searchBy, Optional version, String typeId) throws Exception { + + InventoryClient inventoryClient = getInventoryClient(); + ServiceTypeQueryParams serviceQueryParams = null; + + if (version.isPresent()) { + serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).onlyLatest(false).build(); + } else { + serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).build(); + } + + List itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); + + if (version.isPresent()) { + itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(version.get().toString())) + .collect(Collectors.toList()); + } + Optional bpId = Optional.of(""); + if (typeId != null && typeId.equals("typeId")) { + ServiceType item = (ServiceType) ((List) itemList).get(0); + bpId = item.getTypeId(); + } + return bpId.get(); + } + + /** + * Query the installed helm package revisions from cloudify + * + * @param deploymentId + * @param tenant + * @param request + * @return + * @throws Exception + */ + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}/revisions"}, method = RequestMethod.GET, produces = "application/json") + public String getDeploymentRevisions(@PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant") String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(); + result = restClient.getNodeInstanceVersion(deploymentId, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Query inputs used to create a deployment + * + * @param deploymentId + * @param tenant + * @param request + * @return + * @throws Exception + */ + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}/inputs"}, method = RequestMethod.GET, produces = "application/json") + public String getDeploymentInputs(@PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant") String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(); + result = restClient.getDeploymentInputs(deploymentId, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Create an upgrade/rollback workflow execution for a deployment. + * + * @param request + * HttpServletRequest + * @param execution + * Execution model + * @return Information about the execution + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}"}, method = RequestMethod.PUT, produces = "application/json") + public String modifyDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request, InputStream upgParams) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + CloudifyClient restClient = getCloudifyRestClient(); + String nodeInstId = ""; + Map parameters = + objectMapper.readValue(upgParams, new TypeReference>() {}); + String tenant = (String) parameters.get("tenant"); + String workflow = (String) parameters.get("workflow"); + parameters.remove("tenant"); + parameters.remove("workflow"); + // get the node instance ID for the deployment + CloudifyNodeInstanceIdList nodeInstList = restClient.getNodeInstanceId(deploymentId, tenant); + if (nodeInstList != null) { + nodeInstId = nodeInstList.items.get(0).id; + } + parameters.put("node_instance_id", nodeInstId); + CloudifyExecutionRequest execution = + new CloudifyExecutionRequest(deploymentId, workflow, false, false, tenant, parameters); + result = restClient.startExecution(execution); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + result = new RestResponseError("updateDeployment failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + @RequestMapping(value = { SERVICE_TYPES_PATH + "/{typeid}" + "/services" }, method = RequestMethod.GET, produces = "application/json") + public String getServicesForType( HttpServletRequest request, + @PathVariable("typeid") String typeId) + throws Exception { + preLogAudit(request); + List result = new ArrayList(); + InventoryClient inventoryClient = getInventoryClient(); + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); + result.add(srvcMap); + return objectMapper.writeValueAsString(result); + } + + @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.POST, produces = "application/json") + public String createDeployment( HttpServletRequest request, + @RequestBody DeploymentInput deploymentRequestObject) + throws Exception { + preLogAudit(request); + String json = null; + StringBuffer status = new StringBuffer(); + //Optional bpId = Optional.empty(); + Optional bpVersion = null; + String srvcTypeId = null; + String bpName = deploymentRequestObject.getBlueprintName(); + String cName = deploymentRequestObject.getComponent(); + String tag = deploymentRequestObject.getTag(); + String depName = cName+"_"+tag; + + if (deploymentRequestObject.getBlueprintVersion().isPresent()) { + bpVersion = deploymentRequestObject.getBlueprintVersion(); + } + if (deploymentRequestObject.getBlueprintId().isPresent()) { + srvcTypeId = deploymentRequestObject.getBlueprintId().get(); + //srvcTypeId = bpId.get(); + } + if (srvcTypeId == null) { + // get the serviceTypeId from inventory using the blueprint name + try { + srvcTypeId = getBlueprintTypeId(bpName, bpVersion, "typeId"); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "ECOMP Inventory"); + MDC.put("TargetServiceName", "ECOMP Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting blueprint ID failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = null; + if (ex instanceof HttpStatusCodeException) + result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + else + result = new RestResponseError("Failed to get blueprint", ex); + try { + json = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + return json; + } finally { + postLogAudit(request); + } + } + DeploymentHandlerClient deploymentHandlerClient = null; + try { + deploymentHandlerClient = getDeploymentHandlerClient(); + DeploymentResponse resp = + deploymentHandlerClient.putDeployment( + depName, deploymentRequestObject.getTenant(), + new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs())); + DeploymentResponseLinks deplLinks = resp.getLinks(); + String deplStatus = deplLinks.getStatus(); + if (!deplStatus.contains("cfy_tenant")) { + deplStatus = deplStatus + "?cfy_tenant_name=" + deploymentRequestObject.getTenant(); + } + String self = request.getRequestURL().append("/").append(depName).toString(); + status.append(self).append("/executions?tenant=").append(deploymentRequestObject.getTenant()); + DeploymentResource deplRsrc = new DeploymentResource(depName, + new DeploymentResourceLinks(self, deplStatus, status.toString())); + JSONObject statObj = new JSONObject(deplRsrc); + json = statObj.toString(); + } catch (BadRequestException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServiceAlreadyExistsException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServerErrorException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}/update"}, method = RequestMethod.PUT, produces = "application/json") + public String updateDeployment( @PathVariable("deploymentId") String deploymentId, HttpServletRequest request, + @RequestBody DeploymentInput deploymentRequestObject) + throws Exception { + preLogAudit(request); + String json = null; + String srvcTypeId = ""; + Optional bpVersion = null; + String bpName = deploymentRequestObject.getBlueprintName(); + if (deploymentRequestObject.getBlueprintVersion().isPresent()) { + bpVersion = deploymentRequestObject.getBlueprintVersion(); + } + // get the serviceTypeId from inventory using the blueprint name + try { + srvcTypeId = getBlueprintTypeId(bpName, bpVersion, "typeId"); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "ECOMP Inventory"); + MDC.put("TargetServiceName", "ECOMP Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting blueprint ID failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = null; + if (ex instanceof HttpStatusCodeException) + result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + else + result = new RestResponseError("Failed to get blueprint", ex); + try { + json = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + return json; + } finally { + postLogAudit(request); + } + DeploymentHandlerClient deploymentHandlerClient = null; + try { + deploymentHandlerClient = getDeploymentHandlerClient(); + json = objectMapper.writeValueAsString(deploymentHandlerClient.updateDeployment( + deploymentId, deploymentRequestObject.getTenant(), + new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs()))); + } catch (BadRequestException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServiceAlreadyExistsException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServerErrorException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Gets the executions for one deployment. + * + * + * @param deployment_id + * Deployment ID (query parameter) + * @param request + * HttpServletRequest + * @return CloudifyExecutionList + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}" + "/" + EXECUTIONS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getExecutionByDeploymentId( + @PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant", required = true) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String cloudPrimTenant = + getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); + if (tenant == null) { + tenant = cloudPrimTenant; + } + CloudifyClient restClient = getCloudifyRestClient(); + result = restClient.getExecutionsSummary(deploymentId, tenant); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Deletes the specified blueprint. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return status code on success; error on failure. + * @throws Exception + * On serialization failure + */ + @RequestMapping(value = { SERVICE_TYPES_PATH + "/{typeid}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, + HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = "{\"202\": \"OK\"}"; + try { + InventoryClient inventoryClient = getInventoryClient(); + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + if (srvcRefs != null && srvcRefs.totalCount > 0) { + throw new Exception("Services exist for the service type template, delete not permitted"); + } + inventoryClient.deleteServiceType(typeId); + } catch (ServiceTypeNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServiceTypeAlreadyDeactivatedException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("deleteBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Un-deploy an application or service + * + * @param deploymentId + * @param request + * @param tenant + * @param response + * @return + * @throws Exception + */ + @RequestMapping(value = { + DEPLOYMENTS_PATH + "/{deploymentId}" }, method = RequestMethod.DELETE, produces = "application/json") + public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, + @RequestParam("tenant") String tenant, HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = null; + StringBuffer status = new StringBuffer(); + try { + DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(); + deploymentHandlerClient.deleteDeployment(deploymentId, tenant); + String self = request.getRequestURL().toString().split("\\?")[0]; + status.append(self) + .append("/executions?tenant=") + .append(tenant); + DeploymentResource deplRsrc = + new DeploymentResource(deploymentId, + new DeploymentResourceLinks(self, "", status.toString())); + JSONObject statObj = new JSONObject(deplRsrc); + json = statObj.toString(); + } catch (BadRequestException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServerErrorException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DeploymentNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Cancels an execution. + * + * @param id + * Execution ID + * @param deploymentId + * Deployment ID (not clear why this is needed) + * @param action + * Action to perform (not clear why this is needed) + * @param request + * HttpServletRequest + * @param response + * HttpServletRequest + * @return Passes thru HTTP status code from remote endpoint; no body on + * success + * @throws Exception + * on serialization failure + */ + @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String cancelExecution( + @RequestHeader HttpHeaders headers, + @PathVariable("id") String id, + @RequestBody Map parameters, + HttpServletRequest request, HttpServletResponse response) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + List tenant = null; + try { + tenant = headers.get("tenant"); + CloudifyClient restClient = getCloudifyRestClient(); + result = restClient.cancelExecution(id, parameters, tenant.get(0)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + result = new RestResponseError("cancelExecution failed on ID " + id, t); + } finally { + postLogAudit(request); + } + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); + } + + private void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + // logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, + // APP_NAME); + } + + private void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java index 8350737..3aa7821 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java @@ -1,445 +1,483 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import com.fasterxml.jackson.core.JsonProcessingException; -import java.net.URI; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import javax.servlet.http.HttpServletRequest; - -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.RestResponsePage; -import org.onap.ccsdk.dashboard.rest.IControllerRestClient; -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.ccsdk.dashboard.model.RestResponseError; -import org.onap.ccsdk.dashboard.model.RestResponseSuccess; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.client.HttpStatusCodeException; - -/** - * Controller for Consul features: health checks of services, nodes, data - * centers. Methods serve Ajax requests made by Angular scripts on pages that - * show content. - */ -@Controller -@RequestMapping("/healthservices") -public class ConsulController extends DashboardRestrictedBaseController { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulController.class); - - /** - * Enum for selecting an item type. - */ - public enum ConsulDataItem { - SERVICE_INFO, SERVICE_HEALTH, NODES, DATACENTERS; - } - - private static final String NODES_PATH = "/nodes"; - private static final String SERVICES_PATH = "/services"; - - /** - * Supports sorting results by node name - */ - private static Comparator nodeHealthComparator = Comparator.comparing(o -> o.node); - - /** - * Supports sorting results by service name - */ - private static Comparator serviceHealthComparator = Comparator.comparing(o -> o.serviceName); - - /** - * Supports sorting results by service name - */ - private static Comparator serviceInfoComparator = Comparator.comparing(o -> o.name); - - /** - * Gets one page of objects and supporting information via the REST client. On - * success, returns a page of objects as String. - * - * @param option - * Specifies which item type to get - * @param pageNum - * Page number of results - * @param pageSize - * Number of items per browser page - * @return JSON block as String, see above. - * @throws DashboardControllerException, - * JsonProcessingException On any error; e.g., Network failure. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private String getItemListForPage(long userId, ConsulDataItem option, int pageNum, int pageSize) - throws DashboardControllerException, JsonProcessingException { - IControllerRestClient restClient = getControllerRestClient(userId); - List itemList; - switch (option) { - case NODES: - itemList = restClient.getNodes(); - itemList.sort(nodeHealthComparator); - break; - case DATACENTERS: - itemList = restClient.getDatacenters(); - break; - default: - throw new DashboardControllerException( - "getItemListForPage failed: unimplemented case: " + option.name()); - } - - // Shrink if needed - if (itemList.size() > pageSize) { - itemList = getPageOfList(pageNum, pageSize, itemList); - } - int pageCount = (int) Math.ceil((double) itemList.size() / pageSize); - RestResponsePage model = new RestResponsePage<>(itemList.size(), pageCount, itemList); - return objectMapper.writeValueAsString(model); - } - - /** - * Gets one page of the specified items. This method traps exceptions and - * constructs an appropriate JSON block to report errors. - * - * @param request - * Inbound request - * @param option - * Item type to get - * @return JSON with one page of objects; or an error. - */ - protected String getItemListForPageWrapper(HttpServletRequest request, ConsulDataItem option) { - String outboundJson; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { - throw new DashboardControllerException("getItemListForPageWrapper: Failed to get application user"); - } - int pageNum = getRequestPageNumber(request); - int pageSize = getRequestPageSize(request); - outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize); - } catch (Exception ex) { - // Remote service failed; build descriptive error message - logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception", ex); - RestResponseError result = new RestResponseError("Failed to get " + option.name(), ex); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } - return outboundJson; - } - - /** - * Serves all service details. - * - * @param request - * HttpServletRequest - * @return List of ConsulServiceInfo objects, as JSON - * @throws JsonProcessingException - * if serialization fails - */ - @RequestMapping(value = {SERVICES_PATH}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getServices(HttpServletRequest request) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - Object result; - try { - IControllerRestClient restClient = getControllerRestClient(request); - List itemList = restClient.getServices(); - itemList.sort(serviceInfoComparator); - result = itemList; - } catch (Exception t) { - result = new RestResponseError("getServices failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Serves service health details - not paginated. - * - * @param request - * HttpServletRequest - * @param serviceId - * Service ID - * @return List of ConsulServiceHealth objects as JSON - * @throws JsonProcessingException - * if serialization fails - */ - @RequestMapping(value = { - SERVICES_PATH + "/{serviceId}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getServiceHealthDetails(HttpServletRequest request, @PathVariable String serviceId) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - Object result; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getServiceHealth(serviceId); - } catch (Exception t) { - result = new RestResponseError("getServiceHealthDetails failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Serves service health historical data - not paginated. - * - * @param request - * HttpServletRequest - * @param serviceName - * Service name as path parameter - * @param start - * Earliest date-time as an ISO 8061 value, such as - * 2007-12-03T10:15:30+01:00 - * @param end - * Latest date-time as an ISO 8061 value, such as - * 2007-12-03T10:15:30+01:00 - * @return List of ConsulServiceHealth objects as JSON - * @throws JsonProcessingException - * if serialization fails - */ - @RequestMapping(value = {"/svchist/{serviceName}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getServiceHealthHistory(HttpServletRequest request, // - @PathVariable String serviceName, // - @RequestParam String start, // - @RequestParam String end) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - Object result = null; - try { - Instant startDateTime = Instant.parse(start); - Instant endDateTime = Instant.parse(end); - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getServiceHealthHistory(serviceName, startDateTime, endDateTime); - } catch (HttpStatusCodeException e) { - // Rare, but can happen - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - // Work around the hack to report no-match. - result = new RestResponseError("getServiceHealthHistory failed: " + t.getMessage()); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Serves one page of service health information by getting all service names, - * then iterating over them to get the health of each service. - * - * ECOMP-C does NOT provide an API to get the health of all services in one - * request. - * - * @param request - * HttpServletRequest - * @return List of ConsulServiceHealth objects, as JSON - * @throws JsonProcessingException - * on serialization exception - */ - @SuppressWarnings("unchecked") - @RequestMapping(value = {"/serviceshealth"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getServicesHealth(HttpServletRequest request) throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - List itemList = new ArrayList<>(); - IControllerRestClient restClient = getControllerRestClient(request); - List svcInfoList = restClient.getServices(); - for (ConsulServiceInfo csi : svcInfoList) { - List csh = restClient.getServiceHealth(csi.name); - itemList.addAll(csh); - } - itemList.sort(serviceHealthComparator); - // Paginate - final int pageNum = getRequestPageNumber(request); - final int pageSize = getRequestPageSize(request); - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - // Shrink if needed - if (totalItems > pageSize) { - itemList = getPageOfList(pageNum, pageSize, itemList); - } - result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception t) { - result = new RestResponseError("getServicesHealth failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Serves one page of node information. - * - * @param request - * HttpServletRequest - * @return List of ConsulNodeInfo objects, as JSON - */ - @RequestMapping(value = {NODES_PATH}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getNodesInfo(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - String json = getItemListForPageWrapper(request, ConsulDataItem.NODES); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return json; - } - - /** - * Serves node services health details - not paginated. - * - * @param request - * HttpServletRequest - * @param nodeName - * Node name - * @return List of ConsulServiceHealth objects as JSON - * @throws JsonProcessingException - * if serialization fails - */ - @RequestMapping(value = {NODES_PATH + "/{nodeName}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getNodeServicesHealth(HttpServletRequest request, @PathVariable String nodeName) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - Object result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - result = restClient.getNodeServicesHealth(nodeName); - } catch (Exception t) { - result = new RestResponseError("getNodeServicesHealth failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Serves one page of data centers health. - * - * @param request - * HttpServletRequest - * @return List of ConsulHealthStatus objects - */ - @RequestMapping(value = {"/datacenters"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDatacentersHealth(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - String json = getItemListForPageWrapper(request, ConsulDataItem.DATACENTERS); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return json; - } - - /** - * Processes request to register a service for health checks. - * - * @param request - * HttpServletRequest - * @param registration - * Consul service registration - * @return URI of the newly registered resource - * @throws JsonProcessingException - * on serialization error - */ - @RequestMapping(value = {"/register"}, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String registerService(HttpServletRequest request, @RequestBody ConsulHealthServiceRegistration registration) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - URI uri = restClient.registerService(registration); - result = new RestResponseSuccess(uri.toString()); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("registerService failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to deregister a service for health checks. - * - * @param request - * HttpServletRequest - * @param serviceName - * Consul service name to deregister - * @return Success or error indicator - * @throws JsonProcessingException - * on serialization error - */ - @RequestMapping(value = { - "/deregister" + "/{serviceName}"}, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String deregisterService(HttpServletRequest request, @PathVariable String serviceName) - throws JsonProcessingException { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - ECTransportModel result = null; - try { - IControllerRestClient restClient = getControllerRestClient(request); - int code = restClient.deregisterService(serviceName); - result = new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code)); - } catch (HttpStatusCodeException e) { - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { - result = new RestResponseError("deregisterService failed", t); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return objectMapper.writeValueAsString(result); - } -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration.EndpointCheck; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.model.RestResponseSuccess; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * Controller for Consul features: health checks of services, nodes, data + * centers. Methods serve Ajax requests made by Angular scripts on pages that + * show content. + */ +@Controller +@RequestMapping("/healthservices") +public class ConsulController extends DashboardRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulController.class); + + /** + * Enum for selecting an item type. + */ + public enum ConsulDataItem { + SERVICE_INFO, SERVICE_HEALTH, NODES, DATACENTERS; + } + + private static Date begin, end; + private static final String NODES_PATH = "/nodes"; + private static final String SERVICES_PATH = "/services"; + + /** + * Supports sorting results by node name + */ + private static Comparator nodeHealthComparator = new Comparator() { + @Override + public int compare(ConsulNodeInfo o1, ConsulNodeInfo o2) { + return o1.node.compareTo(o2.node); + } + }; + + /** + * Supports sorting results by service name + */ + private static Comparator serviceHealthComparator = new Comparator() { + @Override + public int compare(ConsulServiceHealth o1, ConsulServiceHealth o2) { + return o1.serviceName.compareTo(o2.serviceName); + } + }; + + /** + * Supports sorting results by service name + */ + private static Comparator serviceInfoComparator = new Comparator() { + @Override + public int compare(ConsulServiceInfo o1, ConsulServiceInfo o2) { + return o1.name.compareTo(o2.name); + } + }; + + /** + * Gets one page of objects and supporting information via the REST client. + * On success, returns a page of objects as String. + * + * @param option + * Specifies which item type to get + * @param pageNum + * Page number of results + * @param pageSize + * Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception + * On any error; e.g., Network failure. + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private String getItemListForPage(long userId, ConsulDataItem option, + int pageNum, int pageSize, String dc) throws Exception { + ConsulClient restClient = getConsulRestClient(userId); + List itemList = null; + switch (option) { + case NODES: + itemList = restClient.getNodes(dc); + Collections.sort(itemList, nodeHealthComparator); + break; + case DATACENTERS: + itemList = restClient.getDatacenters(); + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); + throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + } + final int totalItems = itemList.size(); + // Shrink if needed + if (itemList.size() > pageSize) { + itemList = getPageOfList(pageNum, pageSize, itemList); + } + int pageCount = (int) Math.ceil((double) totalItems / pageSize); + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + return objectMapper.writeValueAsString(model); + } + + /** + * Gets one page of the specified items. This method traps exceptions and + * constructs an appropriate JSON block to report errors. + * + * @param request + * Inbound request + * @param option + * Item type to get + * @return JSON with one page of objects; or an error. + */ + protected String getItemListForPageWrapper(HttpServletRequest request, + String dc, + ConsulDataItem option) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("getItemListForPageWrapper: Failed to get application user"); + int pageNum = getRequestPageNumber(request); + int pageSize = getRequestPageSize(request); + outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize, dc); + } catch (Exception ex) { + // Remote service failed; build descriptive error message + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = new RestResponseError("Failed to get " + option.name(), ex); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } + return outboundJson; + } + + /** + * Serves service health details - not paginated. + * + * @param request + * HttpServletRequest + * @param serviceId + * Service ID + * @return List of ConsulServiceHealth objects as JSON + * @throws Exception + * if serialization fails + */ + @RequestMapping(value = { + SERVICES_PATH + "/{serviceId}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getServiceHealthDetails(HttpServletRequest request, + @RequestParam String dc, + @PathVariable String serviceId) throws Exception { + preLogAudit(request); + Object result = null; + try { + ConsulClient restClient = getConsulRestClient(request); + result = restClient.getServiceHealth(dc,serviceId); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting service health details for " + serviceId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getServiceHealthDetails caught exception"); + result = new RestResponseError("getServiceHealthDetails failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Serves one page of service health information by getting all service + * names, then iterating over them to get the health of each service. + * + * ECOMP-C does NOT provide an API to get the health of all services in one + * request. + * + * @param request + * HttpServletRequest + * @return List of ConsulServiceHealth objects, as JSON + * @throws Exception + * on serialization exception + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { "/serviceshealth" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getServicesHealth(HttpServletRequest request, + @RequestParam String dc) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + List itemList = new ArrayList<>(); + ConsulClient restClient = getConsulRestClient(request); + List svcInfoList = restClient.getServices(dc); + for (ConsulServiceInfo csi : svcInfoList) { + List csh = restClient.getServiceHealth(dc, csi.name); + itemList.addAll(csh); + } + Collections.sort(itemList, serviceHealthComparator); + // Paginate + final int pageNum = getRequestPageNumber(request); + final int pageSize = getRequestPageSize(request); + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + // Shrink if needed + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + result = new RestResponsePage<>(totalItems, pageCount, itemList); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting services health failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getServicesHealth caught exception"); + result = new RestResponseError("getServicesHealth failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Serves one page of node information. + * + * @param request + * HttpServletRequest + * @return List of ConsulNodeInfo objects, as JSON + */ + @RequestMapping(value = { NODES_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getNodesInfo(HttpServletRequest request, + @RequestParam String dc) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, dc, ConsulDataItem.NODES); + postLogAudit(request); + return json; + } + + /** + * Serves node services health details - not paginated. + * + * @param request + * HttpServletRequest + * @param nodeName + * Node name + * @return List of ConsulServiceHealth objects as JSON + * @throws Exception + * if serialization fails + */ + @RequestMapping(value = { NODES_PATH + "/{nodeName}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getNodeServicesHealth(HttpServletRequest request, + @RequestParam String dc, + @PathVariable String nodeName) throws Exception { + preLogAudit(request); + Object result = null; + try { + ConsulClient restClient = getConsulRestClient(request); + result = restClient.getNodeServicesHealth(dc, nodeName); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting node services health for " + nodeName + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getNodeServicesHealth caught exception"); + result = new RestResponseError("getNodeServicesHealth failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Serves one page of datacenters health. + * + * @param request + * HttpServletRequest + * @return List of ConsulHealthStatus objects + */ + @RequestMapping(value = { "/datacenters" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDatacentersHealth(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, null, ConsulDataItem.DATACENTERS); + postLogAudit(request); + return json; + } + + /** + * Processes request to register a service for health checks. + * + * @param request + * HttpServletRequest + * @param registration + * Consul service registration + * @return URI of the newly registered resource + * @throws Exception + * on serialization error + */ + @RequestMapping(value = { "/register" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String registerService(HttpServletRequest request, @RequestBody ConsulHealthServiceRegistration registration) + throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + if (registration.services == null) { + throw new Exception("services[] tag is mandatory"); + } + + List checks = registration.services.get(0).checks; + String service_name = registration.services.get(0).name; + String service_port = registration.services.get(0).port; + String service_address = registration.services.get(0).address; + + if (checks == null || service_port.isEmpty() || service_address.isEmpty() || service_name.isEmpty()) { + throw new Exception("fields : [checks[], port, address, name] are mandatory"); + } + for (EndpointCheck check : checks) { + if (check.endpoint.isEmpty() || check.interval.isEmpty() ) { + throw new Exception("Required fields : [endpoint, interval] in checks"); + } + } + ConsulClient restClient = getConsulRestClient(request); + result = new RestResponseSuccess(restClient.registerService(registration)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Registering service failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "registerService caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Registering service failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "registerService caught exception"); + result = new RestResponseError("registerService failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Processes request to deregister a service for health checks. + * + * @param request + * HttpServletRequest + * @param serviceName + * Consul service name to deregister + * @return Success or error indicator + * @throws Exception + * on serialization error + */ + @RequestMapping(value = { "/deregister" + "/{serviceName}" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String deregisterService(HttpServletRequest request, + @PathVariable String serviceName) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + ConsulClient restClient = getConsulRestClient(request); + int code = restClient.deregisterService(serviceName); + result = new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "De-registering service " + serviceName + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deregisterService caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "De-registering service " + serviceName + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deregisterService caught exception"); + result = new RestResponseError("deregisterService failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java index 8ec1d2c..7ccdbf4 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java @@ -1,162 +1,402 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import java.util.ArrayList; - -import javax.servlet.http.HttpServletRequest; - -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; -import org.onap.ccsdk.dashboard.model.ControllerEndpointTransport; -import org.onap.ccsdk.dashboard.model.RestResponseError; -import org.onap.ccsdk.dashboard.model.RestResponseSuccess; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This controller maps requests for the application's landing page, which is an - * Angular single-page application. - */ -@Controller -@RequestMapping("/") -public class DashboardHomeController extends DashboardRestrictedBaseController { - - /** - * This path is embedded in the database, so it's nontrivial to change. - */ - public static final String APP_CONTEXT_PATH = "/ecd"; - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardHomeController.class); - - @Autowired - private ControllerEndpointService controllerEndpointService; - - /** - * For general use in these methods - */ - private final ObjectMapper mapper; - - private static final String CONTROLLERS_PATH = "controllers"; - - /** - * Spring autowires fields AFTER the constructor is called. - */ - public DashboardHomeController() { - mapper = new ObjectMapper(); - // Do not serialize null values - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - /** - * @return View name key, which is resolved to a file using an Apache tiles - * "definitions.xml" file. - */ - @RequestMapping(value = { APP_CONTEXT_PATH }, method = RequestMethod.GET) - public ModelAndView dbcDefaultController() { - // a model is only useful for JSP; this app is angular. - return new ModelAndView("oom_home_tdkey"); - } - - /** - * Gets the available controller endpoints. - * - * @param request - * HttpServletRequest - * @return List of ControllerEndpointTransport objects, or an error on failure - */ - @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getControllers(HttpServletRequest request) { - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - String outboundJson = null; - // Static data - ControllerEndpointCredentials[] configured = getControllerEndpoints(); - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new DashboardControllerException("getControllers: Failed to get application user"); - ControllerEndpointCredentials selectedInDb = getOrSetControllerEndpointSelection(appUser.getId()); - // Built result from properties - ArrayList list = new ArrayList<>(); - for (ControllerEndpointCredentials ctrl : configured) { - // Check if this is the selected endpoint in DB - boolean selected = (selectedInDb != null && selectedInDb.getUrl() != null - && selectedInDb.getUrl().equals(ctrl.getUrl())); - // Result has no privileged information - ControllerEndpointTransport transport = new ControllerEndpointTransport(selected, ctrl.getName(), - ctrl.getUrl()); - list.add(transport); - } - outboundJson = mapper.writeValueAsString(list); - } catch (Exception ex) { - RestResponseError response = new RestResponseError("Failed to get controller endpoint list", ex); - outboundJson = response.toJson(); - } - return outboundJson; - } - - /** - * Sets the controller endpoint selection for the user. - * - * @param request - * HttpServletRequest - * @param endpoint - * Body with endpoint details - * @return Result indicating success or failure - * @throws DashboardControllerException, - * if application user is not found - * @throws JsonProcessingException - * If serialization fails - */ - @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String setControllerSelection(HttpServletRequest request, @RequestBody ControllerEndpointTransport endpoint) - throws DashboardControllerException, JsonProcessingException { - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - String outboundJson = null; - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new DashboardControllerException("setControllerSelection: Failed to get application user"); - ControllerEndpoint dbEntry = new ControllerEndpoint(appUser.getId(), endpoint.getName(), endpoint.getUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - RestResponseSuccess success = new RestResponseSuccess("Updated selection to " + endpoint.getName()); - outboundJson = mapper.writeValueAsString(success); - return outboundJson; - } -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; +import org.onap.ccsdk.dashboard.domain.EcdComponent; +import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; +import org.onap.ccsdk.dashboard.model.ControllerEndpointTransport; +import org.onap.ccsdk.dashboard.model.ControllerOpsTools; +import org.onap.ccsdk.dashboard.model.EcdAppComponent; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.RestResponseSuccess; +import org.onap.ccsdk.dashboard.service.ControllerEndpointService; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * This controller maps requests for the application's landing page, which is + * an Angular single-page application. + */ +@Controller +@RequestMapping("/") +public class DashboardHomeController extends DashboardRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardHomeController.class); + + @Autowired + private ControllerEndpointService controllerEndpointService; + + /** + * For general use in these methods + */ + private final ObjectMapper mapper; + + private static Date begin, end; + private static final String CONTROLLERS_PATH = "controllers"; + private static final String COMPONENTS_PATH = "components"; + private static final String USER_APPS_PATH = "user-apps"; + private static final String OPS_PATH = "ops"; + private static final String APP_LABEL = "app-label"; + /** + * Never forget that Spring autowires fields AFTER the constructor is + * called. + */ + public DashboardHomeController() { + mapper = new ObjectMapper(); + // Do not serialize null values + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + /** + * @return View name key, which is resolved to a file using an Apache tiles + * "definitions.xml" file. + */ + @RequestMapping(value = { "/ecd" }, method = RequestMethod.GET) + public ModelAndView dbcDefaultController() { + // a model is only useful for JSP; this app is angular. + return new ModelAndView("ecd_home_tdkey"); + } + + /** + * Gets the available blueprint component names + * + * @param request + * HttpServletRequest + * @return List of component name strings, or an error on + * failure + */ + @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getComponents(HttpServletRequest request) { + preLogAudit(request); + String outboundJson = ""; // "['MSO','CLAMP','APPC','ECOMPSCHEDULER','POLICY']"; + try { + HttpSession session = request.getSession(true); + Set userApps = (Set)session.getAttribute("authComponents"); + if (userApps == null) { + userApps = new TreeSet(); + } + List filterList = new ArrayList(); + List ecdApps = new ArrayList(); + + List dbResult = + controllerEndpointService.getComponents(); + + List dcaeCompList = + (List) dbResult.stream().filter(s -> ((EcdComponent) s).contains("dcae")).collect(Collectors.toList()); + + if (!userApps.isEmpty()) { // non-admin role level + for(String userRole : userApps) { + if (userRole.equalsIgnoreCase("dcae")) { + if (dcaeCompList != null && !dcaeCompList.isEmpty()) { + EcdAppComponent dcaeAppComponent = new EcdAppComponent("DCAE", dcaeCompList); + ecdApps.add(dcaeAppComponent); + } + } else { + List tmpItemList = + (List) dbResult.stream().filter(s -> ((EcdComponent) s).contains(userRole)).collect(Collectors.toList()); + if (tmpItemList != null) { + logger.debug(">>>> adding filtered items"); + filterList.addAll(tmpItemList); + } + } + } + if (!filterList.isEmpty()) { + EcdAppComponent ecdAppComponent = new EcdAppComponent("ECOMP", filterList); + ecdApps.add(ecdAppComponent); + } + } else { + // lookup "dcae" in the db component list + if (dcaeCompList != null && !dcaeCompList.isEmpty()) { + EcdAppComponent dcaeAppComponent = new EcdAppComponent("DCAE", dcaeCompList); + ecdApps.add(dcaeAppComponent); + } + if (dbResult != null && !dbResult.isEmpty()) { + EcdAppComponent ecdAppComponent = new EcdAppComponent("ECOMP", dbResult); + ecdApps.add(ecdAppComponent); + } + } + outboundJson = mapper.writeValueAsString(ecdApps); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Get components failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get components list"); + RestResponseError response = new RestResponseError("Failed to get components list", ex); + outboundJson = response.toJson(); + } finally { + postLogAudit(request); + } + return outboundJson; + } + + /** + * Get the application label - name + environment + * + */ + @RequestMapping(value = {APP_LABEL}, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getAppLabel(HttpServletRequest request) throws Exception { + return mapper.writeValueAsString(appProperties.getPropertyDef(appProperties.CONTROLLER_IN_ENV, "NA")); + //return mapper.writeValueAsString(systemProperties.getAppDisplayName()); + } + /** + * Gets the application name(s) for the authenticated user + * + * @param request + * HttpServletRequest + * @return List of component name strings, or an error on + * failure + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { USER_APPS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getUserApps(HttpServletRequest request) { + preLogAudit(request); + String outboundJson = ""; // "['MSO','CLAMP','APPC','ECOMPSCHEDULER','POLICY']"; + try { + HttpSession session = request.getSession(true); + Set userApps = (Set)session.getAttribute("authComponents"); + if (userApps == null) { + userApps = new TreeSet(); + } + outboundJson = mapper.writeValueAsString(userApps); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Get User Apps failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get apps list"); + RestResponseError response = new RestResponseError("Failed to get apps list", ex); + outboundJson = response.toJson(); + } finally { + postLogAudit(request); + } + return outboundJson; + } + /** + * Sets the controller endpoint selection for the user. + * + * @param request + * HttpServletRequest + * @param endpoint + * Body with endpoint details + * @return Result indicating success or failure + * @throws Exception + * if application user is not found + */ + @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String insertComponent(HttpServletRequest request, @RequestBody EcdComponent newComponent) + throws Exception { + preLogAudit(request); + String outboundJson = null; + controllerEndpointService.insertComponent(newComponent); + RestResponseSuccess success = new RestResponseSuccess("Inserted new component with name " + newComponent.getCname()); + outboundJson = mapper.writeValueAsString(success); + postLogAudit(request); + return outboundJson; + } + + /** + * Gets the OPS Tools URLs from dashboard properties + * + * @param request + * HttpServletRequest + * @return List of ControllerOpsTools objects, or an error on + * failure + * @throws Exception + */ + @RequestMapping(value = { OPS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getOpsToolUrls(HttpServletRequest request) { + preLogAudit(request); + String outboundJson = null; + try { + List opsList = getControllerOpsTools(); + outboundJson = mapper.writeValueAsString(opsList); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Get Ops Tools URLs failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get Ops Tools URL list"); + RestResponseError response = new RestResponseError("Failed to get Ops Tools URL list", ex); + outboundJson = response.toJson(); + } finally { + postLogAudit(request); + } + return outboundJson; + } + + // get sites + // get cfy, cnsl URLs + // get cfy tenants + // get cfy secret value for k8s ip per tenant + // construct models TenantOpsCluster, SiteOpsToolLinks + // return final model + /** + * Gets the available controller endpoints. + * + * @param request + * HttpServletRequest + * @return List of ControllerEndpointTransport objects, or an error on + * failure + * @throws Exception + * if application user is not found + */ + @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getControllers(HttpServletRequest request) { + preLogAudit(request); + String outboundJson = null; + // Static data + ControllerEndpointCredentials[] configured = getControllerEndpoints(); + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Get controllers failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get application user"); + throw new Exception("getControllers: Failed to get application user"); + } + ControllerEndpointCredentials selectedInDb = getOrSetControllerEndpointSelection(appUser.getId()); + // Built result from properties + ArrayList list = new ArrayList<>(); + for (ControllerEndpointCredentials ctrl : configured) { + // Check if this is the selected endpoint in DB + boolean selected = (selectedInDb != null && selectedInDb.getUrl() != null + && selectedInDb.getUrl().equals(ctrl.getUrl())); + // Result has no privileged information + ControllerEndpointTransport transport = new ControllerEndpointTransport(selected, ctrl.getName(), + ctrl.getUrl(), ctrl.getInventoryUrl(), ctrl.getDhandlerUrl(), ctrl.getConsulUrl()); + list.add(transport); + } + outboundJson = mapper.writeValueAsString(list); + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Get controllers failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get controller endpoint list"); + RestResponseError response = new RestResponseError("Failed to get controller endpoint list", ex); + outboundJson = response.toJson(); + } finally { + postLogAudit(request); + } + return outboundJson; + } + + /** + * Sets the controller endpoint selection for the user. + * + * @param request + * HttpServletRequest + * @param endpoint + * Body with endpoint details + * @return Result indicating success or failure + * @throws Exception + * if application user is not found + */ + @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String setControllerSelection(HttpServletRequest request, @RequestBody ControllerEndpointTransport endpoint) + throws Exception { + preLogAudit(request); + String outboundJson = null; + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Set controllers failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get application user"); + postLogAudit(request); + throw new Exception("setControllerSelection: Failed to get application user"); + } + ControllerEndpoint dbEntry = new ControllerEndpoint(appUser.getId(), endpoint.getName(), endpoint.getUrl(), endpoint.getInventoryUrl(), endpoint.getDhandlerUrl()); + controllerEndpointService.updateControllerEndpointSelection(dbEntry); + RestResponseSuccess success = new RestResponseSuccess("Updated selection to " + endpoint.getName()); + outboundJson = mapper.writeValueAsString(success); + postLogAudit(request); + return outboundJson; + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "DashboardHomeController"); + MDC.put("TargetServiceName", "DashboardHomeController"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java index 02f8770..809dbb9 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java @@ -1,275 +1,470 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.ccsdk.dashboard.rest.ControllerRestClientMockImpl; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.ccsdk.dashboard.rest.IControllerRestClient; -import org.onap.ccsdk.dashboard.util.DashboardProperties; -import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; -import org.onap.ccsdk.dashboard.rest.ControllerRestClientImpl; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This base class provides utility methods to child controllers. - */ -public class DashboardRestrictedBaseController extends RestrictedBaseController { - - /** - * Logger that conforms with ECOMP guidelines - */ - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardRestrictedBaseController.class); - - /** - * Application name - */ - protected static final String APP_NAME = "ecd-app"; - - /** - * EELF-approved format - */ - protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - /** - * Query parameter for desired page number - */ - protected static final String PAGE_NUM_QUERY_PARAM = "pageNum"; - - /** - * Query parameter for desired items per page - */ - protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage"; - - /** - * For general use in these methods and subclasses - */ - protected final ObjectMapper objectMapper = new ObjectMapper(); - - /** - * Application properties - NOT available to constructor. - */ - @Autowired - private DashboardProperties appProperties; - - /** - * For getting selected controller - */ - @Autowired - private ControllerEndpointService controllerEndpointService; - - /** - * Hello Spring, here's your no-arg constructor. - */ - public DashboardRestrictedBaseController() { - // Do not serialize null values - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - /** - * Access method for subclasses. - * - * @return DbcappProperties object that was autowired by Spring. - */ - protected DashboardProperties getAppProperties() { - return appProperties; - } - - /** - * Gets the requested page number from a query parameter in the - * HttpServletRequest. Defaults to 1, which is useful to allow manual - * testing of endpoints without supplying those pesky parameters. - * - * @param request - * HttpServletRequest - * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not - * found. - */ - protected int getRequestPageNumber(HttpServletRequest request) { - int pageNum = 1; - String param = request.getParameter(PAGE_NUM_QUERY_PARAM); - if (param != null) - pageNum = Integer.parseInt(param); - return pageNum; - } - - /** - * Gets the requested page size from a query parameter in the - * HttpServletRequest. Defaults to 50, which is useful to allow manual - * testing of endpoints without supplying those pesky parameters. - * - * @param request - * HttpServletRequest - * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if - * not found. - */ - protected int getRequestPageSize(HttpServletRequest request) { - int pageSize = 50; - String param = request.getParameter(PAGE_SIZE_QUERY_PARAM); - if (param != null) - pageSize = Integer.parseInt(param); - return pageSize; - } - - /** - * Gets the items for the specified page from the specified list. - * - * @param pageNum - * Page number requested by user, indexed from 1 - * @param pageSize - * Number of items per page - * @param itemList - * List of items to adjust - * @return List of items; empty list if from==to - */ - @SuppressWarnings("rawtypes") - protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) { - int firstIndexOnThisPage = pageSize * (pageNum - 1); - int firstIndexOnNextPage = pageSize * pageNum; - int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); - int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); - return itemList.subList(fromIndex, toIndex); - } - - /** - * Gets all configured controllers from properties. - * - * @return Array of ControllerEndpointRestricted objects - * @throws IllegalStateException - * if a required property is not found - */ - protected ControllerEndpointCredentials[] getControllerEndpoints() { - final String[] controllerKeys = appProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST); - ControllerEndpointCredentials[] controllers = new ControllerEndpointCredentials[controllerKeys.length]; - for (int i = 0; i < controllerKeys.length; ++i) { - String key = controllerKeys[i]; - final String name = appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_NAME); - final String url = appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_URL); - final String user = appProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_USERNAME); - final String pass = appProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_PASSWORD); - final boolean encr = Boolean.parseBoolean ( - appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_ENCRYPTED)); - logger.debug(EELFLoggerDelegate.debugLogger, "getConfiguredControllers: key {} yields url {}", key, url); - controllers[i] = new ControllerEndpointCredentials(false, name, url, user, pass, encr); - } - return controllers; - } - - /** - * Gets the controller endpoint for the specified user ID. Chooses the first - * one from properties if the user has not selected one previously. - * - * @param userId - * Database User ID - * @return ControllerEndpointCredentials for the specified user - */ - protected ControllerEndpointCredentials getOrSetControllerEndpointSelection(long userId) { - // Always need the complete list from properties - ControllerEndpointCredentials[] configured = getControllerEndpoints(); - // See if the database has an entry for this user - ControllerEndpoint dbEntry = controllerEndpointService.getControllerEndpointSelection(userId); - // If no row found DAO returns an object with null entries. - if (dbEntry == null || dbEntry.getName() == null) { - // Arbitrarily choose the first one - ControllerEndpointCredentials first = configured[0]; - dbEntry = new ControllerEndpoint(userId, first.getName(), first.getUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - } - // Fetch complete details for the selected item - ControllerEndpointCredentials selected = null; - for (ControllerEndpointCredentials cec : configured) { - if (dbEntry.getUrl().equals(cec.getUrl())) { - selected = cec; - break; - } - } - // Defend against a stale database entry. - if (selected == null) { - selected = configured[0]; - dbEntry = new ControllerEndpoint(userId, selected.getName(), selected.getUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - } - return selected; - } - - /** - * Convenience method that gets the user ID from the session and fetches the - * REST client. Factors code out of subclass methods. - * - * @param request - * HttpServletRequest - * @return REST client appropriate for the user - * @throws DashboardControllerException - */ - protected IControllerRestClient getControllerRestClient(HttpServletRequest request) throws DashboardControllerException { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new DashboardControllerException("getControllerRestClient: Failed to get application user"); - return getControllerRestClient(appUser.getId()); - } - - /** - * Gets a REST client; either a mock client (returns canned data), or a real - * client with appropriate credentials from properties. - * - * @return REST client. - * @throws DashboardControllerException on any failure; e.g., if the password cannot be decrypted. - */ - protected IControllerRestClient getControllerRestClient(long userId) throws DashboardControllerException { - IControllerRestClient result = null; - // Be robust to missing development-only property - boolean mock = false; - if (appProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = appProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new ControllerRestClientMockImpl(); - } else { - try { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new ControllerRestClientImpl(details.getUrl(), details.getUsername(), clearText); - } - catch (Exception ex) { - logger.error("getControllerRestClient failed", ex); - throw new DashboardControllerException(ex); - } - } - return result; - } - -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; +import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; +import org.onap.ccsdk.dashboard.model.ControllerOpsTools; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.CloudifyMockClientImpl; +import org.onap.ccsdk.dashboard.rest.CloudifyRestClientImpl; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.ccsdk.dashboard.rest.ConsulMockClientImpl; +import org.onap.ccsdk.dashboard.rest.ConsulRestClientImpl; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClientImpl; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.ccsdk.dashboard.rest.RestInventoryClientImpl; +import org.onap.ccsdk.dashboard.rest.RestInventoryClientMockImpl; +import org.onap.ccsdk.dashboard.service.ControllerEndpointService; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +/** + * This base class provides utility methods to child controllers. + */ +public class DashboardRestrictedBaseController extends RestrictedBaseController { + + /** + * Application name + */ + protected static final String APP_NAME = "ecd-app"; + + /** + * EELF-approved format + */ + protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + /** + * Query parameter for desired page number + */ + protected static final String PAGE_NUM_QUERY_PARAM = "pageNum"; + + /** + * Query parameter for desired items per page + */ + protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage"; + + /** + * For general use in these methods and subclasses + */ + protected final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Application properties - NOT available to constructor. + */ + @Autowired + protected DashboardProperties appProperties; + + /** + * For getting selected controller + */ + @Autowired + private ControllerEndpointService controllerEndpointService; + + /** + * Hello Spring, here's your no-arg constructor. + */ + public DashboardRestrictedBaseController() { + // Do not serialize null values + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + // Register Jdk8Module() for Stream and Optional types + objectMapper.registerModule(new Jdk8Module()); + } + + /** + * Access method for subclasses. + * + * @return DbcappProperties object that was autowired by Spring. + */ + protected DashboardProperties getAppProperties() { + return appProperties; + } + + /** + * Gets the requested page number from a query parameter in the + * HttpServletRequest. Defaults to 1, which is useful to allow manual + * testing of endpoints without supplying those pesky parameters. + * + * @param request + * HttpServletRequest + * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not + * found. + */ + protected int getRequestPageNumber(HttpServletRequest request) { + int pageNum = 1; + String param = request.getParameter(PAGE_NUM_QUERY_PARAM); + if (param != null) + pageNum = Integer.parseInt(param); + return pageNum; + } + + /** + * Gets the requested page size from a query parameter in the + * HttpServletRequest. Defaults to 50, which is useful to allow manual + * testing of endpoints without supplying those pesky parameters. + * + * @param request + * HttpServletRequest + * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if + * not found. + */ + protected int getRequestPageSize(HttpServletRequest request) { + int pageSize = 50; + String param = request.getParameter(PAGE_SIZE_QUERY_PARAM); + if (param != null) + pageSize = Integer.parseInt(param); + return pageSize; + } + + /** + * Gets the items for the specified page from the specified list. + * + * @param pageNum + * Page number requested by user, indexed from 1 + * @param pageSize + * Number of items per page + * @param itemList + * List of items to adjust + * @return List of items; empty list if from==to + */ + @SuppressWarnings("rawtypes") + protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) { + int firstIndexOnThisPage = pageSize * (pageNum - 1); + int firstIndexOnNextPage = pageSize * pageNum; + int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); + int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); + return itemList.subList(fromIndex, toIndex); + } + + /** + * Gets all configured controllers from properties. + * + * @return Array of ControllerEndpointRestricted objects + * @throws IllegalStateException + * if a required property is not found + */ + protected ControllerEndpointCredentials[] getControllerEndpoints() { + final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST); + ControllerEndpointCredentials[] controllers = new ControllerEndpointCredentials[controllerKeys.length]; + for (int i = 0; i < controllerKeys.length; ++i) { + String key = controllerKeys[i]; + final String name = DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_NAME); + final String url = DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_URL); + final String inventoryUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL); + final String dhandlerUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL); + final String consulUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL); + final String user = DashboardProperties.getControllerProperty(key, + DashboardProperties.CONTROLLER_SUBKEY_USERNAME); + final String pass = DashboardProperties.getControllerProperty(key, + DashboardProperties.CONTROLLER_SUBKEY_PASS); + final boolean encr = Boolean.parseBoolean( + DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_ENCRYPTED)); + controllers[i] = new ControllerEndpointCredentials(false, name, url, inventoryUrl, dhandlerUrl, consulUrl, user, pass, encr); + } + return controllers; + } + + /** + * Get the list of configured OPS Tools URLs from dashboard properties + * + * @return Array of ControllerOpsTools objects + * @throws IllegalStateException + * if a required property is not found + */ + protected List getControllerOpsTools() { + List opsList = new ArrayList<>(); + final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST); + String key = controllerKeys[0]; + final String cfyId = DashboardProperties.OPS_CLOUDIFY_URL.split("\\.")[1]; + final String cfyUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CLOUDIFY_URL); + final String k8Id = DashboardProperties.OPS_K8S_URL.split("\\.")[1]; + final String k8Url = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_K8S_URL); + final String grfId = DashboardProperties.OPS_GRAFANA_URL.split("\\.")[1]; + final String grfUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_GRAFANA_URL); + final String cnslId = DashboardProperties.OPS_CONSUL_URL.split("\\.")[1]; + final String cnslUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CONSUL_URL); + final String promId = DashboardProperties.OPS_PROMETHEUS_URL.split("\\.")[1]; + final String promUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_PROMETHEUS_URL); + final String dbclId = DashboardProperties.OPS_DBCL_URL.split("\\.")[1]; + final String dbclUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_DBCL_URL); + opsList.add(new ControllerOpsTools(cfyId, cfyUrl)); + opsList.add(new ControllerOpsTools(k8Id, k8Url)); + opsList.add(new ControllerOpsTools(grfId, grfUrl)); + opsList.add(new ControllerOpsTools(cnslId, cnslUrl)); + opsList.add(new ControllerOpsTools(promId, promUrl)); + opsList.add(new ControllerOpsTools(dbclId, dbclUrl)); + + return opsList; + } + + /** + * Gets the controller endpoint for the specified user ID. Chooses the first + * one from properties if the user has not selected one previously. + * + * @param userId + * Database User ID + * @return ControllerEndpointCredentials for the specified user + */ + protected ControllerEndpointCredentials getOrSetControllerEndpointSelection(long userId) { + // Always need the complete list from properties + ControllerEndpointCredentials[] configured = getControllerEndpoints(); + // See if the database has an entry for this user + ControllerEndpoint dbEntry = controllerEndpointService.getControllerEndpointSelection(userId); + // If no row found DAO returns an object with null entries. + if (dbEntry == null || dbEntry.getName() == null) { + // Arbitrarily choose the first one + ControllerEndpointCredentials first = configured[0]; + dbEntry = new ControllerEndpoint(userId, first.getName(), first.getUrl(), first.getInventoryUrl(), first.getDhandlerUrl()); + controllerEndpointService.updateControllerEndpointSelection(dbEntry); + } + // Fetch complete details for the selected item + ControllerEndpointCredentials selected = null; + for (ControllerEndpointCredentials cec : configured) { + if (dbEntry.getUrl().equals(cec.getUrl())) { + selected = cec; + break; + } + } + // Defend against a stale database entry. + if (selected == null) { + selected = configured[0]; + dbEntry = new ControllerEndpoint(userId, selected.getName(), selected.getUrl(), selected.getInventoryUrl(), selected.getDhandlerUrl()); + controllerEndpointService.updateControllerEndpointSelection(dbEntry); + } + return selected; + } + + protected ControllerEndpointCredentials getOrSetControllerEndpointSelection() { + ControllerEndpointCredentials[] configured = getControllerEndpoints(); + return configured[0]; + } + /** + * Convenience method that gets the user ID from the session and fetches the + * REST client. Factors code out of subclass methods. + * + * @param request + * HttpServletRequest + * @return REST client appropriate for the user + */ + protected CloudifyClient getCloudifyRestClient(HttpServletRequest request) throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getCloudifyRestClient: Failed to get application user"); + return getCloudifyRestClient(appUser.getId()); + } + + /** + * Gets a REST client; either a mock client (returns canned data), or a real + * client with appropriate credentials from properties. + * + * @return REST client. + */ + protected CloudifyClient getCloudifyRestClient(long userId) throws Exception { + CloudifyClient result = null; + // Be robust to missing development-only property + boolean mock = false; + if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) + mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); + if (mock) { + result = new CloudifyMockClientImpl(); + } else { + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText); + } + return result; + } + + /** + * Gets a REST client; either a mock client (returns canned data), or a real + * client with appropriate credentials from properties. + * + * @return REST client. + */ + protected CloudifyClient getCloudifyRestClient() throws Exception { + CloudifyClient result = null; + // Be robust to missing development-only property + boolean mock = false; + if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) + mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); + if (mock) { + result = new CloudifyMockClientImpl(); + } else { + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText); + } + return result; + } + + /** + * Convenience method that gets the user ID from the session and fetches the + * REST client. Factors code out of subclass methods. + * + * @param request + * HttpServletRequest + * @return REST client appropriate for the user + */ + protected ConsulClient getConsulRestClient(HttpServletRequest request) throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getControllerRestClient: Failed to get application user"); + return getConsulRestClient(appUser.getId()); + } + + /** + * Gets a REST client; either a mock client (returns canned data), or a real + * client with appropriate credentials from properties. + * + * @return REST client. + */ + protected ConsulClient getConsulRestClient(long userId) throws Exception { + ConsulClient result = null; + // Be robust to missing development-only property + boolean mock = false; + if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) + mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); + if (mock) { + result = new ConsulMockClientImpl(); + } else { + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText); + } + return result; + } + + /** + * Gets a REST client; either a mock client (returns canned data), or a real + * client with appropriate credentials from properties. + * + * @return REST client. + */ + protected ConsulClient getConsulRestClient() throws Exception { + ConsulClient result = null; + // Be robust to missing development-only property + boolean mock = false; + if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) + mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); + if (mock) { + result = new ConsulMockClientImpl(); + } else { + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText); + } + return result; + } + + /** + * Convenience method that gets the user ID from the session and fetches the + * Inventory client. Factors code out of subclass methods. + * + * @param request + * HttpServletRequest + * @return Inventory client appropriate for the user + */ + protected InventoryClient getInventoryClient(HttpServletRequest request) throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null) + throw new Exception("getControllerRestClient: Failed to get application user"); + return getInventoryClient(appUser.getId()); + } + + /** + * Gets an Inventory client with appropriate credentials from properties. + * + * @return Inventory Client. + */ + protected InventoryClient getInventoryClient(long userId) throws Exception { + InventoryClient result = null; + boolean mock = false; + if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) + mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); + if (mock) { + result = new RestInventoryClientMockImpl(); + } else { + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText); + } + return result; + } + + protected InventoryClient getInventoryClient() throws Exception { + InventoryClient result = null; + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText); + return result; + } + /** + * Convenience method that gets the user ID from the session and fetches the + * Deployment Handler client. Factors code out of subclass methods. + * + * @param request + * HttpServletRequest + * @return Deployment Handler client appropriate for the user + */ + protected DeploymentHandlerClient getDeploymentHandlerClient(HttpServletRequest request) throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null) + throw new Exception("getControllerRestClient: Failed to get application user"); + return getDeploymentHandlerClient(appUser.getId()); + } + + /** + * Gets a Deployment Handler client with appropriate credentials from properties. + * + * @return Deployment Handler Client. + */ + protected DeploymentHandlerClient getDeploymentHandlerClient(long userId) throws Exception { + DeploymentHandlerClient result = null; + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText); + return result; + } + + protected DeploymentHandlerClient getDeploymentHandlerClient() throws Exception { + DeploymentHandlerClient result = null; + ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); + final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); + result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText); + return result; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java new file mode 100644 index 0000000..c99583c --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java @@ -0,0 +1,243 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequestObject; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResource; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResourceLinks; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * Controller for Deployment Handler features: get/put/delete deployments + * Methods serve Ajax requests made by Angular scripts on pages that show + * content. + */ +@Controller +@RequestMapping("/deploymenthandler") +public class DeploymentHandlerController extends DashboardRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); + + private static final String DEPLOYMENTS_PATH = "dcae-deployments"; + + private static Date begin, end; + + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId:.+}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String putDeployment(HttpServletRequest request, @RequestBody DeploymentRequestObject deploymentRequestObject) throws Exception { + preLogAudit(request); + String json = null; + try { + DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(request); + if (deploymentRequestObject.getMethod().equals("create")) { + json = objectMapper.writeValueAsString(deploymentHandlerClient.putDeployment(deploymentRequestObject.getDeploymentId(), + deploymentRequestObject.getTenant(), new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), deploymentRequestObject.getInputs()))); + } else { + json = objectMapper.writeValueAsString(deploymentHandlerClient.updateDeployment(deploymentRequestObject.getDeploymentId(), + deploymentRequestObject.getTenant(), new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), deploymentRequestObject.getInputs()))); + } + } catch (BadRequestException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed! Bad Request"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Bad Request " + e.getMessage())); + } catch (ServiceAlreadyExistsException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed! Service already exists"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Service already exists " + e.getMessage())); + } catch (ServerErrorException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed! Server Error"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Server Error " + e.getMessage())); + } catch (DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed! Downstream Exception"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Downstream Exception " + e.getMessage())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed! Json Processing Exception"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId:.+}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, + @RequestParam("tenant") String tenant, HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = null; + StringBuffer status = new StringBuffer(); + try { + DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(request); + deploymentHandlerClient.deleteDeployment(deploymentId, tenant); + String self = request.getRequestURL().toString().split("\\?")[0]; + status.append(self) + .append("/executions?tenant=") + .append(tenant); + DeploymentResource deplRsrc = + new DeploymentResource(deploymentId, + new DeploymentResourceLinks(self, "", status.toString())); + JSONObject statObj = new JSONObject(deplRsrc); + json = statObj.toString(); + } catch (BadRequestException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServerErrorException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (DeploymentNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java index 28f939c..de86a3e 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java @@ -1,299 +1,302 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ - -package org.onap.ccsdk.dashboard.controller; - -import java.io.UnsupportedEncodingException; - -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.portalsdk.core.auth.LoginStrategy; -import org.onap.portalsdk.core.command.LoginBean; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.menu.MenuProperties; -import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; -import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; -import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; -import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; -import org.onap.portalsdk.core.service.LoginService; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.portalsdk.core.web.support.AppUtils; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.onap.portalsdk.core.service.RoleService; -import org.onap.portalsdk.core.domain.RoleFunction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.util.WebUtils; - -@Controller -@RequestMapping("/") -/** - * Replicated from - * org.onap.portalapp.controller.core.SingleSignOnController to modify the - * behavior of sending user's browser on a detour of Portal app to get the - * EPService cookie. - */ -public class ECDSingleSignOnController extends UnRestrictedBaseController { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECDSingleSignOnController.class); - private static final String REDIRECT = "redirect:"; - - @Autowired - private LoginService loginService; - - @Autowired - private LoginStrategy loginStrategy; - - @Autowired - private RoleService roleService; - - private String viewName; - private String welcomeView; - - /** - * Handles requests directed to the single sign-on page by the session timeout - * interceptor. - * - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse - * @return Redirect to an appropriate address - * @throws DashboardControllerException - * User not found - * @throws PortalAPIException - * User ID can't be fetched - * @throws UnsupportedEncodingException - * Encoding fails - */ - @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET) - public ModelAndView singleSignOnLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { - //throws DashboardControllerException, PortalAPIException, UnsupportedEncodingException { - - Map model = new HashMap<>(); - HashMap additionalParamsMap = new HashMap<>(); - LoginBean commandBean = new LoginBean(); - - // SessionTimeoutInterceptor sets these parameters - String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8"); - String redirectToPortal = request.getParameter("redirectToPortal"); - - if (isLoginCookieExist(request) && redirectToPortal == null) { - HttpSession session = null; - session = AppUtils.getSession(request); - User user = UserUtils.getUserSession(request); - if (session == null || user == null) { - - final String authMech = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); - String userId = loginStrategy.getUserId(request); - commandBean.setUserid(userId); - commandBean = getLoginService().findUser(commandBean, - (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap); - List roleFunctionList = roleService.getRoleFunctions(userId); - try { - commandBean = getLoginService().findUser(commandBean, - (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), - additionalParamsMap); - } catch (Exception ex) { - logger.error("singleSignOnLogin failed", ex); - throw new DashboardControllerException(ex); - } - if (commandBean.getUser() == null) { - String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) - ? commandBean.getLoginErrorMessage() - : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; - model.put(LoginStrategy.ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage)); - final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) - + "?noUserError=Yes"; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}", - redirectUrl); - return new ModelAndView(REDIRECT + redirectUrl); - } else { - // store the user's information in the session - String loginMethod; - if (null == authMech || "".equals(authMech) || "BOTH".equals(authMech)) { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); - } else if ("CSP".equals(authMech)) { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); - } else { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION); - } - UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), - commandBean.getBusinessDirectMenu(), loginMethod, roleFunctionList); - initateSessionMgtHandler(request); - logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", - userId, commandBean.getUser().getOrgUserId()); - return new ModelAndView(REDIRECT + forwardURL); - } - } // user is null or session is null - else { - // both user and session are non-null. - logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}", - forwardURL); - return new ModelAndView(REDIRECT + forwardURL); - } - } else { - /* - * Login cookie not found, or redirect-to-portal parameter was found. - */ - if (isPortalAvailable()) { - /* - * Redirect the user to the portal with a suitable return URL. The forwardURL - * parameter that arrives as a parameter is a partial (not absolute) request - * path for a page in the application. The challenge here is to compute the - * correct absolute path for the original request so the portal can redirect the - * user back to the right place. If the application sits behind WebJunction, or - * if separate FE-BE hosts are used, then the URL yielded by the request has a - * host name that is not reachable by the user. - */ - String returnToAppUrl = null; - if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) { - // New feature as of 1610, release 3.3.3: - // application can publish a base URL in system.properties - String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL); - returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL; - logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl); - } else { - /** - * Be backward compatible with applications that don't need this feature. This - * is the controller for the single_signon.htm page, so the replace should - * always find the specified token. - */ - returnToAppUrl = request.getRequestURL().toString() - .replace("single_signon.htm", forwardURL); - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}", - returnToAppUrl); - } - final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8"); - // Also send the application's UEB key so Portal can block URL - // reflection attacks. - final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/process_csp"; - final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" - + encodedReturnToAppUrl; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}", - redirectUrl); - return new ModelAndView(REDIRECT + redirectUrl); - } // portal is available - - else { - /* - * Portal is not available. Redirect user to the login page, ignoring the - * forwardURL parameter. - */ - return new ModelAndView("redirect:login.htm"); - } - - } - } - - /** - * Discover if the portal is available by GET-ing a resource from the REST URL - * specified in portal.properties, using a very short timeout. - * - * @return True if the portal answers, otherwise false. - */ - private boolean isPortalAvailable() { - HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(); - final int oneSecond = 1000; - httpRequestFactory.setConnectionRequestTimeout(oneSecond); - httpRequestFactory.setConnectTimeout(oneSecond); - httpRequestFactory.setReadTimeout(oneSecond); - RestTemplate restTemplate = new RestTemplate(httpRequestFactory); - boolean avail = true; - try { - final String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); - String s = restTemplate.getForObject(portalUrl, String.class); - logger.trace("isPortalAvailable got response {}", s); - } catch (RestClientException ex) { - logger.debug("isPortalAvailable failed", ex); - avail = false; - } - return avail; - } - - protected void initateSessionMgtHandler(HttpServletRequest request) { - String portalJSessionId = getPortalJSessionId(request); - String jSessionId = getJessionId(request); - PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request)); - } - - public boolean isLoginCookieExist(HttpServletRequest request) { - Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE); - return (ep != null); - } - - public String getPortalJSessionId(HttpServletRequest request) { - Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE); - return ep.getValue(); - } - - public String getJessionId(HttpServletRequest request) { - return request.getSession().getId(); - } - - @Override - public String getViewName() { - return viewName; - } - - @Override - public void setViewName(String viewName) { - this.viewName = viewName; - } - - public String getWelcomeView() { - return welcomeView; - } - - public void setWelcomeView(String welcomeView) { - this.welcomeView = welcomeView; - } - - public LoginService getLoginService() { - return loginService; - } - - public void setLoginService(LoginService loginService) { - this.loginService = loginService; - } - -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.controller; + +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.onap.portalsdk.core.auth.LoginStrategy; +import org.onap.portalsdk.core.command.LoginBean; +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.menu.MenuProperties; +import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.service.LoginService; +import org.onap.portalsdk.core.service.RoleService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.util.WebUtils; + +@Controller +@RequestMapping("/") +/** + * Replicated from + * org.openecomp.portalapp.controller.core.SingleSignOnController to modify the + * behavior of sending user's browser on a detour of Portal app to get the + * EPService cookie. + */ +public class ECDSingleSignOnController extends UnRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECDSingleSignOnController.class); + + @Autowired + private LoginService loginService; + + @Autowired + private LoginStrategy loginStrategy; + + @Autowired + private RoleService roleService; + + private String viewName; + private String welcomeView; + + /** + * Handles requests directed to the single sign-on page by the session + * timeout interceptor. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return Redirect to an appropriate address + * @throws Exception + * On any failure + */ + @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET) + public ModelAndView singleSignOnLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + + Map model = new HashMap(); + HashMap additionalParamsMap = new HashMap(); + LoginBean commandBean = new LoginBean(); + + // SessionTimeoutInterceptor sets these parameters + String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8"); + String redirectToPortal = request.getParameter("redirectToPortal"); + + if (isLoginCookieExist(request) && redirectToPortal == null) { + HttpSession session = null; + session = AppUtils.getSession(request); + User user = UserUtils.getUserSession(request); + if (session == null || user == null) { + + final String authMech = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + String userId = loginStrategy.getUserId(request); + commandBean.setUserid(userId); + commandBean = getLoginService().findUser(commandBean, + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) + ? commandBean.getLoginErrorMessage() + : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; + model.put(LoginStrategy.ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage)); + final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) + + "?noUserError=Yes"; + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}", + redirectUrl); + return new ModelAndView("redirect:" + redirectUrl); + } else { + // store the user's information in the session + String loginMethod; + if (null == authMech || "".equals(authMech) || "BOTH".equals(authMech)) { + loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); + } else if ("CSP".equals(authMech)) { + loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); + } else { + loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION); + } + UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), + commandBean.getBusinessDirectMenu(), loginMethod, roleService.getRoleFunctions(userId)); + initateSessionMgtHandler(request); + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", + userId, commandBean.getUser().getOrgUserId()); + return new ModelAndView("redirect:" + forwardURL); + } + } // user is null or session is null + else { + // both user and session are non-null. + logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}", + forwardURL); + return new ModelAndView("redirect:" + forwardURL); + } + } else { + /* + * Login cookie not found, or redirect-to-portal parameter was + * found. + */ + if (isPortalAvailable()) { + /* + * Redirect the user to the portal with a suitable return URL. + * The forwardURL parameter that arrives as a parameter is a + * partial (not absolute) request path for a page in the + * application. The challenge here is to compute the correct + * absolute path for the original request so the portal can + * redirect the user back to the right place. If the application + * sits behind WebJunction, or if separate FE-BE hosts are used, + * then the URL yielded by the request has a host name that is + * not reachable by the user. + */ + String returnToAppUrl = null; + if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) { + // New feature as of 1610, release 3.3.3: + // application can publish a base URL in system.properties + String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL); + returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL; + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl); + } else { + /** + * Be backward compatible with applications that don't need + * this feature. This is the controller for the + * single_signon.htm page, so the replace should always find + * the specified token. + */ + returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString() + .replace("single_signon.htm", forwardURL); + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}", + returnToAppUrl); + } + final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8"); + // Also send the application's UEB key so Portal can block URL + // reflection attacks. + final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/process_csp"; + final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + + encodedReturnToAppUrl; + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}", + redirectUrl); + return new ModelAndView("redirect:" + redirectUrl); + } // portal is available + + else { + /* + * Portal is not available. Redirect user to the login page, + * ignoring the forwardURL parameter. + */ + return new ModelAndView("redirect:login.htm"); + } + + } + } + + /** + * Discover if the portal is available by GET-ing a resource from the REST + * URL specified in portal.properties, using a very short timeout. + * + * @return True if the portal answers, otherwise false. + */ + private boolean isPortalAvailable() { + HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + final int oneSecond = 1000; + httpRequestFactory.setConnectionRequestTimeout(oneSecond); + httpRequestFactory.setConnectTimeout(oneSecond); + httpRequestFactory.setReadTimeout(oneSecond); + RestTemplate restTemplate = new RestTemplate(httpRequestFactory); + boolean avail = true; + try { + final String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + String s = restTemplate.getForObject(portalUrl, String.class); + logger.trace("isPortalAvailable got response {}", s); + } catch (RestClientException ex) { + logger.debug("isPortalAvailable failed", ex); + avail = false; + } + return avail; + } + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String portalJSessionId = getPortalJSessionId(request); + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request)); + } + + public boolean isLoginCookieExist(HttpServletRequest request) { + Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE); + return (ep != null); + } + + public String getPortalJSessionId(HttpServletRequest request) { + Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE); + return ep.getValue(); + } + + public String getJessionId(HttpServletRequest request) { + return request.getSession().getId(); + } + + public String getViewName() { + return viewName; + } + + public void setViewName(String viewName) { + this.viewName = viewName; + } + + public String getWelcomeView() { + return welcomeView; + } + + public void setWelcomeView(String welcomeView) { + this.welcomeView = welcomeView; + } + + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java index be099a7..0810e3d 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java @@ -1,86 +1,277 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.onap.ccsdk.dashboard.model.HealthStatus; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.onap.portalsdk.core.domain.App; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * This controller responds to probes for application health, returning a JSON - * body to indicate current status. - */ -@RestController -@Configuration -@EnableAspectJAutoProxy -@RequestMapping("/") -public class HealthCheckController extends UnRestrictedBaseController { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); - - private static final String HEALTH_CHECK_PATH = "/healthCheck"; - - @Autowired - private DataAccessService dataAccessService; - - /** - * Checks application health by making a trivial query to (what??). - * - * @param request - * HttpServletRequest - * @return 200 if database access succeeds, 500 if it fails. - */ - @RequestMapping(value = { HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus healthCheck(HttpServletRequest request) { - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DashboardRestrictedBaseController.APP_NAME); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - HealthStatus healthStatus = null; - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); - @SuppressWarnings("unchecked") - // Get the single app. - List list = dataAccessService.getList(App.class, null); - if (!list.isEmpty()) - healthStatus = new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check succeeded"); - else - healthStatus = new HealthStatus(500, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check failed to run db query"); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex); - healthStatus = new HealthStatus(500, "health check failed: " + ex.toString()); - } - return healthStatus; - } - -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.HttpStatus; +import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; +import org.onap.ccsdk.dashboard.model.HealthStatus; +import org.onap.portalsdk.core.domain.App; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * This controller responds to probes for application health, returning a JSON + * body to indicate current status. + */ +@RestController +@Configuration +@EnableAspectJAutoProxy +@RequestMapping("/") +public class HealthCheckController extends DashboardRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); + + /** + * Application name + */ + protected static final String APP_NAME = "ecd-app"; + + private static Date begin, end; + private static final String APP_HEALTH_CHECK_PATH = "/health"; + private static final String APP_SRVC_HEALTH_CHECK_PATH = "/health-info"; + + private static final String APP_DB_QRY = "from App where id = 1"; + public static final String APP_METADATA = "APP.METADATA"; + + @Autowired + private DataAccessService dataAccessService; + + private AbstractCacheManager cacheManager; + + /** + * application health by simply responding with a JSON object indicating status + * + * @param request + * HttpServletRequest + * @return HealthStatus object always + */ + @RequestMapping(value = { APP_HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) { + return new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check passed "); + } + + /** + * Checks application health by executing a sample query with local DB + * + * @param request + * HttpServletRequest + * @return 200 if database access succeeds, 500 if it fails. + */ + /* + public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) { + //preLogAudit(request); + HealthStatus healthStatus = new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check passed "); + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + App app; + Object appObj = getCacheManager().getObject(APP_METADATA); + if (appObj == null) { + app = findApp(); + if (app != null) { + getCacheManager().putObject(APP_METADATA, app); + } else { + healthStatus = new HealthStatus(503, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check failed to query App from database"); + } + } + + if (isDbConnUp()) { + healthStatus = new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check passed "); + } else { + healthStatus = new HealthStatus(503, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check failed to run db query"); + } + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Health Check"); + MDC.put("TargetServiceName", "Health Check"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Health check failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check"); + healthStatus = new HealthStatus(503, "health check failed: " + ex.toString()); + } finally { + postLogAudit(request); + } + if (healthStatus.getStatusCode() != 200) { + response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); + response.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, objectMapper.writeValueAsString(healthStatus)); + } + + return healthStatus; + } + */ + /** + * Checks application health and availability of dependent services + * + * @param request + * HttpServletRequest + * @return 200 if database access succeeds, 500 if it fails. + */ + @RequestMapping(value = { APP_SRVC_HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus srvcHealthCheck(HttpServletRequest request, HttpServletResponse response) throws Exception { + preLogAudit(request); + HealthStatus healthStatus = null; + StringBuffer sb = new StringBuffer(); + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + if (isDbConnUp()) { + sb.append(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)).append( " health check passed; "); + healthStatus = new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + sb.toString()); + } else { + sb.append(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)).append(" health check failed to run db query; "); + healthStatus = new HealthStatus(503, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + sb.toString()); + } + ControllerEndpointCredentials[] cec = getControllerEndpoints(); + + for(int i = 0; i < cec.length; ++i) { + // Check if API Handler is reachable + if (!isServiceReachable(cec[i].getUrl())) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "API Handler"); + MDC.put("TargetServiceName", "API Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "API Handler unreachable!"); + sb.append(" API Handler unreachable; "); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping API Handler"); + } + // Check if Inventory is reachable + if (!isServiceReachable(cec[i].getInventoryUrl()+"/dcae-services")) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "DCAE Inventory unreachable!"); + sb.append(" DCAE Inventory unreachable; "); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping DCAE Inventory"); + } + // Check if Deployment Handler is reachable + if (!isServiceReachable(cec[i].getDhandlerUrl())) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Deployment Handler"); + MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deployment Handler unreachable!"); + sb.append(" Deployment Handler unreachable; "); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping Deployment Handler"); + } + } + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Health Check"); + MDC.put("TargetServiceName", "Health Check"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Health check failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check"); + sb.append(" "); + sb.append(ex.toString()); + healthStatus = new HealthStatus(503, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check failed: " + sb.toString()); + } finally { + postLogAudit(request); + } + if (healthStatus.getStatusCode() != 200) { + response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); + response.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, objectMapper.writeValueAsString(healthStatus)); + } + return healthStatus; + } + + private boolean isDbConnUp() { + @SuppressWarnings("unchecked") + List list = dataAccessService.executeQuery(APP_DB_QRY, null); + if (list.size() > 0) { + return true; + } else { + return false; + } + } + + private App findApp() { + @SuppressWarnings("unchecked") + List list = dataAccessService.executeQuery(APP_DB_QRY, null); + return (list == null || list.isEmpty()) ? null : (App) list.get(0); + } + + public static boolean isServiceReachable(String targetUrl) throws IOException { + HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(targetUrl).openConnection(); + httpUrlConnection.setRequestMethod("HEAD"); + + try { + int responseCode = httpUrlConnection.getResponseCode(); + return responseCode == HttpURLConnection.HTTP_OK; + } catch (UnknownHostException noInternetConnection) { + return false; + } + } + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "Health Check"); + MDC.put("TargetServiceName", "Health Check"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java new file mode 100644 index 0000000..bdbf6ad --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java @@ -0,0 +1,984 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.ccsdk.dashboard.model.RestResponseError; +import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.model.inventory.Blueprint; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeServiceMap; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * Controller for Inventory features: services, service types, services groupby. + * Methods serve Ajax requests made by Angular scripts on pages that show + * content. + */ +@RestController +@RequestMapping("/inventory") +public class InventoryController extends DashboardRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InventoryController.class); + + /** + * Enum for selecting an item type. + */ + public enum InventoryDataItem { + SERVICES, SERVICE_TYPES, SERVICES_GROUPBY; + } + + private static Date begin, end; + private static final String SERVICES_PATH = "dcae-services"; + private static final String SERVICE_TYPES_PATH = "dcae-service-types"; + private static final String VIEW_SERVICE_TYPE_BLUEPRINT_PATH = "dcae-service-type-blueprint"; + private static final String DEPLOY_ROLE = ".k8.dev"; + private static final String DEP_IDS_FOR_TYPE = "dcae-services/typeIds"; + + /** + * ATT version with user role auth + * Gets one page of objects and supporting information via the REST client. + * On success, returns a PaginatedRestResponse object as String. + * + * @param option + * Specifies which item list type to get + * @param pageNum + * Page number of results + * @param pageSize + * Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception + * On any error; e.g., Network failure. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getItemListForPageAuth(HttpServletRequest request, InventoryDataItem option, int pageNum, int pageSize, String sortBy, String searchBy) + throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getControllerRestClient: Failed to get application user"); + InventoryClient inventoryClient = getInventoryClient(appUser.getId()); + + HttpSession session = AppUtils.getSession(request); + HashMap comp_deploy_tab = (HashMap)session.getAttribute("comp_access"); + String roleLevel = (String)session.getAttribute("role_level"); + + if (roleLevel == null) { + roleLevel = "app"; + } + if (comp_deploy_tab == null) { + comp_deploy_tab = new HashMap(); + } + + Set userApps = (Set)session.getAttribute("authComponents"); + if (userApps == null) { + userApps = new TreeSet(); + } + + List itemList = null; + List filterList = new ArrayList(); + List authDepList = new ArrayList(); + switch (option) { + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + if (roleLevel.equals("app")) { + for(String userRole : userApps) { + logger.debug(">>>> check component type from deployment: " + userRole); + for (Service cont: (List)itemList) { + String deplRef = cont.getDeploymentRef().toLowerCase(); + logger.debug(">>>> container deployment name: " + deplRef); + if (deplRef.contains(userRole)) { + logger.debug(">>>> adding deployment item to filtered subset"); + authDepList.add(cont); + } + } + } + } + + if (searchBy != null) { + if (!roleLevel.equals("app")) { + itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); + } else { + if (!authDepList.isEmpty()) { + authDepList = (List) authDepList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); + } + } + } + if (roleLevel.equals("app")) { + logger.debug(">>>> update response with authorized content"); + itemList.clear(); + itemList.addAll(authDepList); + } + + // check for authorization to perform delete deployed blueprints + + if (!roleLevel.equals("ops")) { + for (Service bp: (List)itemList) { + String deplRef = bp.getDeploymentRef().split("_")[0].toLowerCase(); + logger.debug(">>>> deployment reference: " + deplRef); + if (comp_deploy_tab.containsKey(deplRef) ) { + boolean enableDeploy = comp_deploy_tab.get(deplRef); + logger.debug(">>>> enable deploy button: " + enableDeploy); + bp.setCanDeploy(Optional.of(enableDeploy)); + } else { + bp.setCanDeploy(Optional.of(false)); + } + } + } else { + for (Service bp: (List)itemList) { + bp.setCanDeploy(Optional.of(true)); + } + } + + if (sortBy != null) { + if (sortBy.equals("deploymentRef")) { + Collections.sort(itemList, serviceDeploymentRefComparator); + } + else if (sortBy.equals("serviceId")) { + Collections.sort(itemList, serviceIdComparator); + } + else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceCreatedComparator); + } + else if (sortBy.equals("modified")) { + Collections.sort(itemList, serviceModifiedComparator); + } + } + break; + case SERVICE_TYPES: + ServiceTypeQueryParams serviceQueryParams = null; + serviceQueryParams = new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); + itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); + if (roleLevel.equals("app")) { + for(String userApp : userApps) { + logger.debug(">>>> check component type from BP: " + userApp); + for (ServiceType bp: (List)itemList) { + String bpComp = bp.getComponent(); + String bpOwner = bp.getOwner(); // for backward compatibility + logger.debug(">>>> BP component name: " + bpComp); + if ( (bpComp != null && bpComp.equalsIgnoreCase(userApp)) || bpOwner.contains(userApp) ) { + logger.debug(">>>> adding item to filtered subset"); + filterList.add(bp); + } + } + } + } + if (searchBy != null) { + if (!roleLevel.equals("app")) { + itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList()); + } else { + if (!filterList.isEmpty()) { + filterList = (List) filterList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList()); + } + } + } + if (roleLevel.equals("app")) { + logger.debug(">>>> update response with authorized content"); + itemList.clear(); + itemList.addAll(filterList); + } + + // check for authorization to perform update/delete/deploy blueprints + if (!roleLevel.equals("ops")) { + for (ServiceType bp: (List)itemList) { + String bpComp = bp.getComponent(); + if (bpComp != null && bpComp.length() > 0) { + bpComp = bpComp.toLowerCase(); + } else { + String bpOwner = bp.getOwner(); // for backward compatibility + if (bpOwner != null && bpOwner.contains(":")) { + bpComp = bp.getOwner().split(":")[0].toLowerCase(); + } + } + logger.debug(">>>> BP component name: " + bpComp); + if (comp_deploy_tab.containsKey(bpComp) ) { + boolean enableDeploy = comp_deploy_tab.get(bpComp); + logger.debug(">>>> enable deploy button: " + enableDeploy); + bp.setCanDeploy(Optional.of(enableDeploy)); + } else { + bp.setCanDeploy(Optional.of(false)); + } + } + } else { + for (ServiceType bp: (List)itemList) { + bp.setCanDeploy(Optional.of(true)); + } + } + + if (sortBy != null) { + if (sortBy.equals("owner")) { + Collections.sort(itemList, serviceTypeOwnerComparator); + } + else if (sortBy.equals("typeId")) { + Collections.sort(itemList, serviceTypeIdComparator); + } + else if (sortBy.equals("typeName")) { + Collections.sort(itemList, serviceTypeNameComparator); + } + else if (sortBy.equals("typeVersion")) { + Collections.sort(itemList, serviceTypeVersionComparator); + } + else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceTypeCreatedComparator); + } + else if (sortBy.equals("application")) { + Collections.sort(itemList, serviceTypeApplComparator); + } + else if (sortBy.equals("component")) { + Collections.sort(itemList, serviceTypeCompComparator); + } + } + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + } + + // Shrink if needed + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + /** + * Gets one page of objects and supporting information via the REST client. + * On success, returns a PaginatedRestResponse object as String. + * + * @param option + * Specifies which item list type to get + * @param pageNum + * Page number of results + * @param pageSize + * Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception + * On any error; e.g., Network failure. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getItemListForPage(HttpServletRequest request, InventoryDataItem option, int pageNum, int pageSize, String sortBy, String searchBy) + throws Exception { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getControllerRestClient: Failed to get application user"); + InventoryClient inventoryClient = getInventoryClient(appUser.getId()); + + List itemList = null; + switch (option) { + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + // Get the tenant names for all the deployments from Cloudify/API handler + ECTransportModel result = null; + List tenantList = new ArrayList(); + try { + CloudifyClient restClient = getCloudifyRestClient(request); + List cldfyTen = restClient.getTenants().items; + for (CloudifyTenant ct: (List)cldfyTen) { + result = restClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList)result).items); + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getTenantInfoFromDeploy caught exception"); + result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + result = new RestResponseError("getTenantInfoFromDeploy failed", t); + } finally { + postLogAudit(request); + } + for (Service depl: (List)itemList) { + for (CloudifyDeployedTenant deplTen: tenantList) { + if (depl.getDeploymentRef().equals(deplTen.id)) { + depl.setTenant(deplTen.tenant_name); + break; + } + } + } + if (searchBy != null) { + itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); + } + for (Service bp: (List)itemList) { + bp.setCanDeploy(Optional.of(true)); + } + if (sortBy != null) { + if (sortBy.equals("deploymentRef")) { + Collections.sort(itemList, serviceDeploymentRefComparator); + } + else if (sortBy.equals("serviceId")) { + Collections.sort(itemList, serviceIdComparator); + } + else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceCreatedComparator); + } + else if (sortBy.equals("modified")) { + Collections.sort(itemList, serviceModifiedComparator); + } + } + break; + case SERVICE_TYPES: + itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); + if (searchBy != null) { + itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList()); + } + for (ServiceType bp: (List)itemList) { + bp.setCanDeploy(Optional.of(true)); + } + if (sortBy != null) { + if (sortBy.equals("owner")) { + Collections.sort(itemList, serviceTypeOwnerComparator); + } + else if (sortBy.equals("typeId")) { + Collections.sort(itemList, serviceTypeIdComparator); + } + else if (sortBy.equals("typeName")) { + Collections.sort(itemList, serviceTypeNameComparator); + } + else if (sortBy.equals("typeVersion")) { + Collections.sort(itemList, serviceTypeVersionComparator); + } + else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceTypeCreatedComparator); + } + else if (sortBy.equals("application")) { + Collections.sort(itemList, serviceTypeApplComparator); + } + else if (sortBy.equals("component")) { + Collections.sort(itemList, serviceTypeCompComparator); + } + } + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + } + + // Shrink if needed + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + + RestResponsePage model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + + /** + * Gets one page of the specified items. This method traps exceptions and + * constructs an appropriate JSON block to report errors. + * + * @param request + * Inbound request + * @param option + * Item type to get + * @return JSON with one page of objects; or an error. + */ + protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, String sortBy, String searchBy) { + preLogAudit(request); + String outboundJson = null; + try { + int pageNum = getRequestPageNumber(request); + int pageSize = getRequestPageSize(request); + String appEnv = "os"; + appEnv = getAppProperties().getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "att"); + if (appEnv.equals("os")) { + outboundJson = getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy); + } else { + outboundJson = getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy); + } + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + RestResponseError result = null; + if (ex instanceof HttpStatusCodeException) + result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + else + result = new RestResponseError("Failed to get " + option.name(), ex); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } finally { + postLogAudit(request); + } + return outboundJson; + } + + /** + * Supports sorting service types by owner + */ + private static Comparator serviceTypeOwnerComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getOwner().compareToIgnoreCase(o2.getOwner()); + } + }; + + /** + * Supports sorting service types by application + */ + private static Comparator serviceTypeApplComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getApplication().compareToIgnoreCase(o2.getApplication()); + } + }; + + /** + * Supports sorting service types by component + */ + private static Comparator serviceTypeCompComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getComponent().compareToIgnoreCase(o2.getComponent()); + } + }; + + /** + * Supports sorting service types by type id + */ + private static Comparator serviceTypeIdComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getTypeId().get().compareToIgnoreCase(o2.getTypeId().get()); + } + }; + + /** + * Supports sorting service types by type name + */ + private static Comparator serviceTypeNameComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getTypeName().compareToIgnoreCase(o2.getTypeName()); + } + }; + + /** + * Supports sorting service types by type version + */ + private static Comparator serviceTypeVersionComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getTypeVersion().compareTo(o2.getTypeVersion()); + } + }; + + /** + * Supports sorting service types by created date + */ + private static Comparator serviceTypeCreatedComparator = new Comparator() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getCreated().get().compareToIgnoreCase(o2.getCreated().get()); + } + }; + + /** + * Supports sorting services by deploymentRef + */ + private static Comparator serviceDeploymentRefComparator = new Comparator() { + @Override + public int compare(Service o1, Service o2) { + return o1.getDeploymentRef().compareToIgnoreCase(o2.getDeploymentRef()); + } + }; + + /** + * Supports sorting services by service id + */ + private static Comparator serviceIdComparator = new Comparator() { + @Override + public int compare(Service o1, Service o2) { + return o1.getServiceId().compareToIgnoreCase(o2.getServiceId()); + } + }; + + /** + * Supports sorting services by created date + */ + private static Comparator serviceCreatedComparator = new Comparator() { + @Override + public int compare(Service o1, Service o2) { + return o1.getCreated().compareToIgnoreCase(o2.getCreated()); + } + }; + + /** + * Supports sorting services by created date + */ + private static Comparator serviceModifiedComparator = new Comparator() { + @Override + public int compare(Service o1, Service o2) { + return o1.getModified().compareToIgnoreCase(o2.getModified()); + } + }; + + /** + * Serves one page of service types + * + * @param request + * HttpServletRequest + * @return List of ServiceTypes objects + */ + @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getServiceTypesByPage(HttpServletRequest request) { + preLogAudit(request); + String json = null; + //json = getMockDataContent("/serviceTypesList.json"); + json = + getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("sortBy"), request.getParameter("searchBy")); + postLogAudit(request); + return json; + } + + + private String getMockDataContent(final String path) { + String result = null; + try { + InputStream is = getClass().getResourceAsStream(path); + if (is == null) + throw new Exception("Failed to find resource at path " + path); + Scanner scanner = new Scanner(is, "UTF-8"); + result = scanner.useDelimiter("\\A").next(); + scanner.close(); + is.close(); + } catch (Exception ex) { + logger.error("getMockDataContent failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + /** + * Query Service objects matching a service type ID + * + */ + @RequestMapping(value = { DEP_IDS_FOR_TYPE }, method = RequestMethod.POST, produces = "application/json") + public String getServicesForType( HttpServletRequest request, + @RequestBody String[] typeList) + throws Exception { + preLogAudit(request); + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getId() == null ) + throw new Exception("getControllerRestClient: Failed to get application user"); + InventoryClient inventoryClient = getInventoryClient(appUser.getId()); + List result = new ArrayList(); + for (String typeId: typeList) { + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); + result.add(srvcMap); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Serves one page of services + * + * @param request + * HttpServletRequest + * + * @return List of Service objects + */ + @RequestMapping(value = { SERVICES_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getServicesByPage(HttpServletRequest request) { + //preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, request.getParameter("sortBy"), request.getParameter("searchBy")); + postLogAudit(request); + return json; + } + /** + * Gets the specified blueprint content for viewing. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @return Blueprint as YAML; or error. + * @throws Exception + * on serialization error + * + */ + @RequestMapping(value = { + VIEW_SERVICE_TYPE_BLUEPRINT_PATH + "/{typeid}" }, method = RequestMethod.GET, produces = "application/yaml") + @ResponseBody + public String viewServiceTypeBlueprintContentById(@PathVariable("typeid") String typeId, HttpServletRequest request) throws Exception { + preLogAudit(request); + String json = null; + try { + InventoryClient inventoryClient = getInventoryClient(request); + json = objectMapper.writeValueAsString(inventoryClient.getServiceType(typeId).get()); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("getBlueprintContentById failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Deletes the specified blueprint. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return status code on success; error on failure. + * @throws Exception + * On serialization failure + */ + @RequestMapping(value = { SERVICE_TYPES_PATH + "/{typeid}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteServiceType(@PathVariable("typeid") String typeid, HttpServletRequest request, + HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = "{\"202\": \"OK\"}"; + try { + InventoryClient inventoryClient = getInventoryClient(request); + inventoryClient.deleteServiceType(typeid); + } catch (ServiceTypeNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServiceTypeAlreadyDeactivatedException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Deletes the specified service i.e. deployment from inventory + * + * @param id + * Service ID + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return status code on success; error on failure. + * @throws Exception + * On serialization failure + */ + @RequestMapping(value = { SERVICES_PATH + "/{serviceId}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteService(@PathVariable("serviceId") String serviceId, HttpServletRequest request, + HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = "{\"202\": \"OK\"}"; + try { + InventoryClient inventoryClient = getInventoryClient(request); + inventoryClient.deleteService(serviceId); + } catch (ServiceTypeNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (ServiceTypeAlreadyDeactivatedException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Processes request to update a blueprint currently existing in DCAE Inventory. + * + * @param request + * HttpServletRequest + * @param blueprint + * Cloudify blueprint + * @return Blueprint as uploaded; or error. + * @throws Exception + * on serialization error + */ + @RequestMapping(value = { SERVICE_TYPES_PATH + "/update"}, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String updateServiceTypeBlueprint(HttpServletRequest request, @RequestBody ServiceType serviceType) + throws Exception { + preLogAudit(request); + String json = "{\"201\": \"OK\"}"; + try { + // Verify that the Service Type can be parsed for inputs. + Blueprint.parse(serviceType.getBlueprintTemplate()); + InventoryClient inventoryClient = getInventoryClient(request); + inventoryClient.addServiceType(serviceType); + } catch (BlueprintParseException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Processes request to update a blueprint currently existing in DCAE Inventory. + * + * @param request + * HttpServletRequest + * @param blueprint + * Cloudify blueprint + * @return Blueprint as uploaded; or error. + * @throws Exception + * on serialization error + */ + @RequestMapping(value = { SERVICE_TYPES_PATH + "/upload" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String uploadServiceTypeBlueprint(HttpServletRequest request, + @RequestBody ServiceTypeRequest serviceTypeRequest) + throws Exception { + preLogAudit(request); + String json = "{\"201\": \"OK\"}"; + try { + Blueprint.parse(serviceTypeRequest.getBlueprintTemplate()); + InventoryClient inventoryClient = getInventoryClient(request); + inventoryClient.addServiceType(serviceTypeRequest); + } catch (BlueprintParseException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Updating service type failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); + json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + public void preLogAudit(HttpServletRequest request) { + begin = new Date(); + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); + MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); + //logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); + } + + public void postLogAudit(HttpServletRequest request) { + end = new Date(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); + MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java index 397f2ed..2905dca 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java @@ -1,71 +1,91 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.domain; - -import org.onap.portalsdk.core.domain.support.DomainVo; - -/** - * Model for controller endpoint information stored in database. A single row - * for a user represents a selected endpoint. - */ -public class ControllerEndpoint extends DomainVo { - - private static final long serialVersionUID = 8785223545128054402L; - - private long userId; - private String name; - private String url; - - public ControllerEndpoint() { - } - - public ControllerEndpoint(long userId, String name, String url) { - this.userId = userId; - this.name = name; - this.url = url; - } - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.domain; + +import org.onap.portalsdk.core.domain.support.DomainVo; + +/** + * Model for controller endpoint information stored in database. A single row + * for a user represents a selected endpoint. + */ +public class ControllerEndpoint extends DomainVo { + + private static final long serialVersionUID = 8785223545128054402L; + + private long userId; + private String name; + private String url; + private String inventoryUrl; + private String dhandlerUrl; + + public ControllerEndpoint() { + } + + public ControllerEndpoint(long userId, String name, String url, String inventoryUrl, String dhandlerUrl) { + this.userId = userId; + this.name = name; + this.url = url; + this.inventoryUrl = inventoryUrl; + this.dhandlerUrl = dhandlerUrl; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getInventoryUrl() { + return inventoryUrl; + } + + public void setInventoryUrl(String inventoryUrl) { + this.inventoryUrl = inventoryUrl; + } + + public String getDhandlerUrl() { + return dhandlerUrl; + } + + public void setDhandlerUrl(String dhandlerUrl) { + this.dhandlerUrl = dhandlerUrl; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java new file mode 100644 index 0000000..719ad23 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.domain; + +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.domain.support.DomainVo; + +public class EcdComponent extends DomainVo { + + private static final long serialVersionUID = 1L; + + private Long compId; + private String cname; // component name + private String dname; // component display name + public Long getCompId() { + return compId; + } + public void setCompId(Long compId) { + this.compId = compId; + } + public String getCname() { + return cname; + } + public void setCname(String cname) { + this.cname = cname; + } + public String getDname() { + return dname; + } + public void setDname(String dname) { + this.dname = dname; + } + + public boolean contains(String searchString) { + if (StringUtils.containsIgnoreCase(this.getCname(), searchString) || + StringUtils.containsIgnoreCase(this.getDname(), searchString)) { + return true; + } + return false; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exception/DashboardControllerException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exception/DashboardControllerException.java deleted file mode 100644 index f288741..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exception/DashboardControllerException.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.onap.ccsdk.dashboard.exception; - -/** - * A little something to placate the Sonar code-analysis tool. - */ -public class DashboardControllerException extends Exception { - - private static final long serialVersionUID = -1373841666122351816L; - - public DashboardControllerException() { - super(); - } - - public DashboardControllerException(String message) { - super(message); - } - - public DashboardControllerException(String message, Throwable cause) { - super(message, cause); - } - - public DashboardControllerException(Throwable cause) { - super(cause); - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java new file mode 100644 index 0000000..bd75bac --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.exceptions; + +public class BadRequestException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8654510668910559419L; + + public BadRequestException (String message) { + super(message); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java new file mode 100644 index 0000000..c1de4fe --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.exceptions; + +/** + * A little something to placate the Sonar code-analysis tool. + */ +public class DashboardControllerException extends Exception { + + private static final long serialVersionUID = -1373841666122351816L; + + public DashboardControllerException() { + super(); + } + + public DashboardControllerException(String message) { + super(message); + } + + public DashboardControllerException(String message, Throwable cause) { + super(message, cause); + } + + public DashboardControllerException(Throwable cause) { + super(cause); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DeploymentNotFoundException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DeploymentNotFoundException.java new file mode 100644 index 0000000..4785823 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DeploymentNotFoundException.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.exceptions; + +public class DeploymentNotFoundException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -5983803277201006988L; + + public DeploymentNotFoundException (String message) { + super(message); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DownstreamException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DownstreamException.java new file mode 100644 index 0000000..72a6dbe --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DownstreamException.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.exceptions; + +public class DownstreamException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 142869535142369337L; + + public DownstreamException (String message) { + super(message); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServerErrorException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServerErrorException.java new file mode 100644 index 0000000..f87dc3e --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServerErrorException.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.exceptions; + +public class ServerErrorException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 8366380783861251332L; + + public ServerErrorException(String message) { + super(message); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServiceAlreadyExistsException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServiceAlreadyExistsException.java new file mode 100644 index 0000000..117d506 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/ServiceAlreadyExistsException.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.exceptions; + +public class ServiceAlreadyExistsException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -4696234983451006280L; + + public ServiceAlreadyExistsException (String message) { + super(message); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseException.java new file mode 100644 index 0000000..2e7f5fe --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseException.java @@ -0,0 +1,10 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class BlueprintParseException extends Exception { + + private static final long serialVersionUID = -6334355506595623685L; + + public BlueprintParseException(Throwable cause) { + super(cause); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedException.java new file mode 100644 index 0000000..1b0e2d8 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedException.java @@ -0,0 +1,13 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceAlreadyDeactivatedException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 7268552618026889672L; + + public ServiceAlreadyDeactivatedException (String message) { + super(message); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundException.java new file mode 100644 index 0000000..de4a549 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundException.java @@ -0,0 +1,9 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceNotFoundException extends Exception { + + private static final long serialVersionUID = -8183806298586822720L; + + public ServiceNotFoundException() { super(); } + public ServiceNotFoundException (String message) { super(message); } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveException.java new file mode 100644 index 0000000..ce799f5 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveException.java @@ -0,0 +1,11 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceTypeActiveException extends Exception { + + private static final long serialVersionUID = 7403567744784579153L; + + public ServiceTypeActiveException() { super(); } + public ServiceTypeActiveException(String msg) { super(msg); } + public ServiceTypeActiveException(Throwable cause) { super(cause); } + public ServiceTypeActiveException(String msg, Throwable cause) { super(msg, cause); } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedException.java new file mode 100644 index 0000000..e7d1f8c --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedException.java @@ -0,0 +1,13 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceTypeAlreadyDeactivatedException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -4359544421618429774L; + + public ServiceTypeAlreadyDeactivatedException (String message) { + super(message); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyExistsException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyExistsException.java new file mode 100644 index 0000000..806d127 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyExistsException.java @@ -0,0 +1,11 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceTypeAlreadyExistsException extends Exception { + + private static final long serialVersionUID = 8146558049192514157L; + + public ServiceTypeAlreadyExistsException() { super(); } + public ServiceTypeAlreadyExistsException(String msg) { super(msg); } + public ServiceTypeAlreadyExistsException(Throwable cause) { super(cause); } + public ServiceTypeAlreadyExistsException(String msg, Throwable cause) { super(msg, cause); } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeNotFoundException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeNotFoundException.java new file mode 100644 index 0000000..54cffcf --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeNotFoundException.java @@ -0,0 +1,12 @@ +package org.onap.ccsdk.dashboard.exceptions.inventory; + +public class ServiceTypeNotFoundException extends Exception { + + private static final long serialVersionUID = 1218738334353236154L; + + public ServiceTypeNotFoundException() { super(); } + + public ServiceTypeNotFoundException (String message) { + super(message); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java index f66a072..47503f8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintContent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintContent.java index 6b95eaa..2c64efe 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintContent.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintContent.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintList.java index a9a98a1..114a823 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintList.java @@ -1,8 +1,9 @@ + /******************************************************************************* * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintUpload.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintUpload.java index 70e093b..d7cf0d3 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintUpload.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintUpload.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenant.java new file mode 100644 index 0000000..f8b13e0 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenant.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyDeployedTenant extends ECTransportModel { + + /** A unique identifier for the deployment. */ + public final String id; + /** tenant where the deployment was done */ + public final String tenant_name; + /** The id of the blueprint the deployment is based on. */ + public final String blueprint_id; + + @JsonCreator + public CloudifyDeployedTenant(@JsonProperty("id") String id, + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("tenant_name") String tenant_name) { + this.id = id; + this.blueprint_id = blueprint_id; + this.tenant_name = tenant_name; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenantList.java new file mode 100644 index 0000000..8c6a39d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenantList.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyDeployedTenantList extends ECTransportModel { + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyDeployedTenantList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java index 126fe9c..4e07c1f 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public final class CloudifyDeployment extends ECTransportModel { * A dictionary containing key value pairs which represents a deployment * input and its provided value. */ - public final Inputs inputs; + public final Map inputs; /** A dictionary containing policies of a deployment. */ public final Map policy_types; /** A dictionary containing policy triggers of a deployment. */ @@ -60,15 +60,17 @@ public final class CloudifyDeployment extends ECTransportModel { /** A list of workflows that can be executed on a deployment. */ public final List workflows; + public final String tenant_name; + @JsonCreator public CloudifyDeployment(@JsonProperty("description") String description, @JsonProperty("blueprint_id") String blueprint_id, @JsonProperty("created_at") String created_at, @JsonProperty("updated_at") String updated_at, @JsonProperty("id") String id, - @JsonProperty("inputs") Inputs inputs, @JsonProperty("policy_types") Map policy_types, + @JsonProperty("inputs") Map inputs, @JsonProperty("policy_types") Map policy_types, @JsonProperty("policy_triggers") Map policy_triggers, @JsonProperty("outputs") Map outputs, @JsonProperty("groups") Map groups, @JsonProperty("scaling_groups") Map scaling_groups, - @JsonProperty("workflows") List workflows) { + @JsonProperty("workflows") List workflows, @JsonProperty("tenant_name") String tenant_name) { this.description = description; this.blueprint_id = blueprint_id; this.created_at = created_at; @@ -81,6 +83,7 @@ public final class CloudifyDeployment extends ECTransportModel { this.groups = groups; this.scaling_groups = scaling_groups; this.workflows = workflows; + this.tenant_name = tenant_name; } public static final class Inputs { diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java index 51b6169..4a26767 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java index 32c7199..92c7ec3 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java new file mode 100644 index 0000000..cecece3 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message POST-ed to controller to update a Cloudify Deployment: + * + * NOTE: THIS IS NOT HOW THE REQUEST TO CLOUDIFY'S ENDPOINT LOOKS. THE REQUEST IS CONSTRUCTED IN PROPER FORMAT IN THE API HANDLER + *
+ * {
+	"deployment_id" : "deployment-id",	 
+	"workflow_name" : "workflow-name",
+    "allow_custom_parameter" : "true|false",
+    "force" : "true|false",
+    "node_instance_id": "node-instance-id",
+    "limits_cpu": limits_cpu,
+    "limits_mem": limits_mem,
+    "image": "image",
+    "replicas": replicas,
+    "container_name": "container_name"
+  }
+ * 
+ */ +public final class CloudifyDeploymentUpdateRequest extends ECTransportModel { + + /** A unique identifier for the deployment. */ + public final String deployment_id; + /** A unique identifier for the workflow */ + public final String workflow_name; + public final Boolean allow_custom_parameter; + public final Boolean force; + /** Parameters: retrieve using the GET /deployments */ + //public final Map parameters; + public final String node_instance_id; + public final String limits_cpu; + public final String limits_mem; + public final String image; + public final Number replicas; + public final String container_name; + + @JsonCreator + public CloudifyDeploymentUpdateRequest(@JsonProperty("deployment_id") String deployment_id, + @JsonProperty("workflow_name") String workflow_name, + @JsonProperty("allow_custom_parameter") Boolean allowCustomParameter, + @JsonProperty("force") Boolean force, + @JsonProperty("node_instance_id") String node_instance_id, + @JsonProperty("limits_cpu") String limits_cpu, + @JsonProperty("limits_mem") String limits_mem, + @JsonProperty("image") String image, + @JsonProperty("replicas") Number replicas, + @JsonProperty("container_name") String container_name) { + + this.deployment_id = deployment_id; + this.workflow_name = workflow_name; + this.allow_custom_parameter = allowCustomParameter; + this.force = force; + //this.parameters = parameters; + this.node_instance_id = node_instance_id; + this.limits_cpu = limits_cpu; + this.limits_mem = limits_mem; + this.image = image; + this.replicas = replicas; + this.container_name = container_name; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java new file mode 100644 index 0000000..19134a4 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model with fields only for the top-level attributes. All complex child + * structures are represented simply as generic collections. + */ +public final class CloudifyDeploymentUpdateResponse extends ECTransportModel { + + /** A unique identifier for the execution. */ + public final String id; + /** The executions status. */ + public final String status; + /** The time the execution was queued at. */ + public final String created_at; + /** The id/name of the workflow the execution is of. */ + public final String workflow_id; + /** true if the execution is of a system workflow. */ + public final Boolean is_system_workflow; + /** The id of the blueprint the execution is in the context of. */ + public final String blueprint_id; + /** The id of the deployment the execution is in the context of. */ + public final String deployment_id; + /** The execution’s error message on execution failure. */ + public final String error; + /** A dict of the workflow parameters passed when starting the execution. */ + public final Map parameters; + + public final String tenant_name; + + public final String created_by; + + public final Boolean private_resource; + + public final String resource_availability; + + + @JsonCreator + public CloudifyDeploymentUpdateResponse(@JsonProperty("status") String status, + @JsonProperty("created_at") String created_at, + @JsonProperty("workflow_id") String workflow_id, + @JsonProperty("is_system_workflow") Boolean is_system_workflow, + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("error") String error, + @JsonProperty("id") String id, + @JsonProperty("parameters") Map parameters, + @JsonProperty("tenant_name") String tenant_name, + @JsonProperty("created_by") String created_by, + @JsonProperty("private_resource") Boolean private_resource, + @JsonProperty("resource_availability") String resource_availability) { + + this.status = status; + this.created_at = created_at; + this.workflow_id = workflow_id; + this.is_system_workflow = is_system_workflow; + this.blueprint_id = blueprint_id; + this.deployment_id = deployment_id; + this.error = error; + this.id = id; + this.parameters = parameters; + this.tenant_name = tenant_name; + this.created_by = created_by; + this.private_resource = private_resource; + this.resource_availability = resource_availability; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java new file mode 100644 index 0000000..3f3a8fa --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message POST-ed to controller to execute upgrade workflow on a Cloudify Deployment: + * + * NOTE: THIS IS NOT HOW THE REQUEST TO CLOUDIFY'S ENDPOINT LOOKS. THE REQUEST IS CONSTRUCTED IN PROPER FORMAT IN THE API HANDLER + *
+*		{
+				"config_url": config_url,
+				"config_format": config_format,
+				"chartRepo": chartRepo,
+				"chartVersion": chartVersion
+		};
+ * 
+ */ +public final class CloudifyDeploymentUpgradeRequest extends ECTransportModel { + + public final String config_url; + public final String config_format; + public final String chartRepo; + public final String chartVersion; + + @JsonCreator + public CloudifyDeploymentUpgradeRequest( + @JsonProperty("config_url") String config_url, + @JsonProperty("config_format") String config_format, + @JsonProperty("chartRepo") String chartRepo, + @JsonProperty("chartVersion") String chartVersion) { + + this.config_url = config_url; + this.config_format = config_format; + this.chartRepo = chartRepo; + this.chartVersion = chartVersion; + } + + public String getConfig_url() { + return config_url; + } + + public String getConfig_format() { + return config_format; + } + + public String getChartRepo() { + return chartRepo; + } + + public String getChartVersion() { + return chartVersion; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyErrorCause.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyErrorCause.java new file mode 100644 index 0000000..468b62d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyErrorCause.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyErrorCause extends ECTransportModel { + + /** Error message */ + public final String message; + + /** Stack trace at the point where the exception was raised */ + public final String traceback; + + /** Exception type */ + public final String type; + + @JsonCreator + public CloudifyErrorCause( + @JsonProperty("message") String message, + @JsonProperty("traceback") String traceback, + @JsonProperty("type") String type) { + + this.message = message; + this.traceback = traceback; + this.type = type; + } + + @Override + public String toString() { + return "CloudifyErrorCause [message=" + message + ", traceback=" + traceback + ", type=" + type + "]"; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java new file mode 100644 index 0000000..4910f9f --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.LinkedList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyEvent extends ECTransportModel { + + /** The id of the blueprint the execution is in the context of. */ + public final String blueprint_id; + /** The id of the deployment the execution is in the context of. */ + public final String deployment_id; + /** List of errors that happened while executing a given task */ + public final List error_causes; + /** The executions status. */ + public final String event_type; + /** The time the execution was queued at. */ + public final String execution_id; + /** log level */ + public final String level; + /** logger id */ + public final String logger; + /** message text */ + public final String message; + /** node instance id */ + public final String node_instance_id; + /** node name */ + public final String node_name; + /** Operation path */ + public final String operation; + /** time at which the event occurred on the executing machine */ + public final String reported_timestamp; + /** time at which the event was logged on the management machine */ + public final String timestamp; + /** resource is a cloudify_event or a cloudify_log */ + public final String type; + /** The id/name of the workflow the execution is of. */ + public final String workflow_id; + + @JsonCreator + public CloudifyEvent( + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("error_causes") List error_causes, + @JsonProperty("event_type") String event_type, + @JsonProperty("execution_id") String execution_id, + @JsonProperty("level") String level, + @JsonProperty("logger") String logger, + @JsonProperty("message") String message, + @JsonProperty("node_instance_id") String node_instance_id, + @JsonProperty("node_name") String node_name, + @JsonProperty("operation") String operation, + @JsonProperty("reported_timestamp") String reported_timestamp, + @JsonProperty("timestamp") String timestamp, + @JsonProperty("type") String type, + @JsonProperty("workflow_id") String workflow_id) { + + this.blueprint_id = blueprint_id; + this.deployment_id = deployment_id; + this.error_causes = (error_causes == null) ? new LinkedList () : error_causes; + this.event_type = event_type; + this.execution_id = execution_id; + this.level = level; + this.logger = logger; + this.message = message; + this.node_instance_id = node_instance_id; + this.node_name = node_name; + this.operation = operation; + this.reported_timestamp = reported_timestamp; + this.timestamp = timestamp; + this.type = type; + this.workflow_id = workflow_id; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEventList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEventList.java new file mode 100644 index 0000000..d633faa --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEventList.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyEventList extends ECTransportModel { + + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyEventList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java index 071ef57..e701528 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,18 +46,28 @@ public final class CloudifyExecution extends ECTransportModel { public final String blueprint_id; /** The id of the deployment the execution is in the context of. */ public final String deployment_id; + /** The tenant used to deploy */ + public final String tenant_name; /** The execution’s error message on execution failure. */ public final String error; /** A dict of the workflow parameters passed when starting the execution. */ public final Map parameters; + /** true if helm plugin is used */ + public Boolean is_helm; + /** true if helm status is enabled */ + public Boolean helm_status; @JsonCreator public CloudifyExecution(@JsonProperty("status") String status, @JsonProperty("created_at") String created_at, @JsonProperty("workflow_id") String workflow_id, @JsonProperty("is_system_workflow") Boolean is_system_workflow, - @JsonProperty("blueprint_id") String blueprint_id, @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("tenant_name") String tenant_name, @JsonProperty("error") String error, @JsonProperty("id") String id, - @JsonProperty("parameters") Map parameters) { + @JsonProperty("parameters") Map parameters, + @JsonProperty("is_helm") Boolean is_helm, + @JsonProperty("helm_status") Boolean helm_status) { this.status = status; this.created_at = created_at; @@ -65,9 +75,12 @@ public final class CloudifyExecution extends ECTransportModel { this.is_system_workflow = is_system_workflow; this.blueprint_id = blueprint_id; this.deployment_id = deployment_id; + this.tenant_name = tenant_name; this.error = error; this.id = id; this.parameters = parameters; + this.is_helm = is_helm; + this.helm_status = helm_status; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java index 5909c62..e493c70 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java index d787fec..c333faf 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,42 +26,78 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -/** - * Model for message POST-ed to controller to create a Cloudify Execution: - * - *
- * {
-	"deployment_id" : "deployment-id",	 
-	"workflow_name" : "workflow-name",
-    "allow_custom_parameter" : "true|false",
-    "force" : "true|false",
-    "parameters":
-       {
-           
-       }
-  }
- * 
- */ -public final class CloudifyExecutionRequest extends ECTransportModel { +public class CloudifyExecutionRequest extends ECTransportModel { /** A unique identifier for the deployment. */ - public final String deployment_id; + public String deployment_id; /** A unique identifier for the workflow */ - public final String workflow_name; - public final Boolean allow_custom_parameter; - public final Boolean force; + public String workflow_id; + public Boolean allow_custom_parameters; + public Boolean force; + public String tenant; /** Parameters: retrieve using the GET /deployments */ - public final Map parameters; + public Map parameters; + + public String getDeployment_id() { + return deployment_id; + } + + public String getWorkflow_id() { + return workflow_id; + } + + public Boolean getAllow_custom_parameters() { + return allow_custom_parameters; + } + + public Boolean getForce() { + return force; + } + + public String getTenant() { + return tenant; + } + + public Map getParameters() { + return parameters; + } + + public void setDeployment_id(String deployment_id) { + this.deployment_id = deployment_id; + } + + public void setWorkflow_id(String workflow_id) { + this.workflow_id = workflow_id; + } + + public void setAllow_custom_parameters(Boolean allow_custom_parameters) { + this.allow_custom_parameters = allow_custom_parameters; + } + + public void setForce(Boolean force) { + this.force = force; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } @JsonCreator public CloudifyExecutionRequest(@JsonProperty("deployment_id") String deployment_id, - @JsonProperty("workflow_name") String workflow_name, - @JsonProperty("allow_custom_parameter") Boolean allowCustomParameter, @JsonProperty("force") Boolean force, + @JsonProperty("workflow_id") String workflow_id, + @JsonProperty("allow_custom_parameters") Boolean allowCustomParameters, + @JsonProperty("force") Boolean force, + @JsonProperty("tenant") String tenant, @JsonProperty("parameters") Map parameters) { this.deployment_id = deployment_id; - this.workflow_name = workflow_name; - this.allow_custom_parameter = allowCustomParameter; + this.workflow_id = workflow_id; + this.allow_custom_parameters = allowCustomParameters; this.force = force; + this.tenant = tenant; this.parameters = parameters; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeId.java new file mode 100644 index 0000000..b275466 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeId.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyNodeId extends ECTransportModel { + /** The id of the node */ + public final String id; + + @JsonCreator + public CloudifyNodeId(@JsonProperty("id") String id) { + this.id = id; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeIdList.java new file mode 100644 index 0000000..95795d6 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeIdList.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyNodeIdList { + + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyNodeIdList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstance.java similarity index 52% rename from ccsdk-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java rename to ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstance.java index ce00583..adbc02a 100644 --- a/ccsdk-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstance.java @@ -1,58 +1,44 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.fusionapp.service; - -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.fusion.core.MockApplicationContextTestSuite; -import org.onap.portalsdk.core.domain.Profile; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.service.ProfileService; -import org.onap.portalsdk.core.service.UserProfileService; -import org.springframework.beans.factory.annotation.Autowired; - - -public class ProfileServiceTest extends MockApplicationContextTestSuite { - - @Autowired - ProfileService service; - - @Autowired - UserProfileService userProfileService; - - @Test - public void testFindAll() throws Exception { - - List profiles = service.findAll(); - Assert.assertTrue(profiles.size() > 0); - } - - @Test - public void testFindAllActive() { - - List users = userProfileService.findAllActive(); - List activeUsers = userProfileService.findAllActive(); - Assert.assertTrue(users.size() - activeUsers.size() >= 0); - } -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyNodeInstance extends ECTransportModel { + + /** The id of the node instance. */ + public final String id; + + /** The runtime properties of the node instance. */ + public final Map runtime_properties; + + @JsonCreator + public CloudifyNodeInstance(@JsonProperty("id") String id, + @JsonProperty("runtime_properties") Map runtime_properties) { + this.id = id; + this.runtime_properties = runtime_properties; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java new file mode 100644 index 0000000..f87d34c --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model with fields only for the top-level attributes. All complex child + * structures are represented as generic collections. + */ +public final class CloudifyNodeInstanceId extends ECTransportModel { + + /** The id of the node instance. */ + public final String id; + + + + /** The name of the user that created the node instance */ + //public final String created_by; + /** The id of the deployment the node instance belongs to. */ + //public final String deployment_id; + /** The Compute node instance id the node is contained within. */ + //public final String host_id; + /** The relationships the node has with other nodes. */ + //public final List relationships; + /** The runtime properties of the node instance. */ + //public final String runtime_properties; + /** The node instance state. */ + //public final String state; + /** The name of the tenant that owns the node instance. */ + //public final String tenant_name; + /** A version attribute used for optimistic locking when updating the node instance. */ + //public final String version; + + + @JsonCreator + public CloudifyNodeInstanceId(@JsonProperty("id") String id) { + this.id = id; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceIdList.java new file mode 100644 index 0000000..c5ed092 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceIdList.java @@ -0,0 +1,63 @@ + +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyNodeInstanceIdList extends ECTransportModel { + + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyNodeInstanceIdList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceList.java new file mode 100644 index 0000000..4a10457 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceList.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyNodeInstanceList extends ECTransportModel { + + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyNodeInstanceList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java new file mode 100644 index 0000000..b0c876e --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifySecret extends ECTransportModel { + + /** The time when the secret was created */ + public final String created_at; + /** The secret’s key, unique per tenant */ + public final String key; + /** The time the secret was last updated at */ + public final String updated_at; + /** The secret’s value */ + public final String value; + /** Defines who can see the secret. Can be private, tenant or global*/ + public final String visibility; + /** Determines who can see the value of the secret. */ + public final String is_hidden_value; + + @JsonCreator + public CloudifySecret( + @JsonProperty("created_at") String created_at, + @JsonProperty("key") String key, + @JsonProperty("updated_at") String updated_at, + @JsonProperty("value") String value, + @JsonProperty("visibility") String visibility, + @JsonProperty("is_hidden_value") String is_hidden_value) { + this.created_at = created_at; + this.key = key; + this.updated_at = updated_at; + this.value = value; + this.visibility = visibility; + this.is_hidden_value = is_hidden_value; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretList.java new file mode 100644 index 0000000..3cd53b7 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretList.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifySecretList extends ECTransportModel { + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifySecretList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java new file mode 100644 index 0000000..b1a3fe5 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifySecretUpload extends ECTransportModel { + + /** The secret's name */ + public final String name; + /** The secret’s value */ + public final String value; + /** Update value if secret already exists */ + public final boolean update_if_exists; + /** Defines who can see the secret. Can be private, tenant or global*/ + public final String visibility; + /** Determines who can see the value of the secret. */ + public final boolean is_hidden_value; + /** The tenant name for this secret */ + public final String tenant; + + @JsonCreator + public CloudifySecretUpload( + @JsonProperty("name") String name, + @JsonProperty("value") String value, + @JsonProperty("update_if_exists") boolean update_if_exists, + @JsonProperty("visibility") String visibility, + @JsonProperty("is_hidden_value") boolean is_hidden_value, + @JsonProperty("tenant") String tenant) { + this.name = name; + this.value = value; + this.update_if_exists = update_if_exists; + this.visibility = visibility; + this.is_hidden_value = is_hidden_value; + this.tenant = tenant; + } +} + diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenant.java new file mode 100644 index 0000000..fba4229 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenant.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyTenant extends ECTransportModel { + + /** A unique identifier for the tenant */ + public final String id; + /** The tenant's name. */ + public final String name; + /** tenant display name */ + public String dName; + + @JsonCreator + public CloudifyTenant(@JsonProperty("name") String name, + @JsonProperty("dName") String dName, + @JsonProperty("id") String id) { + this.name = name; + this.dName = dName; + this.id = id; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenantList.java new file mode 100644 index 0000000..f298a28 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenantList.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CloudifyTenantList extends ECTransportModel { + public final List items; + public final Metadata metadata; + + @JsonCreator + public CloudifyTenantList(@JsonProperty("items") List items, @JsonProperty("metadata") Metadata metadata){ + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; + + @JsonCreator + public Metadata(@JsonProperty("pagination") Pagination pagination){ + this.pagination = pagination; + } + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; + + @JsonCreator + public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + this.total = total; + this.offset = offset; + this.size = size; + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulDatacenter.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulDatacenter.java index 7b610b5..47b6cb0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulDatacenter.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulDatacenter.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java index f899a8d..801dc56 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java index b3ba4ae..617830c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java index b609b78..fcf00d8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; "Name": "Service 'pgaasServer1' check", "Status": "passing", "Notes": "This is a pgaas1_Service_ID health check", - "Output": "HTTP GET http:\/\/1.2.3.4:8000\/healthcheck\/status: 200 OK ..", + "Output": "HTTP GET http:\/\/135.91.224.136:8000\/healthcheck\/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.rdm1.cci.att.com|secondaries=0 |maintenance= |down=1 pgaas2.rdm1.cci.att.com| \" }\n", "ServiceID": "pgaas1_Service_ID", "ServiceName": "pgaasServer1", "CreateIndex": 190199, diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java index f80b506..3a8a171 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; *
   {
     "Status": "critical",
-    "Output": "\"Get http://1.2.3.4:8080: dial tcp 2.3.4.5:8080: getsockopt: connection refused\"",
+    "Output": "\"Get http://135.91.205.200:8080: dial tcp 135.91.205.200:8080: getsockopt: connection refused\"",
     "Date": "2017-06-01 15:31:58.00-0000"
   }
  * 
diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java index edeb029..f990b1f 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model; import java.util.List; @@ -31,11 +32,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; * monitoring. This is NOT a model of message returned by Controller. * * The controller API answers a message with a map of String (name) to List of - * String (IP addresses). + * String (addresses). * *
   {
-	"pgaasServer1":["1.2.3.4"]
+	"pgaasServer1":["135.91.224.136"]
   }
  * 
*/ diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java index 7af9e49..abbfd52 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java @@ -1,116 +1,103 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; - -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.onboarding.util.CipherUtil; - -/** - * Model with Controller username and password for use only within the back end; - * never serialized as JSON. - */ -public class ControllerEndpointCredentials extends ControllerEndpointTransport { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ControllerEndpointCredentials.class); - - public String username; - public String password; - public boolean isEncryptedPass; - - public ControllerEndpointCredentials(boolean selected, String name, String url, String username, String password, - boolean isEncryptedPass) { - super(selected, name, url); - this.username = username; - this.password = password; - this.isEncryptedPass = isEncryptedPass; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public boolean getEncryptedPassword() { - return isEncryptedPass; - } - - public void setEncryptedPassword(boolean isEncryptedPass) { - this.isEncryptedPass = isEncryptedPass; - } - - /** - * Convenience method to yield a ControllerEndpointTransport object. - * - * @return ControllerEndpoint with copy of the non-privileged data - */ - public ControllerEndpointTransport toControllerEndpointTransport() { - return new ControllerEndpointTransport(getSelected(), getName(), getUrl()); - } - - /** - * Accepts clear text and stores an encrypted value; as a side effect, sets the - * encrypted flag to true. - * - * @param plainText - * Clear-text password - * @throws DashboardControllerException - * If encryption fails - */ - public void encryptPassword(final String plainText) throws DashboardControllerException { - try { - this.password = CipherUtil.encrypt(plainText); - this.isEncryptedPass = true; - } catch (Exception ex) { - logger.error("encryptPassword failed", ex); - throw new DashboardControllerException(ex); - } - } - - /** - * Client should call this method if {@link #getEncryptedPassword()} returns - * true. - * - * @return Clear-text password. - * @throws DashboardControllerException - * If decryption fails - */ - public String decryptPassword() throws DashboardControllerException { - try { - return CipherUtil.decrypt(password); - } catch (Exception ex) { - logger.error("decryptPassword failed", ex); - throw new DashboardControllerException(ex); - } - } +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +import org.onap.portalsdk.core.onboarding.util.CipherUtil; + +/** + * Model with Controller username and password for use only within the back end; + * never serialized as JSON. + */ +public class ControllerEndpointCredentials extends ControllerEndpointTransport { + + public String username; + public String password; + public boolean isEncryptedPass; + + public ControllerEndpointCredentials(boolean selected, String name, String url, String inventoryUrl, String dhandlerUrl, + String consulUrl, String username, String password, boolean isEncryptedPass) { + super(selected, name, url, inventoryUrl, dhandlerUrl, consulUrl); + this.username = username; + this.password = password; + this.isEncryptedPass = isEncryptedPass; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean getEncryptedPassword() { + return isEncryptedPass; + } + + public void setEncryptedPassword(boolean isEncryptedPass) { + this.isEncryptedPass = isEncryptedPass; + } + + /** + * Convenience method to yield a ControllerEndpointTransport object. + * + * @return ControllerEndpoint with copy of the non-privileged data + */ + public ControllerEndpointTransport toControllerEndpointTransport() { + return new ControllerEndpointTransport(getSelected(), getName(), getUrl(), + getInventoryUrl(), getDhandlerUrl(), getConsulUrl()); + } + + /** + * Accepts clear text and stores an encrypted value; as a side effect, sets + * the encrypted flag to true. + * + * @param plainText + * Clear-text password + * @throws Exception + * If encryption fails + */ + public void encryptPassword(final String plainText) throws Exception { + this.password = CipherUtil.encrypt(plainText); + this.isEncryptedPass = true; + } + + /** + * Client should call this method if {@link #getEncryptedPassword()} returns + * true. + * + * @return Clear-text password. + * @throws Exception + * If decryption fails + */ + public String decryptPassword() throws Exception { + return CipherUtil.decrypt(password); + } } \ No newline at end of file diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java index 0a2f529..e297782 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,13 +29,20 @@ public class ControllerEndpointTransport extends ECTransportModel { private boolean selected; private String name; private String url; + private String inventoryUrl; + private String dhandlerUrl; + private String consulUrl; public ControllerEndpointTransport() {} - public ControllerEndpointTransport(boolean selected, String name, String url) { + public ControllerEndpointTransport(boolean selected, String name, + String url, String inventoryUrl, String dhandlerUrl, String consulUrl) { this.selected = selected; this.name = name; this.url = url; + this.inventoryUrl = inventoryUrl; + this.dhandlerUrl = dhandlerUrl; + this.consulUrl = consulUrl; } public boolean getSelected() { @@ -62,4 +69,27 @@ public class ControllerEndpointTransport extends ECTransportModel { this.url = url; } + public String getInventoryUrl() { + return inventoryUrl; + } + + public void setInventoryUrl(String inventoryUrl) { + this.inventoryUrl = inventoryUrl; + } + + public String getDhandlerUrl() { + return dhandlerUrl; + } + + public void setDhandlerUrl(String dhandlerUrl) { + this.dhandlerUrl = dhandlerUrl; + } + + public String getConsulUrl() { + return consulUrl; + } + + public void setConsulUrl(String consulUrl) { + this.consulUrl = consulUrl; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.java new file mode 100644 index 0000000..0f752a7 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model; + +/** + * Model for message passed by backend to frontend about OPS Tools URLs. + */ +public class ControllerOpsTools extends ECTransportModel { + + private String id; + private String url; + + public ControllerOpsTools() {} + + public ControllerOpsTools(String id, String url) { + this.setId(id); + this.setUrl(url); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ECTransportModel.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ECTransportModel.java index 3e0baa1..946a4ec 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ECTransportModel.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ECTransportModel.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/test/java/org/onap/fusionapp/SanityTest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/EcdAppComponent.java similarity index 60% rename from ccsdk-app-common/src/test/java/org/onap/fusionapp/SanityTest.java rename to ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/EcdAppComponent.java index c859c28..a507515 100644 --- a/ccsdk-app-common/src/test/java/org/onap/fusionapp/SanityTest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/EcdAppComponent.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,23 +19,26 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.fusionapp; +package org.onap.ccsdk.dashboard.model; -import org.junit.Assert; -import org.junit.Test; -import org.onap.fusion.core.MockApplicationContextTestSuite; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import java.util.List; -public class SanityTest extends MockApplicationContextTestSuite { +import org.onap.ccsdk.dashboard.domain.EcdComponent; + +public class EcdAppComponent { - @Test - public void testGetAvailableRoles() throws Exception { - - ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/api/roles")); - //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass()); - Assert.assertEquals("application/json",ra.andReturn().getResponse().getContentType()); - } + public String app; - + public List comps; +/* + @JsonCreator + public EcdAppComponent(@JsonProperty("app") String app, + @JsonProperty("comps") List comps) { + this(app, comps); + } + */ + public EcdAppComponent(String app, List comps) { + this.app = app; + this.comps = comps; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/HealthStatus.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/HealthStatus.java index 93d072f..1b72e7c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/HealthStatus.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/HealthStatus.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ package org.onap.ccsdk.dashboard.model; * Model for JSON response with health-check results. */ public class HealthStatus { - // Either 200 or 500 + // Either 200 or 503 public int statusCode; // Additional detail in case of error, empty in case of success. public String message; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseError.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseError.java index 64e0d71..8027f92 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseError.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseError.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java index 0902fb0..5e9c963 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java index 145c1cd..4eba0d8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java new file mode 100644 index 0000000..06a516c --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java @@ -0,0 +1,40 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Collection; +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DeploymentErrorResponse { + + /** HTTP status code for the response */ + private final int status; + + /** Human-readable description of the reason for the error */ + private final String message; + + /** exception stack trace */ + private final Optional> stack; + + @JsonCreator + public DeploymentErrorResponse(@JsonProperty("status") int status, + @JsonProperty("message") String message, + @JsonProperty("stack") Optional> stack) { + this.status = status; + this.message = message; + this.stack = stack; + } + + public int getStatus() { + return status; + } + + public String getMessage() { + return message; + } + + public Optional> getStack() { + return stack; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java new file mode 100644 index 0000000..75f97ee --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java @@ -0,0 +1,102 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Map; +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message POST-ed to controller to create a Deployment via the Deployment Handler API: + * + *
+	{ 
+		"component" : "comp",
+		"deploymentTag" : "tag",
+		"blueprintName" : "name",
+		"blueprintVersion" : "version",
+		"blueprintId" : "bp_id",
+		"inputs" :
+			{
+				"input1" : "parameter1",
+				"input2" : "parameter2",
+						...
+				"inputn" : "parametern"
+			},
+		"tenant" : "tenant_name"	
+	}
+ * 
+ * + * THIS OBJECT INCLUDES THE DEPLOYMENTID CREATED BY THE USER! + */ +public class DeploymentInput { + + /** component or namespace for the service */ + private final String component; + + /** tag to identify the deployment */ + private final String tag; + + /** The blueprint name for the service to be deployed. */ + private final String blueprintName; + + /** blueprint version for the service to be deployed */ + private final Optional blueprintVersion; + + /** blueprint typeId from inventory */ + private final Optional blueprintId; + + /** The cloudify tenant name for the deployment */ + private final String tenant; + /** + * Object containing inputs needed by the service blueprint to create an instance of the service. + * Content of the object depends on the service being deployed. + */ + private final Map inputs; + + @JsonCreator + public DeploymentInput( + @JsonProperty("component") String component, + @JsonProperty("tag") String tag, + @JsonProperty("blueprintName") String blueprintName, + @JsonProperty("blueprintVersion") Integer blueprintVersion, + @JsonProperty("blueprintId") String blueprintId, + @JsonProperty("inputs") Map inputs, + @JsonProperty("tenant") String tenant) { + this.component = component; + this.tag = tag; + this.blueprintName = blueprintName; + this.blueprintVersion = Optional.ofNullable(blueprintVersion); + this.blueprintId = Optional.ofNullable(blueprintId); + this.inputs = inputs; + this.tenant = tenant; + } + + public String getBlueprintName() { + return this.blueprintName; + } + + public Map getInputs() { + return this.inputs; + } + + public String getTenant() { + return this.tenant; + } + + public Optional getBlueprintVersion() { + return blueprintVersion; + } + + public String getTag() { + return tag; + } + + public String getComponent() { + return component; + } + + public Optional getBlueprintId() { + return blueprintId; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java new file mode 100644 index 0000000..b715a2d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java @@ -0,0 +1,19 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DeploymentLink { + + /** URL for the service Deployment */ + private String href; + + @JsonCreator + public DeploymentLink (@JsonProperty("href") String href) { + this.href = href; + } + + public String getHref() { + return this.href; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java new file mode 100644 index 0000000..9d6a3b7 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java @@ -0,0 +1,49 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message POST-ed to controller to create a Deployment via the Deployment Handler API: + * + *
+	{ 
+		"serviceTypeId" : "serviceTypeId",
+		"inputs" :
+			{
+				"input1" : "parameter1"
+				"input2" : "parameter2"
+						...
+				"inputn" : "parametern"
+			}	
+	}
+ * 
+ */ +public class DeploymentRequest { + + /** The service type identifier (a unique ID assigned by DCAE inventory) for the service to be deployed. */ + private final String serviceTypeId; + + /** + * Object containing inputs needed by the service blueprint to create an instance of the service. + * Content of the object depends on the service being deployed. + */ + private final Map inputs; + + @JsonCreator + public DeploymentRequest(@JsonProperty("serviceTypeId") String serviceTypeId, + @JsonProperty("inputs") Map inputs) { + this.serviceTypeId = serviceTypeId; + this.inputs = inputs; + } + + public String getServiceTypeId() { + return this.serviceTypeId; + } + + public Map getInputs() { + return this.inputs; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java new file mode 100644 index 0000000..a0606c7 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java @@ -0,0 +1,78 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message POST-ed to controller to create a Deployment via the Deployment Handler API: + * + *
+	{ 
+		"serviceTypeId" : "serviceTypeId",
+		"type" : "install/update",
+		"inputs" :
+			{
+				"input1" : "parameter1"
+				"input2" : "parameter2"
+						...
+				"inputn" : "parametern"
+			}	
+	}
+ * 
+ * + * THIS OBJECT INCLUDES THE DEPLOYMENTID CREATED BY THE USER! + */ +public class DeploymentRequestObject { + + /** Unique deployment identifier assigned by the API client. */ + private final String deploymentId; + + /** type of deployment request */ + private final String method; + + /** The service type identifier (a unique ID assigned by DCAE inventory) for the service to be deployed. */ + private final String serviceTypeId; + + /** The cloudify tenant name for the deployment */ + private final String tenant; + /** + * Object containing inputs needed by the service blueprint to create an instance of the service. + * Content of the object depends on the service being deployed. + */ + private final Map inputs; + + @JsonCreator + public DeploymentRequestObject(@JsonProperty("deploymentId") String deploymentId, + @JsonProperty("serviceTypeId") String serviceTypeId, + @JsonProperty("inputs") Map inputs, + @JsonProperty("tenant") String tenant, + @JsonProperty("method") String method) { + this.deploymentId = deploymentId; + this.serviceTypeId = serviceTypeId; + this.inputs = inputs; + this.tenant = tenant; + this.method = method; + } + + public String getDeploymentId() { + return this.deploymentId; + } + + public String getServiceTypeId() { + return this.serviceTypeId; + } + + public Map getInputs() { + return this.inputs; + } + + public String getTenant() { + return this.tenant; + } + + public String getMethod() { + return method; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java new file mode 100644 index 0000000..513b673 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java @@ -0,0 +1,32 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DeploymentResource { + /** Unique Identifier for the resource */ + private String deploymentId; + + public String getDeploymentId() { + return deploymentId; + } + + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + /** Links that the API client can access */ + private DeploymentResourceLinks links; + + @JsonCreator + public DeploymentResource(@JsonProperty("deployment_id") String deploymentId, + @JsonProperty("links") DeploymentResourceLinks links) { + this.deploymentId = deploymentId; + this.links = links; + } + + public DeploymentResourceLinks getLinks() { + return this.links; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java new file mode 100644 index 0000000..0dd9f9e --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java @@ -0,0 +1,37 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DeploymentResourceLinks { + /** Link used to retrieve information about the service being deployed. */ + private final String self; + + /** Link used to retrieve information about deployment outcome */ + private final String outcome; + + /** Link used to retrieve information about the status of the installation workflow. */ + private final String status; + + @JsonCreator + public DeploymentResourceLinks( + @JsonProperty("self") String self, + @JsonProperty("outcome") String outcome, + @JsonProperty("status") String status) { + this.self = self; + this.outcome = outcome; + this.status = status; + } + + public String getSelf() { + return this.self; + } + + public String getStatus() { + return this.status; + } + + public String getOutcome() { + return outcome; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java new file mode 100644 index 0000000..cd81a0b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java @@ -0,0 +1,32 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Response body for a PUT or DELETE to /dcae-deployments/{deploymentId} + * + */ +public class DeploymentResponse { + + /** Unique Identifier for the request */ + private String requestId; + + /** Links that the API client can access */ + private DeploymentResponseLinks links; + + @JsonCreator + public DeploymentResponse(@JsonProperty("requestId") String requestId, + @JsonProperty("links") DeploymentResponseLinks links) { + this.requestId = requestId; + this.links = links; + } + + public String getRequestId() { + return this.requestId; + } + + public DeploymentResponseLinks getLinks() { + return this.links; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java new file mode 100644 index 0000000..c0b27b6 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java @@ -0,0 +1,32 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Links that the API client can access + * + */ +public class DeploymentResponseLinks { + + /** Link used to retrieve information about the service being deployed. */ + private final String self; + + /** Link used to retrieve information about the status of the installation workflow. */ + private final String status; + + @JsonCreator + public DeploymentResponseLinks(@JsonProperty("self") String self, + @JsonProperty("status") String status) { + this.self = self; + this.status = status; + } + + public String getSelf() { + return this.self; + } + + public String getStatus() { + return this.status; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java new file mode 100644 index 0000000..5b3b456 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java @@ -0,0 +1,34 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Collection; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Object providing a list of deployments + * + */ +public class DeploymentsListResponse { + + /** Unique identifier for the request */ + private final String requestId; + + /** Stream object containing links to all deployments known to the orchestrator. */ + private final Collection deployments; + + @JsonCreator + public DeploymentsListResponse (@JsonProperty("requestId") String requestId, + @JsonProperty("deployments") Collection deployments) { + this.requestId = requestId; + this.deployments = deployments; + } + + public String getRequestId() { + return this.requestId; + } + + public Collection getDeployments() { + return this.deployments; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java new file mode 100644 index 0000000..564d4b3 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java @@ -0,0 +1,63 @@ +package org.onap.ccsdk.dashboard.model.deploymenthandler; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for message used by the controller to create a DeploymentRequest for + * the Deployment Handler API. + * + *
+	{
+		"deploymentId" : "deploymentId",
+		"body" :
+			{ 
+				"serviceTypeId" : "serviceTypeId",
+				"inputs" :
+					{
+						"input1" : "parameter1"
+						"input2" : "parameter2"
+								...
+						"inputn" : "parametern"
+					}	
+			}
+  	}
+ * 
+ */ +public final class InventoryDeploymentRequest { + + /** Unique deployment identifier assigned by the API client. */ + private final String deploymentId; + + /** The service type identifier (a unique ID assigned by DCAE inventory) for the service to be deployed. */ + private final String serviceTypeId; + + /** + * Object containing inputs needed by the service blueprint to create an instance of the service. + * Content of the object depends on the service being deployed. + */ + private final Map inputs; + + @JsonCreator + public InventoryDeploymentRequest(@JsonProperty("deploymentId") String deploymentId, + @JsonProperty("serviceTypeId") String serviceTypeId, + @JsonProperty("inputs") Map inputs) { + this.deploymentId = deploymentId; + this.serviceTypeId = serviceTypeId; + this.inputs = inputs; + } + + public String getDeploymentId() { + return this.deploymentId; + } + + public String getServiceTypeId() { + return this.serviceTypeId; + } + + public Map getInputs() { + return this.inputs; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java new file mode 100644 index 0000000..a2c1c20 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java @@ -0,0 +1,23 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ApiResponseMessage { + + /** Response Code */ + public Integer code; + /** Response Type */ + public String type; + /** Response Message */ + public String message; + + @JsonCreator + public ApiResponseMessage (@JsonProperty("code") Integer code, + @JsonProperty("type") String type, + @JsonProperty("message") String message){ + this.code = code; + this.type = type; + this.message = message; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java new file mode 100644 index 0000000..c0b7b37 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java @@ -0,0 +1,70 @@ +package org.onap.ccsdk.dashboard.model.inventory; +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.Scanner; + +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Blueprint { + + private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory()); + + static { + YAML_MAPPER.registerModule(new Jdk8Module()); + } + + @JsonProperty("inputs") + private Map inputs; + @JsonProperty("description") + private String description; + + public static Blueprint parse(String blueprint) throws BlueprintParseException { + try { + return getYamlMapper().readValue(blueprint, Blueprint.class); + } catch (IOException e) { + throw new BlueprintParseException(e); + } + } + + private static ObjectMapper getYamlMapper() { + return YAML_MAPPER; + } + + public Map getInputs() { + return inputs; + } + + public String getDescription() { + return description; + } + + @Override + public String toString() { + return "inputs: " + ((getInputs() != null) ? getInputs().toString() : "{}"); + } + + public static void main(String args[]) throws Exception { + + File file = new File("C:\\Temp\\testBP.yaml"); + StringBuilder fileContents = new StringBuilder((int)file.length()); + Scanner scanner = new Scanner(file); + String lineSeparator = System.getProperty("line.separator"); + try { + while(scanner.hasNextLine()) { + fileContents.append(scanner.nextLine() + lineSeparator); + } + Blueprint bp = Blueprint.parse(fileContents.toString()); + System.out.println("blueprint contents: " + bp.toString()); + } finally { + scanner.close(); + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java new file mode 100644 index 0000000..596438b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java @@ -0,0 +1,119 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Compliance with the schema spec'd here: http://docs.getcloudify.org/3.4.0/blueprints/spec-inputs/ + */ +@JsonInclude(Include.NON_NULL) +public class BlueprintInput { + + private final BlueprintInput.Type type; + private final Optional defaultValue; + private final Optional description; + + public static enum Type { + @JsonProperty("any") + ANY, + + @JsonProperty("string") + STRING, + + @JsonProperty("integer") + INTEGER, + + @JsonProperty("boolean") + BOOLEAN + } + + @JsonCreator + public BlueprintInput( + @JsonProperty("type") String type, + @JsonProperty("default") Object defaultValue, + @JsonProperty("description") String description) { + + // Case where there is no default and no type --> Type should be ANY + if (defaultValue == null && type == null) { + this.type = BlueprintInput.Type.ANY; + } + + // Case where there is a default but no type --> Type should be ANY + else if (defaultValue != null && type == null) { + this.type = BlueprintInput.Type.ANY; + } + + // Case where there is a type but no default --> Type should be the specified type. + else if (defaultValue == null && type != null) { + this.type = BlueprintInput.Type.valueOf(type.toString().toUpperCase()); + } + + // Cases where there is a default and a type + else { + switch (BlueprintInput.Type.valueOf(type.toString().toUpperCase())) { + case ANY: + throw new IllegalArgumentException("Cannot specify type ANY (leave blank instead to get ANY type)"); + case BOOLEAN: + if (defaultValue != null && !(defaultValue instanceof Boolean)) throw new IllegalArgumentException("default value does not match specified type"); + this.type = BlueprintInput.Type.BOOLEAN; + break; + case INTEGER: + if (defaultValue != null && !(defaultValue instanceof Integer)) throw new IllegalArgumentException("default value does not match specified type"); + this.type = BlueprintInput.Type.INTEGER; + break; + case STRING: + if (defaultValue != null && !(defaultValue instanceof String)) throw new IllegalArgumentException("default value does not match specified type"); + + this.type = BlueprintInput.Type.STRING; + break; + default: + this.type = Type.ANY; + break; + } + } + + this.defaultValue = Optional.ofNullable(defaultValue); + this.description = Optional.ofNullable(description); + } + + public BlueprintInput.Type getType() { return type; } + + @JsonIgnore + public Optional getDefault() { return defaultValue; } + + @JsonProperty("defaultValue") + public Object getDefaultValue() { return defaultValue.orElse(null); } + + @JsonIgnore + public Optional getDescription() { return description; } + + @JsonProperty("description") + public String getDescriptionValue() { return description.orElse(null); } + + @Override + public boolean equals(Object o) { + if (o instanceof BlueprintInput) { + final BlueprintInput obj = (BlueprintInput) o; + + return obj.getDefaultValue().equals(getDefaultValue()) && + obj.getDescriptionValue().equals(getDescriptionValue()) && + obj.getType().equals(getType()); + } + + return false; + } + + @Override + public String toString() { + return "{" + + "type: " + getType() + + ",default: " + getDefault() + + ",description: " + getDescription() + + "}"; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java new file mode 100644 index 0000000..fdec86d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java @@ -0,0 +1,58 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BlueprintResponse { + + public BlueprintResponse() { + } + + /** Name of the ServiceType */ + private String typeName; + + /** Version number for this ServiceType */ + private Integer typeVersion; + + /** Unique identifier for this ServiceType */ + private String typeId; + + @JsonCreator + public BlueprintResponse(@JsonProperty("typeName") String typeName, + @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("typeId") String typeId) { + + this.typeName = typeName; + this.typeVersion = typeVersion; + this.typeId = typeId; + } + + public String getTypeName() { + return typeName; + } + + public Integer getTypeVersion() { + return typeVersion; + } + + public String getTypeId() { + return typeId; + } + + public void setTypeName(String typeName) { + this.typeName = typeName; + } + + public void setTypeVersion(Integer typeVersion) { + this.typeVersion = typeVersion; + } + + public void setTypeId(String typeId) { + this.typeId = typeId; + } + + @Override + public String toString() { + return "BlueprintResponse [typeName=" + typeName + ", typeVersion=" + typeVersion + ", typeId=" + typeId + "]"; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java new file mode 100644 index 0000000..3856deb --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java @@ -0,0 +1,23 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class InventoryProperty { + + /** Number of Service objects */ + public Integer count; + /** Service property value */ + public String propertyValue; + /** Link to a list of Services that all have this property value */ + public Link dcaeServiceQueryLink; + + @JsonCreator + public InventoryProperty (@JsonProperty("count") Integer count, + @JsonProperty("propertyValue") String propertyValue, + @JsonProperty("dcaeServiceQueryLink") Link dcaeServiceQueryLink) { + this.count = count; + this.propertyValue = propertyValue; + this.dcaeServiceQueryLink = dcaeServiceQueryLink; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java new file mode 100644 index 0000000..42d4e47 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java @@ -0,0 +1,40 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; +import java.util.Map; + +import javax.ws.rs.core.UriBuilder; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Link { + + public String title; + public String href; + public String rel; + public String uri; + public UriBuilder uriBuilder; + public Collection rels; + public Map params; + public String type; + + @JsonCreator + public Link (@JsonProperty("title") String title, + @JsonProperty("href") String href, + @JsonProperty("rel") String rel, + @JsonProperty("uri") String uri, + @JsonProperty("uriBuilder") UriBuilder uriBuilder, + @JsonProperty("rels") Collection rels, + @JsonProperty("params") Map params, + @JsonProperty("type") String type) { + this.title = title; + this.href = href; + this.rel = rel; + this.uri = uri; + this.uriBuilder = uriBuilder; + this.rels = rels; + this.params = params; + this.type = type; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java new file mode 100644 index 0000000..928f176 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java @@ -0,0 +1,162 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Service { + + /** Service ID of the Service */ + private final String serviceId; + /** Link to the Service */ + private final Link selfLink; + /** Creation date of the Service */ + private final String created; + /** Last modified date of the Service */ + private final String modified; + /** Link to the Service Type */ + private final Link typeLink; + /** vnfId of the Service */ + private final String vnfId; + /** Link to the vnf of the Service */ + private final Link vnfLink; + /** vnfType of the Service */ + private final String vnfType; + /** vnfLocation of the Service */ + private final String vnfLocation; + /** Reference to a Cloudify deployment */ + private final String deploymentRef; + /** Collection of ServiceComponent */ + private final Collection components; + /** internal role based setting */ + private Optional canDeploy; + /** tenant name for this service */ + private String tenant; + + @JsonCreator + public Service (@JsonProperty("serviceId") String serviceId, + @JsonProperty("selfLink") Link selfLink, + @JsonProperty("created") String created, + @JsonProperty("modified") String modified, + @JsonProperty("typeLink") Link typeLink, + @JsonProperty("vnfId") String vnfId, + @JsonProperty("vnfLink") Link vnfLink, + @JsonProperty("vnfType") String vnfType, + @JsonProperty("vnfLocation") String vnfLocation, + @JsonProperty("deploymentRef") String deploymentRef, + @JsonProperty("components") Collection components) { + this.serviceId = serviceId; + this.selfLink = selfLink; + this.created = created; + this.modified = modified; + this.typeLink = typeLink; + this.vnfId = vnfId; + this.vnfLink = vnfLink; + this.vnfType = vnfType; + this.vnfLocation = vnfLocation; + this.deploymentRef = deploymentRef; + this.components = components; + } + + public String getServiceId() { + return serviceId; + } + + public Link getSelfLink() { + return selfLink; + } + + public String getCreated() { + return created; + } + + public String getModified() { + return modified; + } + + public Link getTypeLink() { + return typeLink; + } + + public String getVnfId() { + return vnfId; + } + + public Link getVnfLink() { + return vnfLink; + } + + public String getVnfType() { + return vnfType; + } + + public String getVnfLocation() { + return vnfLocation; + } + + public String getDeploymentRef() { + return deploymentRef; + } + + public Collection getComponents() { + return components; + } + + // Used for back end search, only searches the fields displayed in the front end. + public boolean contains(String searchString) { + if (StringUtils.containsIgnoreCase(this.getDeploymentRef(), searchString) || + StringUtils.containsIgnoreCase(this.getServiceId(), searchString) || + StringUtils.containsIgnoreCase(this.getCreated(), searchString) || + StringUtils.containsIgnoreCase(this.getModified(), searchString) || + StringUtils.containsIgnoreCase(this.getTenant(), searchString)) { + return true; + } + return false; + } + + public Optional getCanDeploy() { + return canDeploy; + } + + public void setCanDeploy(Optional canDeploy) { + this.canDeploy = canDeploy; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public ServiceRef createServiceRef() { + return new ServiceRef(serviceId, + created, + modified); + } + /* + public static class ServiceRefBuilder { + private String serviceId; + private String created; + private String modified; + + public ServiceRefBuilder mapFromService(Service srvc) { + this.serviceId = srvc.getServiceId(); + this.created = srvc.getCreated(); + this.modified = srvc.getModified(); + return this; + } + + public ServiceRef build() { + return new ServiceRef(serviceId, + created, + modified); + } + } + */ +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java new file mode 100644 index 0000000..e7d247b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java @@ -0,0 +1,47 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceComponent { + + /** Component ID of the Service Component */ + public String componentId; + /** Link to the Service Component */ + public Link componentLink; + /** Creation date of the Service Component */ + public String created; + /** Last modified date of the Service Component */ + public String modified; + /** Component Type of the Service Component */ + public String componentType; + /** Specifies the name of the underlying source service responsible for this component */ + public String componentSource; + /** Status of the Service Component */ + public String status; + /** Location of the Service Component */ + public String location; + /** Used to determine of this component can be shared amongst different Services */ + public Integer shareable; + + @JsonCreator + public ServiceComponent(@JsonProperty("componentId") String componentId, + @JsonProperty("componentLink") Link componentLink, + @JsonProperty("created") String created, + @JsonProperty("modified") String modified, + @JsonProperty("componentType") String componentType, + @JsonProperty("componentSource") String componentSource, + @JsonProperty("status") String status, + @JsonProperty("location") String location, + @JsonProperty("shareable") Integer shareable) { + this.componentId = componentId; + this.componentLink = componentLink; + this.created = created; + this.modified = modified; + this.componentType = componentType; + this.componentSource = componentSource; + this.status = status; + this.location = location; + this.shareable = shareable; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.java new file mode 100644 index 0000000..c4c2fd9 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.java @@ -0,0 +1,31 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceComponentRequest { + + /** Component ID of the Service Component */ + public String componentId; + /** Component Type of the Service Component */ + public String componentType; + /** Specifies the name of the underlying source service responsible for this component */ + public String componentSource; + /** Used to determine if this component can be shared amongst different Services */ + public Integer shareable; + + @JsonCreator + public ServiceComponentRequest (@JsonProperty("componentId") String componentId, + @JsonProperty("componentType") String componentType, + @JsonProperty("componentSource") String componentSource, + @JsonProperty("shareable") Integer shareable) { + this.componentId = componentId; + this.componentType = componentType; + this.componentSource = componentSource; + this.shareable = shareable; + } + + public static ServiceComponentRequest from(ServiceComponent sc) { + return new ServiceComponentRequest(sc.componentId, sc.componentType, sc.componentSource, sc.shareable); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceGroupByResults.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceGroupByResults.java new file mode 100644 index 0000000..0bf6858 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceGroupByResults.java @@ -0,0 +1,21 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Set; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceGroupByResults { + + /** Property name of the service that the group by operation was performed on */ + public String propertyName; + /** Set of Service objects that have the aforementioned propertyName */ + public Set propertyValues; + + @JsonCreator + public ServiceGroupByResults (@JsonProperty("propertyName") String propertyName, + @JsonProperty("propertyValues") Set propertyValues) { + this.propertyName = propertyName; + this.propertyValues = propertyValues; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java new file mode 100644 index 0000000..71f786a --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java @@ -0,0 +1,40 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceList extends ECTransportModel { + + /** Number of Service objects */ + public final Integer totalCount; + /** Collection containing all of the returned Service objects */ + public final Collection items; + /** Links to the previous and next page of items */ + public final PaginationLinks paginationLinks; + + @JsonCreator + public ServiceList(@JsonProperty("items") Collection items, + @JsonProperty("totalCount") Integer totalCount, + @JsonProperty("links") PaginationLinks paginationLinks) { + this.items = items; + this.totalCount = totalCount; + this.paginationLinks = paginationLinks; + } + + /** Inline200ResponseLinks */ + public static final class PaginationLinks { + public final Link previousLink; + public final Link nextLink; + + @JsonCreator + public PaginationLinks (@JsonProperty("previousLink") Link previousLink, + @JsonProperty("nextLink") Link nextLink) { + this.previousLink = previousLink; + this.nextLink = nextLink; + } + } +} \ No newline at end of file diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java new file mode 100644 index 0000000..c24f86b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java @@ -0,0 +1,122 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +public class ServiceQueryParams { + + private final String typeId; + private final String vnfId; + private final String vnfType; + private final String vnfLocation; + private final String componentType; + private final Boolean shareable; + private final String created; + + // Non-instantiable + private ServiceQueryParams() { + this.typeId = null; + this.vnfId = null; + this.vnfType = null; + this.vnfLocation = null; + this.componentType = null; + this.shareable = null; + this.created = null; + } + + private ServiceQueryParams(String typeId, + String vnfId, + String vnfType, + String vnfLocation, + String componentType, + Boolean shareable, + String created) { + this.typeId = typeId; + this.vnfId = vnfId; + this.vnfType = vnfType; + this.vnfLocation = vnfLocation; + this.componentType = componentType; + this.shareable = shareable; + this.created = created; + } + + public static class Builder { + private String typeId; + private String vnfId; + private String vnfType; + private String vnfLocation; + private String componentType; + private Boolean shareable; + private String created; + + public Builder typeId(String typeId) { + this.typeId = typeId; + return this; + } + + public Builder vnfId(String vnfId) { + this.vnfId = vnfId; + return this; + } + + public Builder vnfType(String vnfType) { + this.vnfType = vnfType; + return this; + } + + public Builder vnfLocation(String vnfLocation) { + this.vnfLocation = vnfLocation; + return this; + } + + public Builder componentType(String componentType) { + this.componentType = componentType; + return this; + } + + public Builder shareable(Boolean shareable) { + this.shareable = shareable; + return this; + } + + public Builder created(String created) { + this.created = created; + return this; + } + + public ServiceQueryParams build() { + return new ServiceQueryParams(typeId, + vnfId, + vnfType, + vnfLocation, + componentType, + shareable, + created); + } + } + + public String getTypeId() { + return this.typeId; + } + + public String getVnfId() { + return this.vnfId; + } + + public String getVnfType() { + return this.vnfType; + } + + public String getVnfLocation() { + return this.vnfLocation; + } + + public String getComponentType() { + return this.componentType; + } + + public Boolean getShareable() { + return this.shareable; + } + + public String getCreated() { + return this.created; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java new file mode 100644 index 0000000..dd7acd1 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java @@ -0,0 +1,50 @@ +package org.onap.ccsdk.dashboard.model.inventory; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceRef { + + /** Service ID of the Service */ + private final String serviceId; + /** Creation date of the Service */ + private final String created; + /** Last modified date of the Service */ + private final String modified; + + + @JsonCreator + public ServiceRef (@JsonProperty("serviceId") String serviceId, + @JsonProperty("created") String created, + @JsonProperty("modified") String modified) { + this.serviceId = serviceId; + this.created = created; + this.modified = modified; + + } + + public String getServiceId() { + return serviceId; + } + + public String getCreated() { + return created; + } + + public String getModified() { + return modified; + } + + /* + private ServiceRef ( + String serviceId, + String created, + String modified) { + this.serviceId = serviceId; + this.created = created; + this.modified = modified; + } + */ + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java new file mode 100644 index 0000000..8524115 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java @@ -0,0 +1,22 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceRefList { + /** Number of Service objects */ + public final Integer totalCount; + /** Collection containing all of the returned Service objects */ + public final Collection items; + + + @JsonCreator + public ServiceRefList(@JsonProperty("items") Collection items, + @JsonProperty("totalCount") Integer totalCount) { + this.items = items; + this.totalCount = totalCount; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java new file mode 100644 index 0000000..036c9ae --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java @@ -0,0 +1,57 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.ArrayList; +import java.util.Collection; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceRequest { + + /** ID of the associated service type */ + public String typeId; + /** Id of the associated VNF that this service is monitoring */ + public String vnfId; + /** The type of the associated VNF that this service is monitoring */ + public String vnfType; + /** Location identifier of the associated VNF that this service is monitoring */ + public String vnfLocation; + /** Reference to a Cloudify deployment */ + public String deploymentRef; + /** Collection of ServiceComponentRequest objects that this service is composed of */ + public Collection components; + + @JsonCreator + public ServiceRequest(@JsonProperty("typeId") String typeId, + @JsonProperty("vnfId") String vnfId, + @JsonProperty("vnfType") String vnfType, + @JsonProperty("vnfLocation") String vnfLocation, + @JsonProperty("deploymentRef") String deploymentRef, + @JsonProperty("components") Collection components) { + this.typeId = typeId; + this.vnfId = vnfId; + this.vnfType = vnfType; + this.vnfLocation = vnfLocation; + this.deploymentRef = deploymentRef; + this.components = components; + } + + public static ServiceRequest from(String typeId, Service service) { + + // Convert the Collection in service to Collection for serviceRequest + final Collection serviceComponents = service.getComponents(); + final Collection serviceComponentRequests = new ArrayList (); + + for (ServiceComponent sc : serviceComponents) { + serviceComponentRequests.add(ServiceComponentRequest.from(sc)); + } + + return new ServiceRequest(typeId, + service.getVnfId(), + service.getVnfType(), + service.getVnfLocation(), + service.getDeploymentRef(), + serviceComponentRequests + ); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java new file mode 100644 index 0000000..f6f26ba --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java @@ -0,0 +1,340 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceType { + + /** Owner of the ServiceType */ + private final String owner; + + /** Name of the ServiceType */ + private final String typeName; + + /** Version number for this ServiceType */ + private final Integer typeVersion; + + /** String representation of a Cloudify blueprint with unbound variables */ + private final String blueprintTemplate; + + /** controller application name */ + private final String application; + /** onboarding component name */ + private final String component; + /** + * List of service ids used to associate with this ServiceType. + * ServiceTypes with this property as null or empty means they apply for every service id. + */ + private final Collection serviceIds; + + /** Collection of vnfTypes associated with this ServiceType */ + private final Collection vnfTypes; + + /** + * List of service locations used to associate with this ServiceType. + * ServiceTypes with this property as null or empty means they apply for every service location. + */ + private final Collection serviceLocations; + + /** + * Id of service this ServiceType is associated with. + * Value source is from ASDC's notification event's field 'serviceInvariantUUID'. + */ + private final Optional asdcServiceId; + + /** + * Id of vf/vnf instance this ServiceType is associated with. + * Value source is from ASDC's notification event's field 'resourceInvariantUUID'. + */ + private final Optional asdcResourceId; + + /** URL to the ASDC service model */ + private final Optional asdcServiceURL; + + /** Unique identifier for this ServiceType */ + private final Optional typeId; + + /** Link to the ServiceType */ + private final Optional selfLink; + + /** Creation date of the ServiceType */ + private final Optional created; + + /** Deactivated timestamp for this ServiceType */ + private final Optional deactivated; + + /** Map that stores the inputs for a Blueprint */ + private final Map blueprintInputs; + + /** Description of a blueprint */ + private final String blueprintDescription; + + /** internal role based setting */ + private Optional canDeploy; + + public static class Builder { + private final String blueprintTemplate; + private final String owner; + private final String typeName; + private final Integer typeVersion; + private final String application; + private final String component; + + private Optional asdcResourceId = Optional.empty(); + private Optional asdcServiceId = Optional.empty(); + private Optional asdcServiceURL = Optional.empty(); + private Optional created = Optional.empty(); + private Optional deactivated = Optional.empty(); + private Optional selfLink = Optional.empty(); + private Optional typeId = Optional.empty(); + private Collection serviceIds = new LinkedList (); + private Collection serviceLocations = new LinkedList (); + private Collection vnfTypes = new LinkedList (); + private Map blueprintInputs = new HashMap (); + private final String blueprintDescription; + private Optional canDeploy = Optional.of(true); + + public Builder(String owner, String typeName, Integer typeVersion, String blueprintTemplate, String blueprintDescription, String application, String component) { + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.blueprintTemplate = blueprintTemplate; + this.blueprintDescription = blueprintDescription; + this.application = application; + this.component = component; + } + + public Builder(ServiceType clone) { + this.asdcResourceId = clone.getAsdcResourceId(); + this.asdcServiceId = clone.getAsdcServiceId(); + this.asdcServiceURL = clone.getAsdcServiceURL(); + this.blueprintTemplate = clone.getBlueprintTemplate(); + this.created = clone.getCreated(); + this.deactivated = clone.getDeactivated(); + this.owner = clone.getOwner(); + this.selfLink = clone.getSelfLink(); + this.serviceIds = clone.getServiceIds(); + this.serviceLocations = clone.getServiceLocations(); + this.typeId = clone.getTypeId(); + this.typeName = clone.getTypeName(); + this.typeVersion = clone.getTypeVersion(); + this.vnfTypes = clone.getVnfTypes(); + this.blueprintInputs = clone.getBlueprintInputs(); + this.blueprintDescription = clone.getBlueprintDescription(); + this.canDeploy = clone.getCanDeploy(); + this.application = clone.getApplication(); + this.component = clone.getComponent(); + } + + public Builder typeId(String typeId) { + this.typeId = Optional.of(typeId); + return this; + } + + public ServiceType build() { + return new ServiceType(this); + } + } + + private ServiceType(Builder builder) { + this.owner = builder.owner; + this.typeName = builder.typeName; + this.typeVersion = builder.typeVersion; + this.blueprintTemplate = builder.blueprintTemplate; + this.application = builder.application; + this.component = builder.component; + this.serviceIds = builder.serviceIds; + this.vnfTypes = builder.vnfTypes; + this.serviceLocations = builder.serviceLocations; + + this.asdcServiceId = builder.asdcServiceId; + this.asdcResourceId = builder.asdcResourceId; + this.asdcServiceURL = builder.asdcServiceURL; + this.typeId = builder.typeId; + this.selfLink = builder.selfLink; + this.created = builder.created; + this.deactivated = builder.deactivated; + this.blueprintInputs = builder.blueprintInputs; + this.blueprintDescription = builder.blueprintDescription; + this.canDeploy = builder.canDeploy; + } + + @JsonCreator + public ServiceType(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, + @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component, + @JsonProperty("serviceIds") Collection serviceIds, + @JsonProperty("vnfTypes") Collection vnfTypes, + @JsonProperty("serviceLocations") Collection serviceLocations, + @JsonProperty("asdcServiceId") String asdcServiceId, + @JsonProperty("asdcResourceId") String asdcResourceId, + @JsonProperty("asdcServiceURL") String asdcServiceURL, + @JsonProperty("typeId") String typeId, + @JsonProperty("selfLink") Link selfLink, + @JsonProperty("created") String created, + @JsonProperty("deactivated") String deactivated, + @JsonProperty("canDeploy") Boolean canDeploy) { + + if (owner == null) throw new IllegalArgumentException("owner cannot be null"); + if (typeName == null) throw new IllegalArgumentException("typeName cannot be null"); + if (typeVersion == null) throw new IllegalArgumentException("typeVersion cannot be null"); + if (blueprintTemplate == null) throw new IllegalArgumentException("blueprintTemplate cannot be null"); + + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.blueprintTemplate = blueprintTemplate; + this.application = application; + this.component = component; + + this.serviceIds = (serviceIds == null) ? new LinkedList () : serviceIds; + this.vnfTypes = (vnfTypes == null) ? new LinkedList () : vnfTypes; + this.serviceLocations = (serviceLocations == null) ? new LinkedList () : serviceLocations; + + this.asdcServiceId = Optional.ofNullable(asdcServiceId); + this.asdcResourceId = Optional.ofNullable(asdcResourceId); + this.asdcServiceURL = Optional.ofNullable(asdcServiceURL); + this.typeId = Optional.ofNullable(typeId); + this.selfLink = Optional.ofNullable(selfLink); + this.created = Optional.ofNullable(created); + this.deactivated = Optional.ofNullable(deactivated); + this.canDeploy = Optional.of(false); + try { + this.blueprintInputs = Blueprint.parse(blueprintTemplate).getInputs(); + this.blueprintDescription = Blueprint.parse(blueprintTemplate).getDescription(); + } catch (BlueprintParseException e) { + throw new RuntimeException("Error while parsing blueprint template for " + this.typeName + " " + this.typeVersion, e); + } + } + + public String getOwner() { + return owner; + } + + public String getTypeName() { + return typeName; + } + + public Integer getTypeVersion() { + return typeVersion; + } + + public String getBlueprintTemplate() { + return blueprintTemplate; + } + + public Collection getServiceIds() { + return serviceIds; + } + + public Collection getVnfTypes() { + return vnfTypes; + } + + public Collection getServiceLocations() { + return serviceLocations; + } + + public Optional getAsdcServiceId() { + return asdcServiceId; + } + + public Optional getAsdcResourceId() { + return asdcResourceId; + } + + public Optional getAsdcServiceURL() { + return asdcServiceURL; + } + + public Optional getTypeId() { + return typeId; + } + + public Optional getSelfLink() { + return selfLink; + } + + public Optional getCreated() { + return created; + } + + public Optional getDeactivated() { + return deactivated; + } + + public Map getBlueprintInputs() { + return blueprintInputs; + } + + public String getBlueprintDescription() { + return blueprintDescription; + } + + public Optional getCanDeploy() { + return canDeploy; + } + + public String getApplication() { + return application; + } + + public String getComponent() { + return component; + } + + public void setCanDeploy(Optional canDeploy) { + this.canDeploy = canDeploy; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof ServiceType)) return false; + + final ServiceType serviceType = (ServiceType) obj; + + return (serviceType.getAsdcResourceId().equals(getAsdcResourceId()) && + serviceType.getAsdcServiceId().equals(getAsdcServiceId()) && + serviceType.getAsdcServiceURL().equals(getAsdcServiceURL()) && + serviceType.getBlueprintTemplate().equals(getBlueprintTemplate()) && + serviceType.getCreated().equals(getCreated()) && + serviceType.getDeactivated().equals(getDeactivated()) && + serviceType.getOwner().equals(getOwner()) && + serviceType.getSelfLink().equals(getSelfLink()) && + serviceType.getServiceIds().equals(getServiceIds()) && + serviceType.getServiceLocations().equals(getServiceLocations()) && + serviceType.getTypeId().equals(getTypeId()) && + serviceType.getTypeName().equals(getTypeName()) && + serviceType.getTypeVersion().equals(getTypeVersion()) && + serviceType.getVnfTypes().equals(getVnfTypes()) && + serviceType.getApplication().equals(getApplication()) && + serviceType.getComponent().equals(getComponent())); + } + + // Used for back end search, only searches the fields displayed in the front end. + public boolean contains(String searchString) { + if (StringUtils.containsIgnoreCase(this.getOwner(), searchString) || + StringUtils.containsIgnoreCase(this.getBlueprintDescription(), searchString) || + StringUtils.containsIgnoreCase(this.getTypeId().get(), searchString) || + StringUtils.containsIgnoreCase(this.getTypeName(), searchString) || + StringUtils.containsIgnoreCase(Integer.toString(this.getTypeVersion()), searchString) || + StringUtils.containsIgnoreCase(this.getCreated().get(), searchString) || + StringUtils.containsIgnoreCase(this.getComponent(), searchString) || + StringUtils.containsIgnoreCase(this.getApplication(), searchString) ) { + return true; + } + return false; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java new file mode 100644 index 0000000..28cddf6 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java @@ -0,0 +1,40 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceTypeList extends ECTransportModel { + + /** Number of ServiceType objects */ + public final Integer totalCount; + /** Collection containing all of the returned ServiceType objects */ + public final Collection items; + /** Links to the previous and next page of items */ + public final PaginationLinks paginationLinks; + + @JsonCreator + public ServiceTypeList(@JsonProperty("items") Collection items, + @JsonProperty("totalCount") Integer totalCount, + @JsonProperty("links") PaginationLinks paginationLinks) { + this.items = items; + this.totalCount = totalCount; + this.paginationLinks = paginationLinks; + } + + /** InlineResponse200Links */ + public static final class PaginationLinks { + public final Link previousLink; + public final Link nextLink; + + @JsonCreator + public PaginationLinks (@JsonProperty("previousLink") Link previousLink, + @JsonProperty("nextLink") Link nextLink) { + this.previousLink = previousLink; + this.nextLink = nextLink; + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java new file mode 100644 index 0000000..f9d1b6f --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java @@ -0,0 +1,157 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +public class ServiceTypeQueryParams { + + private final String typeName; + private final Boolean onlyLatest; + private final Boolean onlyActive; + private final String vnfType; + private final String serviceId; + private final String serviceLocation; + private final String asdcServiceId; + private final String asdcResourceId; + private final String application; + private final String component; + + // Non-instantiable + private ServiceTypeQueryParams() { + this.typeName = null; + this.onlyLatest = null; + this.onlyActive = null; + this.vnfType = null; + this.serviceId = null; + this.serviceLocation = null; + this.asdcServiceId = null; + this.asdcResourceId = null; + this.application = null; + this.component = null; + } + + private ServiceTypeQueryParams(String typeName, + Boolean onlyLatest, + Boolean onlyActive, + String vnfType, + String serviceId, + String serviceLocation, + String asdcServiceId, + String asdcResourceId, + String application, + String component) { + this.typeName = typeName; + this.onlyLatest = onlyLatest; + this.onlyActive = onlyActive; + this.vnfType = vnfType; + this.serviceId = serviceId; + this.serviceLocation = serviceLocation; + this.asdcServiceId = asdcServiceId; + this.asdcResourceId = asdcResourceId; + this.application = application; + this.component = component; + } + + public static class Builder { + private String typeName; + private Boolean onlyLatest; + private Boolean onlyActive; + private String vnfType; + private String serviceId; + private String serviceLocation; + private String asdcServiceId; + private String asdcResourceId; + private String application; + private String component; + + public Builder typeName(String typeName) { + this.typeName = typeName; + return this; + } + + public Builder onlyLatest(Boolean onlyLatest) { + this.onlyLatest = onlyLatest; + return this; + } + + public Builder onlyActive(Boolean onlyActive) { + this.onlyActive = onlyActive; + return this; + } + + public Builder vnfType(String vnfType) { + this.vnfType = vnfType; + return this; + } + + public Builder serviceId(String serviceId) { + this.serviceId = serviceId; + return this; + } + + public Builder serviceLocation(String serviceLocation) { + this.serviceLocation = serviceLocation; + return this; + } + + public Builder asdcServiceId(String asdcServiceId) { + this.asdcServiceId = asdcServiceId; + return this; + } + + public Builder asdcResourceId(String asdcResourceId) { + this.asdcResourceId = asdcResourceId; + return this; + } + + public ServiceTypeQueryParams build() { + return new ServiceTypeQueryParams(typeName, + onlyLatest, + onlyActive, + vnfType, + serviceId, + serviceLocation, + asdcServiceId, + asdcResourceId, + application, + component); + } + } + + public String getTypeName() { + return this.typeName; + } + + public Boolean getOnlyLatest() { + return this.onlyLatest; + } + + public Boolean getOnlyActive() { + return this.onlyActive; + } + + public String getVnfType() { + return this.vnfType; + } + + public String getServiceId() { + return this.serviceId; + } + + public String getServiceLocation() { + return this.serviceLocation; + } + + public String getAsdcServiceId() { + return this.asdcServiceId; + } + + public String getAsdcResourceId() { + return this.asdcResourceId; + } + + public String getApplication() { + return this.application; + } + + public String getComponent() { + return this.component; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java new file mode 100644 index 0000000..42dd018 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java @@ -0,0 +1,115 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceTypeRequest { + + /** Owner of the Service Type */ + public String owner; + /** Name of the Service Type */ + public String typeName; + /** Version number of the Service Type */ + public Integer typeVersion; + /** String representation of a Cloudify blueprint with unbound variables */ + public String blueprintTemplate; + /** controller application name */ + public String application; + /** onboarding component name */ + public String component; + /** + * Collection of service ids used to associate with the Service Type. + * Service Types with this property as null or empty means they apply for every service id. + */ + public Collection serviceIds; + /** Collection of vnfTypes associated with the Service Type */ + public Collection vnfTypes; + /** + * Collection of service locations that are used to associate with the Service Type. + * Service Types with this property as null or empty means they apply for every service location. + */ + public Collection serviceLocations; + /** + * Id of the service this Service Type is associated with. + * Value source is from ASDC's notification event's field 'serviceInvariantUUID'." + * */ + public Optional asdcServiceId; + /** + * Id of the vf/vnf instance this Service Type is associated with. + * Value source is from ASDC's notification event's field 'resourceInvariantUUID'." + */ + public Optional asdcResourceId; + /** URL to the ASDC Service Model */ + public Optional asdcServiceURL; + + @JsonCreator + public ServiceTypeRequest (@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, + @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component, + @JsonProperty("serviceIds") Collection serviceIds, + @JsonProperty("vnfTypes") Collection vnfTypes, + @JsonProperty("serviceLocations") Collection serviceLocations, + @JsonProperty("asdcServiceId") String asdcServiceId, + @JsonProperty("asdcResourceId") String asdcResourceId, + @JsonProperty("asdcServiceURL") String asdcServiceURL) { + this(owner, typeName, typeVersion, blueprintTemplate, + application, component, + serviceIds, vnfTypes, serviceLocations, + Optional.ofNullable(asdcServiceId), + Optional.ofNullable(asdcResourceId), + Optional.ofNullable(asdcServiceURL)); + } + + public ServiceTypeRequest(String owner, + String typeName, + Integer typeVersion, + String blueprintTemplate, + String application, + String component, + Collection serviceIds, + Collection vnfTypes, + Collection serviceLocations, + Optional asdcServiceId, + Optional asdcResourceId, + Optional asdcServiceURL) { + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.blueprintTemplate = blueprintTemplate; + this.application = application; + this.component = component; + this.serviceIds = serviceIds; + this.vnfTypes = vnfTypes; + this.serviceLocations = serviceLocations; + this.asdcServiceId = asdcServiceId; + this.asdcResourceId = asdcResourceId; + this.asdcServiceURL = asdcServiceURL; + } + + public static ServiceTypeRequest from(ServiceType serviceType) { + return new ServiceTypeRequest( + serviceType.getOwner(), + serviceType.getTypeName(), + serviceType.getTypeVersion(), + serviceType.getBlueprintTemplate(), + serviceType.getApplication(), + serviceType.getComponent(), + serviceType.getServiceIds(), + serviceType.getVnfTypes(), + serviceType.getServiceLocations(), + serviceType.getAsdcServiceId(), + serviceType.getAsdcResourceId(), + serviceType.getAsdcServiceURL() + ); + } + + public String getBlueprintTemplate() { + return this.blueprintTemplate; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java new file mode 100644 index 0000000..292773a --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java @@ -0,0 +1,26 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceTypeServiceMap { + + private final String serviceTypeId; + + private final ServiceRefList serviceRefList; + + @JsonCreator + public ServiceTypeServiceMap (@JsonProperty("serviceTypeId") String serviceTypeId, + @JsonProperty("created") ServiceRefList serviceRefList) { + this.serviceTypeId = serviceTypeId; + this.serviceRefList = serviceRefList; + } + + public String getServiceTypeId() { + return serviceTypeId; + } + + public ServiceRefList getServiceRefList() { + return serviceRefList; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java new file mode 100644 index 0000000..3ef334f --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java @@ -0,0 +1,48 @@ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceTypeUploadRequest { + + /** Owner of the Service Type */ + public String owner; + /** Name of the Service Type */ + public String typeName; + /** Version number of the Service Type */ + public Integer typeVersion; + /** String representation of a Cloudify blueprint with unbound variables */ + public String blueprintTemplate; + /** Application controller name */ + public String application; + /** onboarding component name */ + public String component; + + @JsonCreator + public ServiceTypeUploadRequest(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, + @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component ) { + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.blueprintTemplate = blueprintTemplate; + this.application = application; + this.component = component; + } + + public static ServiceTypeUploadRequest from(ServiceType serviceType) { + return new ServiceTypeUploadRequest(serviceType.getOwner(), serviceType.getTypeName(), + serviceType.getTypeVersion(), serviceType.getBlueprintTemplate(), + serviceType.getApplication(), serviceType.getComponent()); + } + public String getBlueprintTemplate() { + return this.blueprintTemplate; + + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java new file mode 100644 index 0000000..56fb9ee --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java @@ -0,0 +1,247 @@ +/** + * + */ +package org.onap.ccsdk.dashboard.rest; + +import java.util.Map; + +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.CloudifySecret; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; + +/** + * @author rp5662 + * + */ +public interface CloudifyClient { + + /** + * Get the execution logs + * + */ + public CloudifyEventList getEventlogs(String execution_id, String tenant); + /** + * Gets the list of Cloudify tenants. + * + * @return CloudifyBlueprintList + */ + public CloudifyTenantList getTenants(); + + /** + * Starts a Cloudify execution. + * + * @param execution + * Execution details + * @return CloudifyExecution + */ + public CloudifyExecution startExecution(CloudifyExecutionRequest execution); + + /** + * Deletes the Cloudify execution with the specified ids. + * + * @param executionId + * execution ID + * @param deploymentId + * Deployment ID + * @param action + * either "cancel" or "force-cancel" + * @return Status code; e.g., 200, 202, 204. + */ + public CloudifyExecution cancelExecution(final String executionId, Map parameters, + final String tenant); + + /** + * Get the node-instance-id. + * + * @param deploymentId + * deployment ID + * @param nodeId + * node ID + * @param tenant + * tenant name + * @return CloudifyNodeInstanceList + */ + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant); + /** + * Gets all the deployments with include filters for tenant name + * + * @return List of CloudifyDeployedTenant objects + */ + public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant); + + /** + * Get the node-instance-id. + * + * @param deploymentId + * deployment ID + * @param tenant + * tenant name + * + * @return CloudifyNodeInstanceList + */ + public CloudifyNodeInstanceIdList getNodeInstanceId(String id, String tenant); + + /** + * Query execution information for a deployment ID and execution ID passed as inputs + * + * @param executionId + * @param deploymentId + * @return + */ + public CloudifyExecutionList getExecution(String executionId, String deploymentId); + + /** + * Initiate a deployment update in cloudify + * + * @param execution + * @return + */ + public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution); + + /** + * Query execution information for a deployment ID passed as input + * + * @param deploymentId + * @param tenant + * @return + */ + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant); + + /** + * Query execution summary for a deployment ID passed as input + * + * @param deploymentId + * @param tenant + * @return + */ + public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant); + + /** + * Get cloudify node-instance-revisions. + * + * @param deploymentId + * deployment ID + * @param nodeId + * node ID + * @param tenant + * tenant name + * @return CloudifyNodeInstanceList + */ + public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant); + + /** + * Get cloudify node-instance-revisions + * + * @param bp_id + * @param tenant + * @return + */ + public CloudifyNodeInstanceList getNodeInstanceVersion(String bp_id, String tenant); + + /** + * Start Uninstall execution workflow in cloudify + * @param id + * @param ignoreLiveNodes + * @return + */ + public int deleteDeployment(String id, boolean ignoreLiveNodes); + + /** + * Start install execution workflow in cloudify + * + * @param deployment + * @return + */ + public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment); + + /** + * Query deployment object from cloudify + * + * @param id + * @param tenant + * @return + */ + public CloudifyDeploymentList getDeployment(String id, String tenant); + + /** + * Query deployment object from cloudify + * + * @param id + * @return + */ + public CloudifyDeploymentList getDeployment(String id); + /** + * Query deployments from cloudify + * + */ + public CloudifyDeploymentList getDeployments(); + + /** + * Remove blueprint referred by ID from cloudify + * + * @param id + * @return + */ + public int deleteBlueprint(String id); + + /** + * Upload blueprint into cloudify + * + * @param blueprint + * @return + */ + public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint); + + /** + * View blueprint YAML text + * + * @param id + * @return + */ + public CloudifyBlueprintContent viewBlueprint(String id); + + /** + * Query a blueprint object matching the blueprint ID in cloudify + * + * @param id + * @param tenant + * @return + */ + public CloudifyBlueprintList getBlueprint(String id, String tenant); + /** + * Query all the blueprints in cloudify + * @return + */ + public CloudifyBlueprintList getBlueprints(); + + /** + * Query deployment inputs for a deployment ID in the cloudify tenant + * + * @param id + * @param tenant + * @return + */ + public CloudifyDeploymentList getDeploymentInputs(String id, String tenant); + + /** + * Query a secret object matching the input secret name in the cloudify tenant + * + * @param secretName + * @param tenant + * @return + */ + public CloudifySecret getSecret(String secretName, String tenant); +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java new file mode 100644 index 0000000..a433908 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java @@ -0,0 +1,205 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.io.InputStream; +import java.util.Map; +import java.util.Scanner; + +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.CloudifySecret; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Provides mock implementations that return contents of files on the classpath. + */ +public class CloudifyMockClientImpl implements CloudifyClient { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyMockClientImpl.class); + + /** + * For mock outputs + */ + private final ObjectMapper objectMapper = new ObjectMapper(); + + private String getMockDataContent(final String path) { + String result = null; + try { + InputStream is = getClass().getResourceAsStream(path); + if (is == null) + throw new Exception("Failed to find resource at path " + path); + Scanner scanner = new Scanner(is, "UTF-8"); + result = scanner.useDelimiter("\\A").next(); + scanner.close(); + is.close(); + } catch (Exception ex) { + logger.error("getMockDataContent failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + /** + * Creates an input stream using the specified path and requests the mapper + * create an object of the specified type. + * + * @param modelClass + * Model class + * @param path + * Path to classpath resource + * @return Instance of modelClass + */ + private ECTransportModel getMockData(final Class modelClass, final String path) { + ECTransportModel result = null; + String json = getMockDataContent(path); + try { + result = (ECTransportModel) objectMapper.readValue(json, modelClass); + } catch (Exception ex) { + logger.error("getMockData failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + @Override + public CloudifyTenantList getTenants() { + return (CloudifyTenantList) getMockData(CloudifyTenantList.class, "/tenantsList.json"); + } + + @Override + public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant) { + return (CloudifyDeployedTenantList) getMockData(CloudifyDeployedTenantList.class, "/serviceTenantList.json"); + + } + + @Override + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant) { + return null; + } + + @Override + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String tenant) { + return null; + } + + @Override + public CloudifyNodeInstanceList getNodeInstanceVersion(String bpId, String tenant) { + return null; + } + @Override + public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant) { + return null; + } + + @Override + public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution) { + return null; + } + @Override + public CloudifyEventList getEventlogs(String executionId, String tenant) { + return null; + } + + public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { + logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: {}", deployment.toString()); + return new CloudifyDeploymentList(null, null); + } + + @Override + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { + return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); + } + + @Override + public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant) { + return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); + } + + @Override + public CloudifyExecutionList getExecution(String executionId, String deploymentId) { + return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); + } + + @Override + public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { + logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: {}", execution.toString()); + return new CloudifyExecution(null, null, null, null, null, null, null, null, null, null,null, null); + } + + @Override + public CloudifyExecution cancelExecution(final String executionId, Map parameters, final String tenant) { + return null; + } + + public int deleteDeployment(String id, boolean ignoreLiveNodes) { + return 0; + } + public CloudifyDeploymentList getDeployment(String id, String tenant) { + return null; + } + public CloudifyDeploymentList getDeployment(String id) { + return null; + } + public CloudifyDeploymentList getDeployments() { + return null; + } + public int deleteBlueprint(String id) { + return 0; + } + public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { + return null; + } + public CloudifyBlueprintContent viewBlueprint(String id) { + return null; + } + public CloudifyBlueprintList getBlueprint(String id, String tenant) { + return null; + } + public CloudifyBlueprintList getBlueprints() { + return null; + } + + /** + * Get the a cloudify secret + * + * @return CloudifySecret + */ + @Override + public CloudifySecret getSecret(String secretName, String tenant) { + return null; + } + + /** + * Simple test + * + * @param args + * blueprint ID + * @throws Exception + * On any failure + */ + public static void main(String[] args) throws Exception { + System.out.println("Testing paths and parsing mock data"); + } + + @Override + public CloudifyDeploymentList getDeploymentInputs(String id, String tenant) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java new file mode 100644 index 0000000..1854577 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java @@ -0,0 +1,350 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; + +import org.json.JSONObject; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.CloudifySecret; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CloudifyRestClientImpl extends RestClientBase implements CloudifyClient { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyRestClientImpl.class); + private final String baseUrl; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private static final String BLUEPRINTS = "blueprints"; + private static final String VIEW_BLUEPRINTS = "viewblueprints"; + private static final String DEPLOYMENTS = "deployments"; + private static final String EXECUTIONS = "executions"; + private static final String TENANTS = "tenants"; + private static final String NODES = "nodes"; + private static final String NODE_INSTANCES = "node-instances"; + private static final String UPDATE_DEPLOYMENT = "update-deployment"; + private static final String SECRETS = "secrets"; + private static final String EVENTS = "events"; + private static final String TENANT = "tenant_name"; + + public CloudifyRestClientImpl(String webapiUrl, String user, String pass) { + super(); + if (webapiUrl == null) + throw new IllegalArgumentException("Null URL not permitted"); + + URL url = null; + String urlScheme = "http"; + try { + url = new URL(webapiUrl); + baseUrl = url.toExternalForm(); + } catch (MalformedURLException ex) { + throw new RuntimeException("Failed to parse URL", ex); + } + + urlScheme = webapiUrl.split(":")[0]; + createRestTemplate(url, user, pass, urlScheme); + } + + @Override + public CloudifyTenantList getTenants() { + String url = buildUrl(new String[] { baseUrl, TENANTS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getTenants: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyEventList getEventlogs(String executionId, String tenant) { + String url = buildUrl(new String[] { baseUrl, EVENTS }, + new String[] { "execution_id", executionId }); + logger.debug(EELFLoggerDelegate.debugLogger, "getEventlogs: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant) { + String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, new String[] + { "deployment_id", deploymentId, "node_id", nodeId, "_include", "id"}); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant) { + String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, new String[] + { "deployment_id", deploymentId, "node_id", nodeId, "_include", "runtime_properties,id"}); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceVersion: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyNodeInstanceList getNodeInstanceVersion(String bpId, String tenant) { + String url = buildUrl(new String[] { baseUrl, NODES }, + new String[] { "deployment_id", bpId, "type", "onap.nodes.component", "_include", "id"}); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + CloudifyNodeIdList result = response.getBody(); + String nodeId = result.items.get(0).id; + return getNodeInstanceVersion(bpId, nodeId, tenant); + } + + @Override + public CloudifyNodeInstanceIdList getNodeInstanceId(final String bpId, String tenant) { + // GET /api/v3.1/nodes?deployment_id=clamp_967&type=onap.nodes.component&_include=id + String url = buildUrl(new String[] { baseUrl, NODES }, + new String[] { "deployment_id", bpId, "type", "onap.nodes.component", "_include", "id" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + CloudifyNodeIdList result = response.getBody(); + String nodeId = result.items.get(0).id; + return getNodeInstanceId(bpId, nodeId, tenant); + } + + @Override + public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] {"_include", "id,blueprint_id,tenant_name" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getTenantInfoFromDeploy: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { + String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId }); + logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant) { + String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId, "_include", "deployment_id,id,status,workflow_id,tenant_name,created_at"}); + logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyExecutionList getExecution(String executionId, String deploymentId) { + String url = buildUrl(new String[] { baseUrl, EXECUTIONS, executionId }, + new String[] { "deployment_id", deploymentId }); + logger.debug(EELFLoggerDelegate.debugLogger, "getExecution: url {}", url); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { + String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: url {}", url); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Tenant", execution.tenant); + HttpEntity entity = new HttpEntity(execution, headers); + return restTemplate.postForObject(url, entity, CloudifyExecution.class); + } + + @Override + public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution) { + String url = buildUrl(new String[] { baseUrl, UPDATE_DEPLOYMENT }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "updateDeployment: url {}", url); + return restTemplate.postForObject(url, execution, CloudifyDeploymentUpdateResponse.class); + } + + @Override + public CloudifyExecution cancelExecution(final String executionId, Map parameters, final String tenant) { + String url = buildUrl(new String[] { baseUrl, EXECUTIONS, executionId }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteExecution: url {}", url); + JSONObject requestJson = new JSONObject(parameters); + + // set headers + HttpHeaders headers = new HttpHeaders(); + headers.set("Tenant", tenant); + headers.set("Content-Type", "application/json"); + HttpEntity entity = new HttpEntity(requestJson.toString(), headers); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); //getStatusCode().value(); + } + + @Override + public CloudifyBlueprintList getBlueprints() { + String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprints: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyBlueprintList getBlueprint(final String id, String tenant) { + String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, new String[] { "id", id}); + logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprint: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyBlueprintContent viewBlueprint(final String id) { + String url = buildUrl(new String[] { baseUrl, VIEW_BLUEPRINTS }, new String[] { "id", id }); + logger.debug(EELFLoggerDelegate.debugLogger, "viewBlueprint: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); + String yaml = response.getBody(); + return new CloudifyBlueprintContent(id, yaml); + } + + @Override + public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { + String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "uploadBlueprint: url {}", url); + return restTemplate.postForObject(url, blueprint, CloudifyBlueprintList.class); + } + + @Override + public int deleteBlueprint(final String id) { + String url = buildUrl(new String[] { baseUrl, BLUEPRINTS, id }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteBlueprint: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference() { + }); + return response.getStatusCode().value(); + } + + @Override + public CloudifyDeploymentList getDeployments() { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyDeploymentList getDeployment(final String id) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id }); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyDeploymentList getDeployment(final String id, final String tenant) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, TENANT, tenant }); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyDeploymentList getDeploymentInputs(final String id, final String tenant) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, "_include", "inputs" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); + HttpEntity entity = getTenantHeader(tenant); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + + @Override + public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: url {}", url); + return restTemplate.postForObject(url, deployment, CloudifyDeploymentList.class); + } + + @Override + public int deleteDeployment(final String id, boolean ignoreLiveNodes) { + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, id }, + new String[] { "ignore_live_nodes", Boolean.toString(ignoreLiveNodes) }); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteDeployment: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference() { + }); + return response.getStatusCode().value(); + } + + /** + * Get a cloudify secret + * + * @return CloudifySecret + */ + @Override + public CloudifySecret getSecret(String secretName, String tenant) { + String url = buildUrl(new String[] { baseUrl, SECRETS, secretName }, new String[] { TENANT, tenant }); + logger.debug(EELFLoggerDelegate.debugLogger, "getSecrets: url {}", url); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody(); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java new file mode 100644 index 0000000..f8daaf5 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java @@ -0,0 +1,74 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.util.List; + +import org.onap.ccsdk.dashboard.model.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; + +/** + * Defines the interface of the Consul REST client. + */ +public interface ConsulClient { + + /** + * Gets all the services that are monitored by Consul. + * + * @return List of ConsulServiceHealth + */ + public List getServices(String datacenter); + + /** + * Gets the status for the specified service on all nodes. + * + * @param serviceName + * Service name + * @return List of ConsulServiceHealth + */ + public List getServiceHealth(String datacenter, String srvcName); + + /** + * Gets all the nodes that are monitored by Consul. + * + * @return List of ConsulNodeHealth + */ + public List getNodes(String datacenter); + + /** + * Gets the status for all registered services running on the specified + * node. + * + * @param nodeId + * Node ID + * @return List of ConsulServiceHealth + */ + public List getNodeServicesHealth(String datacenter, String nodeId); + + /** + * Gets all the data centers that are monitored by Consul. + * + * @return List of ConsulDatacenter objects + */ + public List getDatacenters(); + + /** + * Registers a service with Consul for health check. + * + * @param registration + * Details about the service to be registered. + * @return Result of registering a service + */ + public String registerService(ConsulHealthServiceRegistration registration); + + /** + * Deregisters a service with Consul for health check. + * + * @param serviceName + * Name of the service to be deregistered. + * @return Response code + */ + public int deregisterService(String serviceName); + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java new file mode 100644 index 0000000..82095c2 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java @@ -0,0 +1,107 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.io.InputStream; +import java.util.List; +import java.util.Scanner; + +import org.onap.ccsdk.dashboard.model.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ConsulMockClientImpl implements ConsulClient { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulMockClientImpl.class); + + /** + * For mock outputs + */ + private final ObjectMapper objectMapper = new ObjectMapper(); + + private String getMockDataContent(final String path) { + String result = null; + try { + InputStream is = getClass().getResourceAsStream(path); + if (is == null) + throw new Exception("Failed to find resource at path " + path); + Scanner scanner = new Scanner(is, "UTF-8"); + result = scanner.useDelimiter("\\A").next(); + scanner.close(); + is.close(); + } catch (Exception ex) { + logger.error("getMockDataContent failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + /** + * Creates an input stream using the specified path and requests the mapper + * create an object of the specified type. + * + * @param modelClass + * Model class + * @param path + * Path to classpath resource + * @return Instance of modelClass + */ + private ECTransportModel getMockData(final Class modelClass, final String path) { + ECTransportModel result = null; + String json = getMockDataContent(path); + try { + result = (ECTransportModel) objectMapper.readValue(json, modelClass); + } catch (Exception ex) { + logger.error("getMockData failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + @Override + public List getServices(String datacenter) { + + return null; + } + + @Override + public List getServiceHealth(String datacenter, String srvcName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getNodes(String datacenter) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getNodeServicesHealth(String datacenter, String nodeId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getDatacenters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String registerService(ConsulHealthServiceRegistration registration) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int deregisterService(String serviceName) { + // TODO Auto-generated method stub + return 0; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java new file mode 100644 index 0000000..32311a8 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java @@ -0,0 +1,191 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.ccsdk.dashboard.model.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration.EndpointCheck; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ConsulRestClientImpl extends RestClientBase implements ConsulClient { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulRestClientImpl.class); + private final String baseUrl; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private static final String API_VER = "v1"; + private static final String CATALOG = "catalog"; + private static final String SERVICES = "services"; + private static final String HEALTH = "health"; + private static final String CHECKS = "checks"; + private static final String HEALTH_SERVICES = "healthservices"; + + public ConsulRestClientImpl(String webapiUrl, String user, String pass) { + super(); + if (webapiUrl == null) + throw new IllegalArgumentException("Null URL not permitted"); + + URL url = null; + String urlScheme = "http"; + try { + url = new URL(webapiUrl); + baseUrl = url.toExternalForm(); + } catch (MalformedURLException ex) { + throw new RuntimeException("Failed to parse URL", ex); + } + + urlScheme = webapiUrl.split(":")[0]; + createRestTemplate(url, user, pass, urlScheme); + } + + @Override + public List getServiceHealth(String dc, String srvc) { + String url = buildUrl(new String[] { baseUrl, API_VER, HEALTH, CHECKS, srvc}, new String[] {"dc", dc}); + logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealth: url {}", url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + return response.getBody(); + } + + @Override + public List getServices(String dc) { + String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, SERVICES}, new String[] {"dc", dc}); + logger.debug(EELFLoggerDelegate.debugLogger, "getServices: url {}", url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + Map serviceInfo = response.getBody(); + List list = new ArrayList<>(); + for (Map.Entry entry : serviceInfo.entrySet()) { + // Be defensive + List addrs = null; + if (entry.getValue() instanceof List) + addrs = (List) entry.getValue(); + else + addrs = new ArrayList<>(); + list.add(new ConsulServiceInfo(entry.getKey(), addrs)); + } + return list; + } + + @Override + public List getNodes(String dc) { + String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, "nodes" }, new String[] {"dc", dc}); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodesHealth: url {}", url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + return response.getBody(); + } + + @Override + public List getNodeServicesHealth(String dc, String nodeId) { + String url = buildUrl(new String[] { baseUrl, API_VER, HEALTH, "node", nodeId }, new String[] {"dc", dc}); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeServicesHealth: url {}", url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + return response.getBody(); + } + + @Override + public List getDatacenters() { + String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, "datacenters" }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getDatacentersHealth: url {}", url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + List list = response.getBody(); + List result = new ArrayList<>(); + for (String dc : list) + result.add(new ConsulDatacenter(dc)); + return result; + } + + @Override + public String registerService(ConsulHealthServiceRegistration registration) { + String url = buildUrl(new String[] { baseUrl, API_VER, "/agent/service/register" }, null); + logger.debug(EELFLoggerDelegate.debugLogger, "registerService: url {}", url); + String resultStr = ""; + JSONObject outputJson = new JSONObject(); + JSONObject checkObject = new JSONObject(); + List checks = registration.services.get(0).checks; + String service_name = registration.services.get(0).name; + String service_port = registration.services.get(0).port; + String service_address = registration.services.get(0).address; + List tags = registration.services.get(0).tags; + + outputJson.put("Name", service_name); + outputJson.put("ID", service_name); + outputJson.put("Port", Integer.parseInt(service_port)); + outputJson.put("Address", service_address); + outputJson.put("Tags", tags); + + if (checks.size() == 1) { + checkObject.put("HTTP", checks.get(0).endpoint); + checkObject.put("Interval", checks.get(0).interval); + if (!checks.get(0).description.isEmpty()) + checkObject.put("Notes", checks.get(0).description); + checkObject.put("ServiceID", service_name); + outputJson.put("Check", checkObject); + } else { + JSONArray checks_new = new JSONArray(); + for (EndpointCheck check : checks) { + checkObject.put("HTTP", check.endpoint); + checkObject.put("Interval", check.endpoint); + if (!check.description.isEmpty()) + checkObject.put("Notes", check.description); + checkObject.put("ServiceID", service_name); + checks_new.put(checkObject); + } + outputJson.put("Checks", checks_new); + } + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity(outputJson.toString(), headers); + ResponseEntity result = + restTemplate.exchange(url, HttpMethod.PUT, entity, + new ParameterizedTypeReference() {}); + try { + resultStr = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException e) { + + } finally { + } + return resultStr; + + } + + @Override + public int deregisterService(String serviceName) { + String url = buildUrl(new String[] { baseUrl, API_VER, "/agent/service/deregister", serviceName}, null); + logger.debug(EELFLoggerDelegate.debugLogger, "deregisterService: url {}", url); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity(headers); + ResponseEntity result = + restTemplate.exchange(url, HttpMethod.PUT, entity, + new ParameterizedTypeReference() {}); + return result.getStatusCode().value(); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientImpl.java deleted file mode 100644 index 2e28ad2..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientImpl.java +++ /dev/null @@ -1,412 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealthHistory; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Provides methods for accessing the ECOMP Controller API via REST. Most - * methods are just simple proxies. Only the methods that fetch one page of data - * have to do any real work. - * - * Implemented using Spring RestTemplate. Supports basic HTTP authentication. - * - */ -public class ControllerRestClientImpl implements IControllerRestClient { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ControllerRestClientImpl.class); - private static final String DEPLOYMENT_ID = "deployment_id"; - - private final String baseUrl; - private final RestTemplate restTemplate; - private final ObjectMapper objectMapper = new ObjectMapper(); - - /** - * Builds a restTemplate. If username and password are supplied, uses basic - * HTTP authentication. - * - * @param webapiUrl - * URL of the web endpoint - * @param user - * user name; ignored if null - * @param pass - * password - */ - public ControllerRestClientImpl(String webapiUrl, String user, String pass) { - if (webapiUrl == null) - throw new IllegalArgumentException("Null URL not permitted"); - - URL url = null; - try { - url = new URL(webapiUrl); - baseUrl = url.toExternalForm(); - } catch (MalformedURLException ex) { - throw new RuntimeException("Failed to parse URL", ex); - } - final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort()); - - // Build a client with a credentials provider - CloseableHttpClient httpClient = null; - if (user != null && pass != null) { - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); - httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); - } else { - httpClient = HttpClientBuilder.create().build(); - } - // Create request factory - HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( - httpHost); - requestFactory.setHttpClient(httpClient); - - // Put the factory in the template - this.restTemplate = new RestTemplate(); - restTemplate.setRequestFactory(requestFactory); - } - - /** - * Builds URL ensuring appropriate separators. The base comes from - * properties file so could have many problems. - * - * @param base - * @param suffix - * @param queryParams - * key-value pairs; i.e. must have an even number of entries. - * Ignored if null. - * @return - */ - private String buildUrl(final String[] path, final String[] queryParams) { - StringBuilder sb = new StringBuilder(path[0]); - for (int p = 1; p < path.length; ++p) { - if (!path[p - 1].endsWith("/") && !path[p].startsWith("/")) - sb.append('/'); - sb.append(path[p]); - } - if (queryParams != null && queryParams.length > 0) { - sb.append('?'); - int i = 0; - while (i < queryParams.length) { - if (i > 0) - sb.append('&'); - sb.append(queryParams[i]); - sb.append('='); - sb.append(queryParams[i + 1]); - i += 2; - } - } - return sb.toString(); - } - - @Override - public CloudifyBlueprintList getBlueprints() { - String url = buildUrl(new String[] { baseUrl, blueprintsPath }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprints: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyBlueprintList getBlueprint(final String id) { - String url = buildUrl(new String[] { baseUrl, blueprintsPath }, new String[] { "id", id }); - logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprint: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyBlueprintContent viewBlueprint(final String id) { - String url = buildUrl(new String[] { baseUrl, viewBlueprintsPath }, new String[] { "id", id }); - logger.debug(EELFLoggerDelegate.debugLogger, "viewBlueprint: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); - String yaml = response.getBody(); - return new CloudifyBlueprintContent(id, yaml); - } - - @Override - public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { - String url = buildUrl(new String[] { baseUrl, blueprintsPath }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "uploadBlueprint: url {}", url); - return restTemplate.postForObject(url, blueprint, CloudifyBlueprintList.class); - } - - @Override - public int deleteBlueprint(final String id) { - String url = buildUrl(new String[] { baseUrl, blueprintsPath, id }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteBlueprint: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference() { - }); - return response.getStatusCode().value(); - } - - @Override - public CloudifyDeploymentList getDeployments() { - String url = buildUrl(new String[] { baseUrl, deploymentsPath }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyDeploymentList getDeployment(final String id) { - String url = buildUrl(new String[] { baseUrl, deploymentsPath }, new String[] { "id", id }); - logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { - String url = buildUrl(new String[] { baseUrl, deploymentsPath }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: url {}", url); - return restTemplate.postForObject(url, deployment, CloudifyDeploymentList.class); - } - - @Override - public int deleteDeployment(final String id, boolean ignoreLiveNodes) { - String url = buildUrl(new String[] { baseUrl, deploymentsPath, id }, - new String[] { "ignore_live_nodes", Boolean.toString(ignoreLiveNodes) }); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteDeployment: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference() { - }); - return response.getStatusCode().value(); - } - - @Override - public CloudifyExecutionList getExecutions(final String deploymentId) { - String url = buildUrl(new String[]{baseUrl, executionsPath}, new String[]{DEPLOYMENT_ID, deploymentId}); - logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyExecutionList getExecution(String executionId, String deploymentId) { - String url = buildUrl(new String[] { baseUrl, executionsPath, executionId }, - new String[]{DEPLOYMENT_ID, deploymentId}); - logger.debug(EELFLoggerDelegate.debugLogger, "getExecution: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - return response.getBody(); - } - - @Override - public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { - String url = buildUrl(new String[] { baseUrl, executionsPath }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: url {}", url); - return restTemplate.postForObject(url, execution, CloudifyExecution.class); - } - - @Override - public int cancelExecution(final String executionId, final String deploymentId, final String action) { - String url = buildUrl(new String[] { baseUrl, executionsPath, executionId }, - new String[]{DEPLOYMENT_ID, deploymentId, "action", action}); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteExecution: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference() { - }); - return response.getStatusCode().value(); - } - - @Override - public URI registerService(ConsulHealthServiceRegistration registration) { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "register" }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "registerService: url {}", url); - return restTemplate.postForLocation(url, registration); - } - - @Override - public int deregisterService(String serviceName) { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "deregister" , serviceName}, null); - logger.debug(EELFLoggerDelegate.debugLogger, "deregisterService: url {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, null, - new ParameterizedTypeReference() { - }); - return response.getStatusCode().value(); - } - - /** - * Translates the awkward map of String-to-List of IP into a list of - * ConsulServiceInfo objects - */ - @SuppressWarnings("unchecked") - @Override - public List getServices() { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "services" }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getServicesHealth: url {}", url); - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - Map serviceInfo = response.getBody(); - List list = new ArrayList<>(); - for (Map.Entry entry : serviceInfo.entrySet()) { - // Be defensive - List addrs; - if (entry.getValue() instanceof List) - addrs = (List) entry.getValue(); - else - addrs = new ArrayList<>(); - list.add(new ConsulServiceInfo(entry.getKey(), addrs)); - } - return list; - } - - @Override - public List getServiceHealth(String serviceName) { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "services", serviceName }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealth: url {}", url); - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - return response.getBody(); - } - - @Override - public List getServiceHealthHistory(String serviceName, Instant start, - Instant end) { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "svchist", serviceName }, - new String[] { "start", start.toString(), "end", end.toString() }); - logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealthHistory: url {}", url); - // Hack around an odd interface that returns non-JSON on error: - // "No health Data found for the selected dates or service" - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { }); - if (response.getBody().startsWith("No health")) - throw new RuntimeException(response.getBody()); - List result = null; - try { - TypeReference> typeRef = new TypeReference>() { }; - result = objectMapper.readValue(response.getBody(), typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getServiceHealthHistory failed to parse response body", ex); - } - return result; - } - - @Override - public List getNodes() { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "nodes" }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getNodesHealth: url {}", url); - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - return response.getBody(); - } - - @Override - public List getNodeServicesHealth(String nodeId) { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "nodes", nodeId }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getNodeServicesHealth: url {}", url); - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - return response.getBody(); - } - - @Override - public List getDatacenters() { - String url = buildUrl(new String[] { baseUrl, healthServicesPath, "datacenters" }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getDatacentersHealth: url {}", url); - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - List list = response.getBody(); - List result = new ArrayList<>(); - for (String dc : list) - result.add(new ConsulDatacenter(dc)); - return result; - } - - /** - * Simple test - * - * @param args - * blueprint ID - * @throws IllegalArgumentException - * On bad arguments - */ - public static void main(String[] args) throws IllegalArgumentException { - if (args.length != 1) - throw new IllegalArgumentException("Single argument expected: blueprint-id"); - ControllerRestClientImpl client = new ControllerRestClientImpl("http://localhost:8081/controller", "dbus_user", - "dbus_pass"); - final String id = args[0]; - logger.info("Requesting blueprint for " + id); - CloudifyBlueprintList list = client.getBlueprint(id); - if (list == null) - logger.error("Received null"); - else - for (int i = 0; i < list.items.size(); ++i) { - logger.info("Blueprint " + Integer.toString(i)); - logger.info(list.items.get(i).toString()); - } - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientMockImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientMockImpl.java deleted file mode 100644 index 6b0f3d0..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ControllerRestClientMockImpl.java +++ /dev/null @@ -1,311 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.io.InputStream; -import java.net.URI; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - -import org.onap.ccsdk.dashboard.exception.DashboardControllerException; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealthHistory; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Provides mock implementations that return contents of files on the classpath. - */ -public class ControllerRestClientMockImpl implements IControllerRestClient { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ControllerRestClientMockImpl.class); - - /** - * For mock outputs - */ - private final ObjectMapper objectMapper = new ObjectMapper(); - - /** - * No-arg constructor - */ - public ControllerRestClientMockImpl() { - } - - private String getMockDataContent(final String path) { - String result = null; - try { - InputStream is = getClass().getResourceAsStream(path); - if (is == null) - throw new DashboardControllerException("Failed to find resource at path " + path); - Scanner scanner = new Scanner(is, "UTF-8"); - result = scanner.useDelimiter("\\A").next(); - scanner.close(); - is.close(); - } catch (Exception ex) { - logger.error("getMockDataContent failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - /** - * Creates an input stream using the specified path and requests the mapper - * create an object of the specified type. - * - * @param modelClass - * Model class - * @param path - * Path to classpath resource - * @return Instance of modelClass - */ - private ECTransportModel getMockData(final Class modelClass, final String path) { - ECTransportModel result; - String json = getMockDataContent(path); - try { - result = objectMapper.readValue(json, modelClass); - } catch (Exception ex) { - logger.error("getMockData failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - @Override - public CloudifyBlueprintList getBlueprints() { - return (CloudifyBlueprintList) getMockData(CloudifyBlueprintList.class, "/blueprintList.json"); - } - - @Override - public CloudifyBlueprintList getBlueprint(final String id) { - return (CloudifyBlueprintList) getMockData(CloudifyBlueprintList.class, "/blueprintByID.json"); - } - - @Override - public CloudifyBlueprintContent viewBlueprint(final String id) { - String yaml = getMockDataContent("/blueprintContent.yaml"); - return new CloudifyBlueprintContent(id, yaml); - } - - @Override - public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { - logger.debug(EELFLoggerDelegate.debugLogger, "uploadBlueprint: {}", blueprint.toString()); - return new CloudifyBlueprintList(null, null); - } - - @Override - public int deleteBlueprint(final String id) { - logger.debug(EELFLoggerDelegate.debugLogger, "deleteBlueprint: {}", id); - return 204; - } - - @Override - public CloudifyDeploymentList getDeployments() { - return (CloudifyDeploymentList) getMockData(CloudifyDeploymentList.class, "/deploymentList.json"); - } - - @Override - public CloudifyDeploymentList getDeployment(final String id) { - return (CloudifyDeploymentList) getMockData(CloudifyDeploymentList.class, "/deploymentByID.json"); - } - - public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { - logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: {}", deployment.toString()); - return new CloudifyDeploymentList(null, null); - } - - @Override - public int deleteDeployment(final String id, boolean ignoreLiveNodes) { - logger.debug(EELFLoggerDelegate.debugLogger, "deleteDeployment: id {}, ignoreLiveNodes", id, ignoreLiveNodes); - return 204; - } - - @Override - public CloudifyExecutionList getExecutions(final String deploymentId) { - return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); - } - - @Override - public CloudifyExecutionList getExecution(String executionId, String deploymentId) { - return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); - } - - @Override - public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { - logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: {}", execution.toString()); - return new CloudifyExecution(null, null, null, null, null, null, null, null, null); - } - - @Override - public int cancelExecution(String executionId, String deploymentId, String action) { - logger.debug(EELFLoggerDelegate.debugLogger, "deleteExecution: executionId {}, deploymentId {}, action {}", - executionId, deploymentId, action); - return 204; - } - - @Override - public URI registerService(ConsulHealthServiceRegistration registration) { - logger.debug(EELFLoggerDelegate.debugLogger, "registerService: {}", registration); - return null; - } - - @Override - public int deregisterService(String serviceName) { - logger.debug(EELFLoggerDelegate.debugLogger, "deregisterService: {}", serviceName); - return 200; - } - - @Override - public List getServiceHealth(String serviceName) { - logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealth: serviceName={}", serviceName); - String json = getMockDataContent("/serviceHealth.json"); - TypeReference> typeRef = new TypeReference>() { - }; - List result = null; - try { - result = objectMapper.readValue(json, typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getServiceHealth failed", ex); - } - return result; - } - - @Override - public List getServiceHealthHistory(String serviceName, Instant start, Instant end) { - logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealthHistory: serviceName={}", serviceName); - String json = getMockDataContent("/serviceHealthHistory.json"); - TypeReference> typeRef = new TypeReference>() { - }; - List result = null; - try { - result = objectMapper.readValue(json, typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getServiceHealthHistory failed", ex); - } - return result; - } - - @Override - public List getNodeServicesHealth(String nodeId) { - logger.debug(EELFLoggerDelegate.debugLogger, "getNodeServicesHealth: nodeId={}", nodeId); - String json = getMockDataContent("/nodeServicesHealth.json"); - TypeReference> typeRef = new TypeReference>() { - }; - List result = null; - try { - result = objectMapper.readValue(json, typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getNodeServicesHealth failed", ex); - } - return result; - } - - @Override - public List getServices() { - logger.debug(EELFLoggerDelegate.debugLogger, "getServices"); - String json = getMockDataContent("/services.json"); - TypeReference> typeRef = new TypeReference>() { - }; - HashMap map = null; - try { - map = objectMapper.readValue(json, typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getNode failed", ex); - } - ArrayList result = new ArrayList<>(); - if (map != null) { - for (Map.Entry entry : map.entrySet()) { - final String service = entry.getKey(); - @SuppressWarnings("unchecked") final List addrs = (List) entry.getValue(); - result.add(new ConsulServiceInfo(service, addrs)); - } - } - return result; - } - - @Override - public List getNodes() { - logger.debug(EELFLoggerDelegate.debugLogger, "getNodes"); - String json = getMockDataContent("/nodesHealth.json"); - TypeReference> typeRef = new TypeReference>() { - }; - List result = null; - try { - result = objectMapper.readValue(json, typeRef); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getNode failed", ex); - - } - return result; - } - - @Override - public List getDatacenters() { - logger.debug(EELFLoggerDelegate.debugLogger, "getDatacentersHealth"); - return null; - } - - /** - * Simple test - * - * @param args - * blueprint ID - * @throws DashboardControllerException - * On any failure - */ - public static void main(String[] args) throws DashboardControllerException { - logger.info("Testing paths and parsing mock data"); - ControllerRestClientMockImpl client = new ControllerRestClientMockImpl(); - CloudifyBlueprintList list1 = client.getBlueprints(); - CloudifyBlueprintList list2 = client.getBlueprint("mock"); - CloudifyDeploymentList list3 = client.getDeployments(); - CloudifyDeploymentList list4 = client.getDeployment("mock"); - CloudifyExecutionList list5 = client.getExecutions("mock"); - List list6 = client.getServices(); - List list7 = client.getNodes(); - List list8 = client.getServiceHealth("mock"); - List list9 = client.getServiceHealthHistory("mock", Instant.now(), Instant.now()); - if (list1 == null || list2 == null || list3 == null || list4 == null || list5 == null || list6 == null - || list7 == null || list8 == null || list9 == null) - throw new DashboardControllerException("Failed"); - logger.info("Pass."); - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java new file mode 100644 index 0000000..2599a27 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java @@ -0,0 +1,88 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.util.stream.Stream; + +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; + +public interface DeploymentHandlerClient { + + + + /** + * Gets a list of all service deployments known to the orchestrator. + * + * @return Stream + */ + public Stream getDeployments(); + + /** + * Gets a list of all service deployments known to the orchestrator, + * restricted to a single service type. + * + * @param serviceTypeId + * Service type identifier for the type whose deployments are to be listed. + * + * @return Stream + */ + public Stream getDeployments(String serviceTypeId); + + /** + * Request deployment of a DCAE Service. + * + * @param deploymentId + * Unique deployment identifier assigned by the API client. + * + * @param deploymentRequest + * Deployment request object that contains the necessary fields for service deployment. + * + * @return DeploymentResponse + * Response body for a PUT or DELETE to /dcae-deployments/{deploymentId} + * + */ + public DeploymentResponse putDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest) throws + BadRequestException, + ServiceAlreadyExistsException, + ServerErrorException, + DownstreamException; + /** + * Initiate update for a deployment + * + * @param deploymentId + * Unique deployment identifier assigned by the API client. + * + * @param tenant + * Cloudify tenant where the deployment should be done + * + * @param deploymentRequest + * Deployment request object that contains the necessary fields for service deployment. + * + * @return DeploymentResponse + * Response body for a PUT or DELETE to /dcae-deployments/{deploymentId} + * + */ + public DeploymentResponse updateDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest) throws BadRequestException, + ServiceAlreadyExistsException, + ServerErrorException, + DownstreamException; + + /** + * Uninstall the DCAE service and remove all associated data from the orchestrator. + * + * @param deploymentId + * Unique deployment identifier assigned by the API client. + * + */ + public void deleteDeployment(String deploymentId, String tenant) throws BadRequestException, + ServerErrorException, + DownstreamException, + DeploymentNotFoundException; +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java new file mode 100644 index 0000000..168c28b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java @@ -0,0 +1,213 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.stream.Stream; + +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentErrorResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class DeploymentHandlerClientImpl extends RestClientBase implements DeploymentHandlerClient { + + private final String baseUrl; + //private final RestTemplate restTemplate; + private static final String DEPLOYMENTS = "dcae-deployments"; + private static final String UPDATE_PATH = "dcae-deployment-update"; + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + public DeploymentHandlerClientImpl(String webapiUrl) { + this(webapiUrl, null, null); + } + + /** + * Builds a restTemplate. If username and password are supplied, uses basic + * HTTP authentication. + * + * @param webapiUrl + * URL of the web endpoint + * @param user + * user name; ignored if null + * @param pass + * password + */ + public DeploymentHandlerClientImpl(String webapiUrl, String user, String pass) { + super(); + if (webapiUrl == null) + throw new IllegalArgumentException("Null URL not permitted"); + URL url = null; + String urlScheme = "http"; + try { + url = new URL(webapiUrl); + baseUrl = url.toExternalForm(); + } catch (MalformedURLException ex) { + throw new RuntimeException("Failed to parse URL", ex); + } + urlScheme = webapiUrl.split(":")[0]; + createRestTemplate(url, user, pass, urlScheme); + // Do not serialize null values + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + // Register Jdk8Module() for Stream and Optional types + objectMapper.registerModule(new Jdk8Module()); + } + + public Stream getDeployments() { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + DeploymentsListResponse result = response.getBody(); + return result.getDeployments().stream(); + } + + @Override + public Stream getDeployments(String serviceTypeId) { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"serviceTypeId", serviceTypeId}); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + DeploymentsListResponse result = response.getBody(); + return result.getDeployments().stream(); + } + + @Override + public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) + throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS, deploymentId}, new String[] {"cfy_tenant_name",tenant}); + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + ResponseEntity result = restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity(deploymentRequest, headers), + new ParameterizedTypeReference() { + }); + return result.getBody(); + } catch(HttpServerErrorException | HttpClientErrorException e) { + DeploymentErrorResponse errBody = null; + String errMsg = ""; + try { + errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); + } catch (IOException e1) { + errBody = null; + } + if (errBody != null) { + errMsg = errBody.getMessage(); + } + StringBuilder errDetails = new StringBuilder(); + errDetails.append(e.getMessage()).append(" ").append(errMsg); + if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415 || e.getStatusCode().value() == 404) { + throw new BadRequestException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 409) { + throw new ServiceAlreadyExistsException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 500) { + throw new ServerErrorException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 502 || e.getStatusCode().value() == 504) { + throw new DownstreamException(errDetails.toString()); + } + } + return null; + } + + @Override + public DeploymentResponse updateDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest) throws BadRequestException, + ServiceAlreadyExistsException, + ServerErrorException, + DownstreamException { + String url = buildUrl(new String[] {baseUrl, UPDATE_PATH, deploymentId}, new String[] {"cfy_tenant_name",tenant}); + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + ResponseEntity result = restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity(deploymentRequest, headers), + new ParameterizedTypeReference() { + }); + return result.getBody(); + } catch(HttpServerErrorException | HttpClientErrorException e) { + DeploymentErrorResponse errBody = null; + String errMsg = ""; + try { + errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); + } catch (IOException e1) { + errBody = null; + } + if (errBody != null) { + errMsg = errBody.getMessage(); + } + StringBuilder errDetails = new StringBuilder(); + errDetails.append(e.getMessage()).append(" ").append(errMsg); + if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415 || e.getStatusCode().value() == 404) { + throw new BadRequestException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 409) { + throw new ServiceAlreadyExistsException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 500) { + throw new ServerErrorException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 502 || e.getStatusCode().value() == 504) { + throw new DownstreamException(errDetails.toString()); + } + } + return null; // Perhaps this should be a proper JSON error response. + } + + + @Override + public void deleteDeployment(String deploymentId, String tenant) + throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS, deploymentId}, new String[] {"cfy_tenant_name",tenant, "ignore_failure", "true"}); + try { + restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference() { + }); + } catch(HttpServerErrorException | HttpClientErrorException e) { + DeploymentErrorResponse errBody = null; + String errMsg = ""; + try { + errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); + } catch (IOException e1) { + errBody = null; + } + if (errBody != null) { + errMsg = errBody.getMessage(); + } + StringBuilder errDetails = new StringBuilder(); + errDetails.append(e.getMessage()).append(" ").append(errMsg); + if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415) { + throw new BadRequestException(errDetails.toString()); + } + else if (e.getStatusCode().value() == 404) { + throw new DeploymentNotFoundException(e.getMessage()); + } + else if(e.getStatusCode().value() == 500) { + throw new ServerErrorException(errDetails.toString()); + } + else if(e.getStatusCode().value() == 502 || e.getStatusCode().value() == 504) { + throw new DownstreamException(errDetails.toString()); + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 77ccda0..7af5a20 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -1,24 +1,3 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; import java.net.URI; @@ -52,10 +31,9 @@ public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpCompone this.host = host; } - @Override - protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { - return createHttpContext(); - } + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return createHttpContext(); + } private HttpContext createHttpContext() { // Create AuthCache instance diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/IControllerRestClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/IControllerRestClient.java deleted file mode 100644 index 5e060e9..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/IControllerRestClient.java +++ /dev/null @@ -1,247 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.net.URI; -import java.time.Instant; -import java.util.List; - -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealthHistory; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; - -/** - * Defines the interface of the Controller REST client. - */ -public interface IControllerRestClient { - - String blueprintsPath = "blueprints"; - String viewBlueprintsPath = "viewblueprints"; - String deploymentsPath = "deployments"; - String executionsPath = "executions"; - String healthServicesPath = "healthservices"; - - /** - * Gets the list of Cloudify blueprints. - * - * @return CloudifyBlueprintList - */ - CloudifyBlueprintList getBlueprints(); - - /** - * Gets the Cloudify blueprint metadata for the specified ID - * - * @param id - * Blueprint ID - * @return CloudifyBlueprintList of size 1; null if not found - */ - CloudifyBlueprintList getBlueprint(String id); - - /** - * Gets the Cloudify blueprint content for the specified ID - * - * @param id - * Blueprint ID - * @return Blueprint content - */ - CloudifyBlueprintContent viewBlueprint(String id); - - /** - * Uploads a Cloudify blueprint. - * - * @param blueprint - * Cloudify Blueprint to upload - * @return CloudifyBlueprintList of size 1; null if not found - */ - CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint); - - /** - * Deletes the Cloudify blueprint with the specified id. - * - * @param id - * Blueprint ID - * @return Status code; e.g., 200, 202, 204. - */ - int deleteBlueprint(String id); - - /** - * Gets the list of Cloudify deployments. - * - * @return CloudifyDeploymentList - */ - CloudifyDeploymentList getDeployments(); - - /** - * Gets the Cloudify deployment for the specified ID - * - * @param id - * Deployment ID - * @return CloudifyDeploymentList of size 1; null if not found. - */ - CloudifyDeploymentList getDeployment(String id); - - /** - * Creates a Cloudify deployment. - * - * @param deployment - * Deployment details - * @return CloudifyDeploymentList of size 1 - */ - CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment); - - /** - * Deletes the Cloudify deployment with the specified id. - * - * @param id - * Deployment ID - * @param ignoreLiveNodes - * Boolean indicator whether to delete even if live nodes exist - * @return Status code; e.g., 200, 202, 204. - */ - int deleteDeployment(String id, boolean ignoreLiveNodes); - - /** - * Gets the Cloudify executions for the specified deployment ID - * - * @param deploymentId - * Deployment ID - * @return CloudifyExecutionList - */ - CloudifyExecutionList getExecutions(String deploymentId); - - /** - * Gets the Cloudify execution for the specified execution ID and deployment - * ID - * - * @param executionId - * Execution ID - * @param deploymentId - * Deployment ID - * @return CloudifyExecutionList of size 1 - */ - CloudifyExecutionList getExecution(String executionId, String deploymentId); - - /** - * Starts a Cloudify execution. - * - * @param execution - * Execution details - * @return CloudifyExecution - */ - CloudifyExecution startExecution(CloudifyExecutionRequest execution); - - /** - * Deletes the Cloudify execution with the specified ids. - * - * @param executionId - * execution ID - * @param deploymentId - * Deployment ID - * @param action - * either "cancel" or "force-cancel" - * @return Status code; e.g., 200, 202, 204. - */ - int cancelExecution(String executionId, String deploymentId, String action); - - /** - * Registers a service with Consul for health check. - * - * @param registration - * Details about the service to be registered. - * @return Result of registering a service - */ - URI registerService(ConsulHealthServiceRegistration registration); - - /** - * Deregister a service with Consul for health check. - * - * @param serviceName - * Name of the service to be deregister. - * @return Response code - */ - int deregisterService(String serviceName); - - /** - * Gets all the services that are monitored by Consul. - * - * @return List of ConsulServiceHealth - */ - List getServices(); - - /** - * Gets the status for the specified service on all nodes. - * - * @param serviceName - * Service name - * @return List of ConsulServiceHealth - */ - List getServiceHealth(String serviceName); - - /** - * Gets the status for the specified service on all nodes for the specified - * time window. - * - * @param serviceName - * Service name - * @param start - * Start (earliest point) of the time window - * @param end - * End (latest point) of the time window - * @return List of ConsulServiceHealth - */ - List getServiceHealthHistory(String serviceName, Instant start, Instant end); - - /** - * Gets all the nodes that are monitored by Consul. - * - * @return List of ConsulNodeHealth - */ - List getNodes(); - - /** - * Gets the status for all registered services running on the specified - * node. - * - * @param nodeId - * Node ID - * @return List of ConsulServiceHealth - */ - List getNodeServicesHealth(String nodeId); - - /** - * Gets all the data centers that are monitored by Consul. - * - * @return List of ConsulDatacenter objects - */ - List getDatacenters(); -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java new file mode 100644 index 0000000..d9f03ad --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java @@ -0,0 +1,167 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; + +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.inventory.InventoryProperty; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; + +/** + * Defines the interface of the Inventory Client. + */ +public interface InventoryClient { + + /** + * Gets a list of all DCAE Service Type objects. + * + * @return Collection + */ + public Stream getServiceTypes(); + + /** + * Gets a list of all DCAE Service Type objects that fall under a specified filter. + * + * @param serviceTypeQueryParams + * ServiceTypeQueryParams object containing query parameters. + * + * @return Collection + */ + public Stream getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams); + + /** + * Inserts a new DCAE Service Type, or updates an existing instance associated with the name typeName. + * Updates are only allowed iff there are no running DCAE services of the requested type. + * + * @param serviceType + * Service Type to be uploaded. + * + * @return ServiceType + * + * @throws ServiceTypeActiveException if the service type exists and has active instances + */ + public ServiceType addServiceType(ServiceType serviceType) throws ServiceTypeActiveException; + + /** + * Inserts a new DCAE Service Type, or updates an existing instance associated with the name typeName. + * Updates are only allowed iff there are no running DCAE services of the requested type. + * + * @param serviceType + * Service Type to be uploaded. + * @return + * + * @throws ServiceTypeActiveException if the service type exists and has active instances + */ + public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) throws ServiceTypeActiveException; + + /** + * Gets a single DCAE Service Type object with the ID typeId. + * + * @param typeId + * ID of the DCAE Service Type to be retrieved. + * + * @return Optional + */ + public Optional getServiceType(String typeId); + + /** + * Deactivates an existing DCAE Service Type instance with the ID typeId. + * + * @param typeId + * ID of the DCAE Service Type to be deactivated. + * + * @exception ServiceTypeNotFoundException + * Thrown if the DCAE Service Type is not found. + * + * @exception ServiceTypeAlreadyDeactivatedException + * Thrown if the DCAE Service Type is already deactivated. + */ + public void deleteServiceType(String typeId) throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException; + + /** + * Gets a list of all DCAE Service objects. + * + * @return Collection + */ + public Stream getServices(); + + /** + * Gets a list of all DCAE Service objects that fall under a specified filter. + * + * @param serviceQueryParams + * ServiceQueryParams object containing query parameters. + * + * @return Collection + */ + public Stream getServices(ServiceQueryParams serviceQueryParams); + + /** + * Gets a list of all DCAE Service References that match a service type filter. + * + * @param serviceQueryParams + * ServiceQueryParams object containing query parameters. + * + * @return ServiceRefList + */ + public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams); + + /** + * Gets a set of properties on Service objects that match the provided propertyName + * + * @param propertyName + * Property to find unique values. Restricted to type, vnfType, vnfLocation. + * + * @return Set + */ + + public Set getPropertiesOfServices(String propertyName); + + /** + * Gets a single DCAE Service object corresponding to the specified serviceId. + * + * @param serviceId + * Service ID of the DCAE Service to be retrieved. + * + * @return Service + */ + + public Optional getService(String serviceId); + + /** + * Puts a new DCAE Service with the specified serviceId, or updates an existing DCAE Service corresponding to the specified serviceId. + * + * @param typeId + * Type ID of the associated DCAE Service Type + * + * @param service + * DCAE Service to be uploaded. + */ + public void putService(String typeId, Service service); + + /** + * Deletes an existing DCAE Service object corresponding to the specified serviceId. + * + * @param serviceId + * Service ID of the DCAE Service to be deleted. + * + * @exception ServiceNotFoundException + * Thrown if the DCAE Service is not found. + * + * @exception ServiceAlreadyDeactivatedException + * Thrown if the DCAE Service is already deactivated. + * + */ + + public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException; + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java new file mode 100644 index 0000000..c2acb33 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java @@ -0,0 +1,96 @@ +/** + * + */ +package org.onap.ccsdk.dashboard.rest; + +import java.net.URL; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.web.client.RestTemplate; + +/** + * Base class for all the Rest client implementations + * + * @author rp5662 + * + */ +public class RestClientBase { + protected RestTemplate restTemplate = null; + + protected void createRestTemplate(URL url, String user, String pass, String urlScheme) { + RestTemplate restTempl = null; + final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort(), urlScheme); + + // Build a client with a credentials provider + CloseableHttpClient httpClient = null; + + if (user != null && pass != null) { + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); + httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); + } else { + httpClient = HttpClientBuilder.create().build(); + } + // Create request factory + HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( + httpHost); + requestFactory.setHttpClient(httpClient); + + // Put the factory in the template + restTempl = new RestTemplate(); + restTempl.setRequestFactory(requestFactory); + this.restTemplate = restTempl; + } + + /** + * Builds URL ensuring appropriate separators. The base comes from + * properties file so could have many problems. + * + * @param base + * @param suffix + * @param queryParams + * key-value pairs; i.e. must have an even number of entries. + * Ignored if null. + * @return + */ + protected String buildUrl(final String[] path, final String[] queryParams) { + StringBuilder sb = new StringBuilder(path[0]); + for (int p = 1; p < path.length; ++p) { + if (!path[p - 1].endsWith("/") && !path[p].startsWith("/")) + sb.append('/'); + sb.append(path[p]); + } + if (queryParams != null && queryParams.length > 0) { + sb.append('?'); + int i = 0; + while (i < queryParams.length) { + if (i > 0) + sb.append('&'); + sb.append(queryParams[i]); + sb.append('='); + sb.append(queryParams[i + 1]); + i += 2; + } + } + return sb.toString(); + } + /** + * Create Http Entity for the tenant header + * + * @param tenant + * @return + */ + protected HttpEntity getTenantHeader(String tenant) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Tenant", tenant); + return new HttpEntity("parameters", headers); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java new file mode 100644 index 0000000..6389db3 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java @@ -0,0 +1,344 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.inventory.ApiResponseMessage; +import org.onap.ccsdk.dashboard.model.inventory.InventoryProperty; +import org.onap.ccsdk.dashboard.model.inventory.Link; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceGroupByResults; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +public class RestInventoryClientImpl extends RestClientBase implements InventoryClient { + + private final String baseUrl; + //private final RestTemplate restTemplate; + public static final String SERVICE_TYPES = "dcae-service-types"; + public static final String SERVICES = "dcae-services"; + public static final String SERVICES_GROUPBY = "dcae-services-groupby"; + + public RestInventoryClientImpl(String webapiUrl) { + this(webapiUrl, null, null); + } + + /** + * Builds a restTemplate. If username and password are supplied, uses basic + * HTTP authentication. + * + * @param webapiUrl + * URL of the web endpoint + * @param user + * user name; ignored if null + * @param pass + * password + */ + public RestInventoryClientImpl(String webapiUrl, String user, String pass) { + super(); + if (webapiUrl == null) + throw new IllegalArgumentException("Null URL not permitted"); + URL url = null; + String urlScheme = "http"; + try { + url = new URL(webapiUrl); + baseUrl = url.toExternalForm(); + } catch (MalformedURLException ex) { + throw new RuntimeException("Failed to parse URL", ex); + } + urlScheme = webapiUrl.split(":")[0]; + createRestTemplate(url, user, pass, urlScheme); + } + + public Stream getServiceTypes() { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + Collection collection = response.getBody().items; + + // Continue retrieving items on the next page if they exist + Link nextLink = response.getBody().paginationLinks.nextLink; + while (nextLink != null) { + url = response.getBody().paginationLinks.nextLink.href; + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + + return collection.stream(); + } + + public Stream getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { + + // Only utilize the parameters that aren't null + HashMap map = new HashMap<>(); + if (serviceTypeQueryParams.getTypeName() != null) { + map.put("typeName", serviceTypeQueryParams.getTypeName()); + } + if (serviceTypeQueryParams.getOnlyLatest() != null) { + map.put("onlyLatest", Boolean.toString(serviceTypeQueryParams.getOnlyLatest())); + } + if (serviceTypeQueryParams.getOnlyActive() != null) { + map.put("onlyActive", Boolean.toString(serviceTypeQueryParams.getOnlyActive())); + } + if (serviceTypeQueryParams.getVnfType() != null) { + map.put("vnfType", serviceTypeQueryParams.getVnfType()); + } + if (serviceTypeQueryParams.getServiceId() != null) { + map.put("serviceId", serviceTypeQueryParams.getServiceId()); + } + if (serviceTypeQueryParams.getServiceLocation() != null) { + map.put("serviceLocation", serviceTypeQueryParams.getServiceLocation()); + } + if (serviceTypeQueryParams.getAsdcServiceId() != null) { + map.put("asdcServiceId", serviceTypeQueryParams.getAsdcServiceId()); + } + if (serviceTypeQueryParams.getAsdcResourceId() != null) { + map.put("asdcResourceId", serviceTypeQueryParams.getAsdcResourceId()); + } + ArrayList params = new ArrayList<>(); + for (Entry ent : map.entrySet()) { + params.add(ent.getKey()); + params.add(ent.getValue()); + } + + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES}, params.toArray(new String[params.size()])); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + Collection collection = response.getBody().items; + + // Continue retrieving items on the next page if they exist + Link nextLink = response.getBody().paginationLinks.nextLink; + while (nextLink != null) { + url = response.getBody().paginationLinks.nextLink.href; + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + + return collection.stream(); + } + + + public ServiceType addServiceType(ServiceType serviceType) { + String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); + + //Take the ServiceType object and create a ServiceTypeRequest from it + ServiceTypeRequest serviceTypeRequest = ServiceTypeRequest.from(serviceType); + + return restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); + } + + public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) { + String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); + + return restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); + } + + public Optional getServiceType(String typeId) { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES, typeId}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return Optional.ofNullable(response.getBody()); + } + + public void deleteServiceType(String typeId) throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES, typeId}, null); + try { + restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference() { + }); + } catch (HttpClientErrorException e) { + if (e.getStatusCode().value() == 410) { + throw new ServiceTypeAlreadyDeactivatedException(e.getMessage()); + } + else if (e.getStatusCode().value() == 404) { + throw new ServiceTypeNotFoundException(e.getMessage()); + } + } + } + + + public Stream getServices() { + String url = buildUrl(new String[] {baseUrl, SERVICES}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + Collection collection = response.getBody().items; + + // Continue retrieving items on the next page if they exist + Link nextLink = response.getBody().paginationLinks.nextLink; + while (nextLink != null) { + url = response.getBody().paginationLinks.nextLink.href; + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + + return collection.stream(); + } + + public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams) { + + // Only utilize the typeId + HashMap map = new HashMap<>(); + if (serviceQueryParams.getTypeId() != null) { + map.put("typeId", serviceQueryParams.getTypeId()); + } + ArrayList params = new ArrayList<>(); + for (Entry ent : map.entrySet()) { + params.add(ent.getKey()); + params.add(ent.getValue()); + } + + String url = buildUrl(new String[] {baseUrl, SERVICES}, params.toArray(new String[params.size()])); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + Collection collection = response.getBody().items; + int itemCnt = response.getBody().totalCount; + + // Continue retrieving items on the next page if they exist + Link nextLink = response.getBody().paginationLinks.nextLink; + while (nextLink != null) { + url = response.getBody().paginationLinks.nextLink.href; + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + + List srvcRefList = + collection.stream().map(e->e.createServiceRef()).collect(Collectors.toList()); + + return new ServiceRefList(srvcRefList, itemCnt); + } + + public Stream getServices(ServiceQueryParams serviceQueryParams) { + + // Only utilize the parameters that aren't null + HashMap map = new HashMap<>(); + if (serviceQueryParams.getTypeId() != null) { + map.put("typeId", serviceQueryParams.getTypeId()); + } + if (serviceQueryParams.getVnfId() != null) { + map.put("vnfId", serviceQueryParams.getVnfId()); + } + if (serviceQueryParams.getVnfType() != null) { + map.put("vnfType", serviceQueryParams.getVnfType()); + } + if (serviceQueryParams.getVnfLocation() != null) { + map.put("vnfLocation", serviceQueryParams.getVnfLocation()); + } + if (serviceQueryParams.getComponentType() != null) { + map.put("componentType", serviceQueryParams.getComponentType()); + } + if (serviceQueryParams.getShareable() != null) { + map.put("shareable", Boolean.toString(serviceQueryParams.getShareable())); + } + if (serviceQueryParams.getCreated() != null) { + map.put("created", serviceQueryParams.getCreated()); + } + ArrayList params = new ArrayList<>(); + for (Entry ent : map.entrySet()) { + params.add(ent.getKey()); + params.add(ent.getValue()); + } + + String url = buildUrl(new String[] {baseUrl, SERVICES}, params.toArray(new String[params.size()])); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + Collection collection = response.getBody().items; + + // Continue retrieving items on the next page if they exist + Link nextLink = response.getBody().paginationLinks.nextLink; + while (nextLink != null) { + url = response.getBody().paginationLinks.nextLink.href; + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + + return collection.stream(); + } + + public Set getPropertiesOfServices(String propertyName) { + String url = buildUrl(new String[] {baseUrl, SERVICES_GROUPBY, propertyName}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return response.getBody().propertyValues; + } + + public Optional getService(String serviceId) { + String url = buildUrl(new String[] {baseUrl, SERVICES, serviceId}, null); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + return Optional.ofNullable(response.getBody()); + } + + public void putService(String typeId, Service service) { + String url = buildUrl(new String[] {baseUrl, SERVICES, service.getServiceId()}, null); + + ServiceRequest serviceRequest = ServiceRequest.from(typeId, service); + + restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity(serviceRequest), + new ParameterizedTypeReference() { + }); + } + + public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException { + String url = buildUrl(new String[] {baseUrl, SERVICES, serviceId}, null); + try { + restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference() { + }); + } catch (HttpClientErrorException e) { + if (e.getStatusCode().value() == 410) { + throw new ServiceAlreadyDeactivatedException(e.getMessage()); + } + else if (e.getStatusCode().value() == 404) { + throw new ServiceNotFoundException(e.getMessage()); + } + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java new file mode 100644 index 0000000..75d373a --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java @@ -0,0 +1,169 @@ +package org.onap.ccsdk.dashboard.rest; + +import java.io.InputStream; +import java.util.Collection; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.stream.Stream; + +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.ECTransportModel; +import org.onap.ccsdk.dashboard.model.inventory.InventoryProperty; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class RestInventoryClientMockImpl implements InventoryClient { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestInventoryClientMockImpl.class); + /** + * For mock outputs + */ + private final ObjectMapper objectMapper = new ObjectMapper(); + + public RestInventoryClientMockImpl() { + // Do not serialize null values + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + // Register Jdk8Module() for Stream and Optional types + objectMapper.registerModule(new Jdk8Module()); + } + + private String getMockDataContent(final String path) { + String result = null; + try { + InputStream is = getClass().getResourceAsStream(path); + if (is == null) + throw new Exception("Failed to find resource at path " + path); + Scanner scanner = new Scanner(is, "UTF-8"); + result = scanner.useDelimiter("\\A").next(); + scanner.close(); + is.close(); + } catch (Exception ex) { + logger.error("getMockDataContent failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + /** + * Creates an input stream using the specified path and requests the mapper + * create an object of the specified type. + * + * @param modelClass + * Model class + * @param path + * Path to classpath resource + * @return Instance of modelClass + */ + private ECTransportModel getMockData(final Class modelClass, final String path) { + ECTransportModel result = null; + String json = getMockDataContent(path); + try { + result = (ECTransportModel) objectMapper.readValue(json, modelClass); + } catch (Exception ex) { + logger.error("getMockData failed", ex); + throw new RuntimeException(ex); + } + return result; + } + + @Override + public Stream getServiceTypes() { + ServiceTypeList mockData = (ServiceTypeList)getMockData(ServiceTypeList.class, "/serviceTypesList.json"); + Collection collection = mockData.items; + + return collection.stream(); + } + + @Override + public Stream getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { + ServiceTypeList mockData = (ServiceTypeList)getMockData(ServiceTypeList.class, "/serviceTypesList.json"); + Collection collection = mockData.items; + + return collection.stream(); + } + + @Override + public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams) { + return null; + } + @Override + public ServiceType addServiceType(ServiceType serviceType) throws ServiceTypeActiveException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) throws ServiceTypeActiveException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Optional getServiceType(String typeId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void deleteServiceType(String typeId) + throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException { + // TODO Auto-generated method stub + + } + + @Override + public Stream getServices() { + ServiceList mockData = (ServiceList)getMockData(ServiceList.class, "/serviceList.json"); + Collection collection = mockData.items; + + return collection.stream(); + } + + @Override + public Stream getServices(ServiceQueryParams serviceQueryParams) { + ServiceList mockData = (ServiceList)getMockData(ServiceList.class, "/serviceList.json"); + Collection collection = mockData.items; + + return collection.stream(); + } + + @Override + public Set getPropertiesOfServices(String propertyName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Optional getService(String serviceId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putService(String typeId, Service service) { + // TODO Auto-generated method stub + + } + + @Override + public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException { + // TODO Auto-generated method stub + + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java index 621de95..2db0af0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,13 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.service; +import java.util.List; + import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; +import org.onap.ccsdk.dashboard.domain.EcdComponent; /** * Provides methods for managing the user's selection of controller endpoint. @@ -56,4 +60,19 @@ public interface ControllerEndpointService { */ void deleteControllerEndpointSelection(long userId); + /** + * Gets all component names that are currently supported through + * ECOMPC dashboard + * + * @return Component instance list; + */ + public List getComponents(); + + /** + * + * Add a new component to support in ECOMPC platform + * + * @param component + */ + void insertComponent(EcdComponent component); } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java index b4b3c97..88fd53b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java @@ -1,76 +1,120 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.service; - -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.portalsdk.core.service.DataAccessService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Complete controller endpoint information is in properties. The database just - * stores the user's selection. Users are not expected to enter credentials so - * this hybrid solution keeps credentials out of the database. - */ -@Service("controllerEndpointService") -@Transactional -public class ControllerEndpointServiceImpl implements ControllerEndpointService { - - @Autowired - private DataAccessService dataAccessService; - - /** - * @return Data access service - */ - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - /** - * @param dataAccessService - * Data access service - */ - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - @Override - public ControllerEndpoint getControllerEndpointSelection(long userId) { - return (ControllerEndpoint) getDataAccessService() - .getDomainObject(ControllerEndpoint.class, userId, null); - } - - @Override - public void updateControllerEndpointSelection(ControllerEndpoint endpoint) { - getDataAccessService().saveDomainObject(endpoint, null); - } - - @Override - public void deleteControllerEndpointSelection(long userId) { - ControllerEndpoint dbEntry = (ControllerEndpoint) getDataAccessService() - .getDomainObject(ControllerEndpoint.class, userId, null); - if (dbEntry != null) - getDataAccessService().deleteDomainObject(dbEntry, null); - } - -} +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.service; + +import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; +import org.onap.ccsdk.dashboard.domain.EcdComponent; + +import java.util.List; + +import org.onap.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Complete controller endpoint information is in properties. The database just + * stores the user's selection. Users are not expected to enter credentials so + * this hybrid solution keeps credentials out of the database. + */ +@Service("controllerEndpointService") +@Transactional +public class ControllerEndpointServiceImpl implements ControllerEndpointService { + + @Autowired + private DataAccessService dataAccessService; + + /** + * @return Data access service + */ + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + /** + * @param dataAccessService + * Data access service + */ + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.controller.dashboard.service.ControllerEndpointService# + * getControllerEndpoint(java.lang.Integer) + */ + @Override + public ControllerEndpoint getControllerEndpointSelection(long userId) { + return (ControllerEndpoint) getDataAccessService() + .getDomainObject(ControllerEndpoint.class, userId, null); + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.controller.dashboard.service.ControllerEndpointService# + * getComponents() + */ + @SuppressWarnings("unchecked") + @Override + public List getComponents() { + return dataAccessService.executeNamedQuery("getAllComponents", null, null); + } + + @Override + public void insertComponent(EcdComponent component) { + dataAccessService.saveDomainObject(component, null); + } + /* + * (non-Javadoc) + * + * @see + * org.openecomp.controller.dashboard.service.ControllerEndpointService# + * updateControllerEndpoint(org.openecomp.controller.dashboard.domain. + * ControllerEndpoint) + */ + @Override + public void updateControllerEndpointSelection(ControllerEndpoint endpoint) { + getDataAccessService().saveDomainObject(endpoint, null); + } + + /* + * // (non-Javadoc) + * + * @see + * org.openecomp.controller.dashboard.service.ControllerEndpointService# + * deleteControllerEndpoint(java.lang.Integer) + */ + @Override + public void deleteControllerEndpointSelection(long userId) { + ControllerEndpoint dbEntry = (ControllerEndpoint) getDataAccessService() + .getDomainObject(ControllerEndpoint.class, userId, null); + if (dbEntry != null) + getDataAccessService().deleteDomainObject(dbEntry, null); + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java index 717be11..a04a76e 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.util; import org.springframework.beans.factory.annotation.Autowired; @@ -57,6 +58,18 @@ public class DashboardProperties { * Subkey for property with Controller URL */ public static final String CONTROLLER_SUBKEY_URL = "url"; + /** + * Subkey for property with Inventory URL + */ + public static final String CONTROLLER_SUBKEY_INVENTORY_URL = "inventory.url"; + /** + * Subkey for property with Deployment Handler URL + */ + public static final String CONTROLLER_SUBKEY_DHANDLER_URL = "dhandler.url"; + /** + * Subkey for property with Consul URL + */ + public static final String CONTROLLER_SUBKEY_CONSUL_URL = "consul.url"; /** * Subkey for property with Controller user name for authentication */ @@ -64,19 +77,49 @@ public class DashboardProperties { /** * Subkey for property with Controller password */ - public static final String CONTROLLER_SUBKEY_PASSWORD = "password"; + public static final String CONTROLLER_SUBKEY_PASS = "password"; /** * Subkey for property with Controller password encryption status */ public static final String CONTROLLER_SUBKEY_ENCRYPTED = "is_encrypted"; - - private Environment environment; - /** - * No-arg constructor + * Key for dashboard deployment environment - dev/uat/prod */ - public DashboardProperties() { - } + public static final String CONTROLLER_IN_ENV = "controller.env"; + + /** + * Key for cloudify tenant environment + */ + public static final String CLOUDIFY_TENANT_PRIM = "cloudify.tenant.primary"; + + /** + * Key for aic tenant environment + */ + public static final String AIC_TENANT_PRIM = "aic.tenant.primary"; + + /** + * Key for controller type: ATT or OS + */ + public static final String CONTROLLER_TYPE = "controller.type"; + + /** Key for K8s deploy permission string + * + */ + public static final String APP_K8S_PERM = "k8s.deploy.perm"; + + public static final String OPS_K8S_URL = "ops.k8s.url"; + + public static final String OPS_GRAFANA_URL = "ops.grf.url"; + + public static final String OPS_CLOUDIFY_URL = "ops.cfy.url"; + + public static final String OPS_CONSUL_URL = "ops.cnsl.url"; + + public static final String OPS_PROMETHEUS_URL = "ops.prom.url"; + + public static final String OPS_DBCL_URL = "ops.dbcl.url"; + + private static Environment environment; protected Environment getEnvironment() { return environment; @@ -96,7 +139,7 @@ public class DashboardProperties { * Property key * @return True or false */ - public boolean containsProperty(final String key) { + public static boolean containsProperty(final String key) { return environment.containsProperty(key); } @@ -105,16 +148,25 @@ public class DashboardProperties { * Property key * @return String value; throws unchecked exception if key is not found */ - public String getProperty(final String key) { + public static String getProperty(final String key) { return environment.getRequiredProperty(key); } + /** + * @param key + * Property key + * @return String value; throws unchecked exception if key is not found + */ + public static String getPropertyDef(final String key, String defVal) { + return environment.getProperty(key, defVal); + } + /** * @param key * Property key * @return True or False; null if key is not found */ - public Boolean getBooleanProperty(final String key) { + public static Boolean getBooleanProperty(final String key) { final String value = getProperty(key); return Boolean.parseBoolean(value); } @@ -128,7 +180,7 @@ public class DashboardProperties { * @return Array of values with leading and trailing whitespace removed; * null if key is not found. */ - public String[] getCsvListProperty(final String key) { + public static String[] getCsvListProperty(final String key) { String listVal = getProperty(key); if (listVal == null) return null; @@ -146,7 +198,7 @@ public class DashboardProperties { * Second part of key * @return Property value for key "controllerKey.propKey" */ - public String getControllerProperty(final String controllerKey, final String propKey) { + public static String getControllerProperty(final String controllerKey, final String propKey) { final String key = controllerKey + '.' + propKey; return getProperty(key); } diff --git a/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java b/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java index 365ee05..644d332 100644 --- a/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java +++ b/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java b/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java index 1f08b88..165a8b8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java +++ b/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java @@ -2,7 +2,7 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java new file mode 100644 index 0000000..ff6aa24 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java @@ -0,0 +1,90 @@ +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import org.springframework.http.MediaType; + + +public class CloudifyControllerTest extends MockitoTestSuite { + + @Mock + private CloudifyClient restClient; + + @InjectMocks + private CloudifyController subject = new CloudifyController(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + @Mock + UserUtils userUtils = new UserUtils(); + + @Mock + User epuser; + + MockUser mockUser = new MockUser(); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + } + + @Test + public final void testGetControllerEndpoints_stubbed() { + + } + + @Test + public final void testGetTenants_stubbed() throws Exception { + + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(restClient.getTenants()).thenReturn(sampleData); + + RequestBuilder request = MockMvcRequestBuilders. + get("/tenants"). + accept(MediaType.APPLICATION_JSON); + + String tenantStr = + subject.getTenants(mockedRequest); + + assertNotNull(tenantStr); + assertTrue(tenantStr.contains("dyh1b")); + + + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java new file mode 100644 index 0000000..4b68c8e --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java @@ -0,0 +1,65 @@ +package org.onap.ccsdk.dashboard.core; + +import java.util.Date; + +import org.onap.portalsdk.core.domain.User; + +public class MockUser { + + public User mockUser() { + + User ePUser = new User(); + ePUser.setOrgId(null); + ePUser.setManagerId(null); + ePUser.setFirstName("test"); + ePUser.setLastName("test"); + ePUser.setMiddleInitial(null); + ePUser.setPhone(null); + ePUser.setFax(null); + ePUser.setCellular(null); + ePUser.setEmail(null); + ePUser.setAddressId(null); + ePUser.setAlertMethodCd(null); + ePUser.setHrid(null); + ePUser.setOrgUserId("guestT"); + ePUser.setOrgCode(null); + ePUser.setAddress1(null); + ePUser.setAddress2(null); + ePUser.setCity(null); + ePUser.setState(null); + ePUser.setZipCode(null); + ePUser.setCountry(null); + ePUser.setOrgManagerUserId(null); + ePUser.setLocationClli(null); + ePUser.setBusinessCountryCode(null); + ePUser.setBusinessCountryName(null); + ePUser.setBusinessUnit(null); + ePUser.setBusinessUnitName(null); + ePUser.setDepartment(null); + ePUser.setDepartmentName(null); + ePUser.setCompanyCode(null); + ePUser.setCompany(null); + ePUser.setZipCodeSuffix(null); + ePUser.setJobTitle(null); + ePUser.setCommandChain(null); + ePUser.setSiloStatus(null); + ePUser.setCostCenter(null); + ePUser.setFinancialLocCode(null); + + ePUser.setLoginId(null); + ePUser.setLoginPwd(null); + Date date = new Date(); + ePUser.setLastLoginDate(date); + ePUser.setActive(true); + ePUser.setInternal(false); + ePUser.setSelectedProfileId(null); + ePUser.setTimeZoneId(null); + ePUser.setOnline(true); + ePUser.setChatId(null); + ePUser.setUserApps(null); + ePUser.setPseudoRoles(null); + + ePUser.setId((long) -1); + return ePUser; + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java new file mode 100644 index 0000000..c251a5c --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java @@ -0,0 +1,95 @@ + +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.ccsdk.dashboard.core; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoTestSuite { + + + public MockHttpServletRequestWrapper mockedRequest = new MockHttpServletRequestWrapper( + Mockito.mock(HttpServletRequest.class)); + public HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class); + + public MockHttpServletRequestWrapper getMockedRequest() { + return mockedRequest; + } + + public HttpServletResponse getMockedResponse() { + return mockedResponse; + } + + public class MockHttpServletRequestWrapper extends HttpServletRequestWrapper { + + HttpSession session = Mockito.mock(HttpSession.class); + + public MockHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + + } + + @Override + public HttpSession getSession() { + + return session; + } + + @Override + public HttpSession getSession(boolean create) { + + return session; + } + + } + + @Test + public void test() + { + assert(true); + } +} \ No newline at end of file diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java new file mode 100644 index 0000000..e7e51cf --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java @@ -0,0 +1,119 @@ +package org.onap.ccsdk.dashboard.rest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.model.CloudifyErrorCause; +import org.onap.ccsdk.dashboard.model.CloudifyEvent; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyEventList.Metadata; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class CloudifyRestClientImplTest { + + @Mock + RestTemplate mockRest; + + @InjectMocks + CloudifyRestClientImpl subject = + new CloudifyRestClientImpl("https://www.orcl.com/v3.1", "", ""); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + } + + @Test + public final void getEventlogsTest() throws JsonParseException, JsonMappingException, IOException { + String executionId = "123a123a"; + String tenant = "thisTenant"; + List items = new ArrayList(); + CloudifyEvent aMockEvent = new CloudifyEvent("dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", + null, "workflow_succeeded", "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", + "install workflow execution succeeded", "publish_l36bhr", "publish", "cloudify.interfaces.lifecycle.create", + "2019-02-28T23:17:49.228Z", "2019-02-28T23:17:49.700Z", "cloudify_event", "install"); + items.add(aMockEvent); + items.add( + new CloudifyEvent("dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", + null, "workflow_node_event", "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", + "Starting node", "publish_l36bhr", "publish", "cloudify.interfaces.lifecycle.create", + "2019-02-28T23:17:48.391Z", "2019-02-28T23:17:48.516Z", "cloudify_event", "install")); + + String metaInfo = "metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}"; + Metadata metadata = null; + //metadata = objectMapper.readValue(metaInfo, Metadata.class); + + CloudifyEventList expected = new CloudifyEventList(items, metadata); + + ResponseEntity response = new ResponseEntity(expected, HttpStatus.OK); + Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.>any(), + Matchers.>any())).thenReturn(response); + CloudifyEventList actual = subject.getEventlogs(executionId, tenant); + + assertTrue(actual.items.size() == 2); + + } + @Test + public final void testGetTenants_GetData() { + // define the entity you want the exchange to return + String tenantsList = "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + ResponseEntity response = new ResponseEntity(sampleData, HttpStatus.OK); + Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.>any(), + Matchers.>any())).thenReturn(response); + + CloudifyTenantList res = subject.getTenants(); + assertNotNull(res); + assertThat(res.items.get(1).name, is("dyh1b1902")); + // Assert.assertEquals(myobjectA, res.get(0)); + } + + @Test(expected = RestClientException.class) + public final void testGetTenants_withException() { + // define the entity you want the exchange to return + Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.>any(), + Matchers.>any())).thenThrow(RestClientException.class); + + subject.getTenants(); + + + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java b/ccsdk-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java deleted file mode 100644 index ccefdce..0000000 --- a/ccsdk-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.fusion.core; - -import java.io.IOException; - -import org.junit.Before; -import org.junit.runner.RunWith; -import org.onap.portalsdk.core.conf.AppConfig; -import org.onap.portalsdk.core.objectcache.AbstractCacheManager; -import org.onap.portalsdk.core.util.CacheManager; -import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; - -/** - * In order to write a unit test, 1. inherit this class - See SanityTest.java 2. - * place the "war" folder on your test class's classpath 3. run the test with - * the following VM argument; This is important because when starting the - * application from Container, the System Properties file - * (SystemProperties.java) can have the direct path but, when running from the - * Mock Junit container, the path should be prefixed with "classpath" to enable - * the mock container to search for the file in the classpath - * -Dcontainer.classpath="classpath:" - * - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class }) -@ActiveProfiles(value = "test") -public class MockApplicationContextTestSuite { - - @Autowired - public WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() { - if (mockMvc == null) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - - } - } - - public Object getBean(String name) { - return this.wac.getBean(name); - } - - public MockMvc getMockMvc() { - return mockMvc; - } - - public void setMockMvc(MockMvc mockMvc) { - this.mockMvc = mockMvc; - } - - public WebApplicationContext getWebApplicationContext() { - return wac; - } - -} - -@Configuration -@ComponentScan(basePackages = {"org.openecomp", "org.onap"}, excludeFilters = { - // see AppConfig class -}) -@Profile("test") -class MockAppConfig extends AppConfig { - - @Bean - public SystemProperties systemProperties() { - return new MockSystemProperties(); - } - - @Bean - public AbstractCacheManager cacheManager() { - return new CacheManager() { - - public void configure() throws IOException { - - } - }; - } - - protected String[] tileDefinitions() { - return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml", - "classpath:/WEB-INF/defs/definitions.xml" }; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - // registry.addInterceptor(new - // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); - // registry.addInterceptor(resourceInterceptor()); - } - - public static class MockSystemProperties extends SystemProperties { - - public MockSystemProperties() { - } - - } - -} diff --git a/ccsdk-app-os/pom.xml b/ccsdk-app-os/pom.xml index 0efd176..7bd73e6 100644 --- a/ccsdk-app-os/pom.xml +++ b/ccsdk-app-os/pom.xml @@ -14,11 +14,12 @@ UTF-8 4.2.0.RELEASE 4.3.11.Final - 2.1.0 + 2.5.1 1.1.0-SNAPSHOT https://nexus.onap.org - /content/repositories/snapshots/ - /content/repositories/releases/ + content/repositories/snapshots/ + content/repositories/releases/ + /content/repositories/staging/ ${project.version} @@ -28,16 +29,22 @@ - ecomp-releases - OpenECOMP - Release Repository + onap-releases + ONAP - Release Repository ${nexusproxy}/${releaseNexusPath} - ecomp-snapshots - OpenECOMP - Snapshot Repository + onap-snapshots + ONAP - Snapshot Repository ${nexusproxy}/${snapshotNexusPath} + + + onap-staging + ONAP - Staging Repository + ${nexusproxy}${stagingNexusPath} + diff --git a/ccsdk-app-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java b/ccsdk-app-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java index a4a1fa6..68ef057 100644 --- a/ccsdk-app-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java +++ b/ccsdk-app-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java @@ -43,7 +43,7 @@ public class HibernateMappingLocations implements HibernateMappingLocatable { // a leading slash gets stripped so don't bother. // new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), // This is a COPY to work around a bug in the 1.1.0 release. - new ClassPathResource("../fusion-110-copy.hbm.xml"), + new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), new ClassPathResource("../oom-app.hbm.xml") }; } diff --git a/ccsdk-app-os/src/main/resources/logback.xml b/ccsdk-app-os/src/main/resources/logback.xml index 474dd7c..faff70c 100644 --- a/ccsdk-app-os/src/main/resources/logback.xml +++ b/ccsdk-app-os/src/main/resources/logback.xml @@ -30,11 +30,11 @@ --> - - + + - + diff --git a/ccsdk-app-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties b/ccsdk-app-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties index 881fdd1..01ba9f7 100644 --- a/ccsdk-app-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties +++ b/ccsdk-app-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties @@ -44,6 +44,7 @@ user_attribute_name = user # User Session settings roles_attribute_name = roles role_functions_attribute_name = role_functions +role_function_list = role_function_list # POST settings post_initial_context_factory = com.sun.jndi.ldap.LdapCtxFactory diff --git a/ccsdk-app-os/src/main/webapp/WEB-INF/jsp/login_external.jsp b/ccsdk-app-os/src/main/webapp/WEB-INF/jsp/login_external.jsp index a31937c..e023929 100644 --- a/ccsdk-app-os/src/main/webapp/WEB-INF/jsp/login_external.jsp +++ b/ccsdk-app-os/src/main/webapp/WEB-INF/jsp/login_external.jsp @@ -77,7 +77,7 @@ \ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/http-interceptor.js b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/http-interceptor.js new file mode 100644 index 0000000..0f5410d --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/http-interceptor.js @@ -0,0 +1,29 @@ +appDS2.factory('httpInterceptor', function ($q, $rootScope, $location) { + return { + 'request': function (config) { + return config; + }, + /* + 'requestError': function (rejection) { + }, + */ + 'response': function (response) { + if (response.data == null) { + var loc = location.pathname; + console.log("location path name: " + loc); + var loc1 = loc.replace("/", ""); + var loc2 = loc1.replace("/ecd", "/login.htm"); + console.log("location url: " + loc2); + alert("Your session has expired. Please log in again..."); + location.replace("/"+loc2); + } + return response; + }, + // optional method + 'responseError': function (rejection) { + } + }; + }) + .config(function($httpProvider) { + $httpProvider.interceptors.push('httpInterceptor'); + }); \ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/modal-service.js b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/modal-service.js index 07b5d77..8d585f1 100644 --- a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/modal-service.js +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/modal-service.js @@ -1,24 +1,3 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ angular.module("modalServices",[]).service('modalService', ['$modal', function ($modal) { /* @@ -53,11 +32,11 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function ( }; this.showFailure = function (title, text) { - this.showIconTitleTextOkModal('icon-primary-alert', title, text); + this.showIconTitleTextOkModal('icon-alert', title, text); }; this.showSuccess = function (title, text) { - this.showIconTitleTextOkModal('icon-primary-approval', title, text); + this.showIconTitleTextOkModal('icon-approval', title, text); }; /* Replicate modals defined by ds2-modal/modalService.js */ diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-router.js b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-router.js index e598487..7ec5537 100644 --- a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-router.js +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-router.js @@ -23,35 +23,27 @@ appDS2.config(function($routeProvider) { $routeProvider .when('/orgchart', { /* horizontal layout */ - templateUrl: 'app/oom/home/tree_view.html', + templateUrl: 'app/ccsdk/home/tree_view.html', controller : 'treeViewController' }) - .when('/tosca', { - templateUrl: 'app/oom/cloudify/tosca_table.html', - controller : 'toscaTableController' + .when('/ibp', { + templateUrl: 'app/ccsdk/inventory/inventory_blueprint_table.html', + controller : 'inventoryBlueprintTableController' }) - .when('/bp', { - templateUrl: 'app/oom/cloudify/blueprint_table.html', - controller : 'blueprintTableController' - }) - .when('/dep', { - templateUrl: 'app/oom/cloudify/deployment_table.html', - controller : 'deploymentTableController' - }) - .when('/exe', { - templateUrl: 'app/oom/cloudify/execution_table.html', - controller : 'executionTableController' + .when('/idep', { + templateUrl: 'app/ccsdk/inventory/inventory_deployment_table.html', + controller : 'inventoryDeploymentTableController' }) .when('/sh', { - templateUrl: 'app/oom/consul/service_health_table.html', + templateUrl: 'app/ccsdk/consul/service_health_table.html', controller : 'serviceHealthTableController' }) .when('/nh', { - templateUrl: 'app/oom/consul/node_table.html', + templateUrl: 'app/ccsdk/consul/node_table.html', controller : 'nodeTableController' }) .when('/dc', { - templateUrl: 'app/oom/consul/datacenter_table.html', + templateUrl: 'app/ccsdk/consul/datacenter_table.html', controller : 'datacenterTableController' }) .when('/profile/:profileId', { @@ -90,8 +82,36 @@ appDS2.config(function($routeProvider) { templateUrl: 'app/fusion/scripts/DS2-view-models/ds2-admin/usage.html', controller: 'usageListControllerDS2' }) + .when('/cfy', { + templateUrl: 'app/ccsdk/ops/tabs_view.html', + controller: 'tabsController', + item: 'cfy' + }) + .when('/cnsl', { + templateUrl: 'app/ccsdk/ops/tabs_view.html', + controller: 'tabsController', + item: 'cnsl' + }) + .when('/grf', { + templateUrl: 'app/ccsdk/ops/tabs_view.html', + controller: 'tabsController', + item: 'grf' + }) + .when('/k8s', { + templateUrl: 'app/ccsdk/ops/tabs_view.html', + controller: 'tabsController', + item: 'k8s' + }) + .when('/prom', { + templateUrl: 'app/ecdapp/ops/tabs_view.html', + controller: 'tabsController', + item: 'prom' + }) + .when('/dbcl', { + templateUrl: 'app/ecdapp/ops/dbcl_view.html' + }) .otherwise({ - templateUrl: 'app/oom/home/executions_view.html', + templateUrl: 'app/ccsdk/home/executions_view.html', controller : 'executionsViewController' }) ; diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-style.css b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-style.css index e08fc31..a4e9a97 100644 --- a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-style.css +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom-style.css @@ -1,5 +1,10 @@ /* Styles for ECOMP Controller Dashboard */ +.content-container { + min-height: 650px; + width: calc(100% - 50px); +} + .ecd-error-message { font-size: 14px; font-weight: bold; @@ -17,4 +22,280 @@ .ecd-icon-action:hover { color: red; text-decoration: none; -} \ No newline at end of file +} + +.selected { + background-color:black; + color:white; + font-weight:bold; +} +.red-background { + background-color: #ff0000b3; + } +.green-background { + background-color: #bbf0bb; + } +.td-error { + border-top: 5px dotted red; + border-bottom: 5px dotted red; + } +.menu { + display: none; + z-index: 1000; + border: 1px dotted; + border-radius: 5px; + padding: 10px; + width: 50%; + background: azure; + position: fixed; + overflow: scroll; +} + +.show-menu { + z-index: 800; +} + +#show-menu { + display: none; +} + +#show-menu:checked ~ .menu { + display: block; +} + +#show-menu:checked ~ .show-menu { + color: blue; +} + +.menu-off { + position: fixed; + left: 0; + right: 0; + top: 0; + bottom: 0; + z-index: 700; + display: none; +} + +.menu-off { + display: none; +} + +#show-menu:checked ~ .menu-off { + display: block; +} + +#show-menu:checked ~ .show-menu { + display: none; +} + +.menu-off input[type=checkbox]:checked ~ .menu { + display: none; +} + +.menu-off input[type=checkbox]:checked ~ .show-menu { + display: block; +} + +td > .btn-group { + min-width: 0; + width: auto; +} + +.dropup, +.dropdown { + position: relative; +} +.dropdown-toggle:focus { + outline: 0; +} +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, .15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); + box-shadow: 0 6px 12px rgba(0, 0, 0, .175); +} +.dropdown-menu.pull-right { + right: 0; + left: auto; +} +.dropdown-menu .divider { + height: 1px; + margin: 9px 0; + overflow: hidden; + background-color: #e5e5e5; +} +.dropdown-menu > li > a { + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 1.42857143; + color: #333; + white-space: nowrap; +} +.dropdown-menu > li > a:hover, +.dropdown-menu > li > a:focus { + color: #262626; + text-decoration: none; + background-color: #f5f5f5; +} +.dropdown-menu > .active > a, +.dropdown-menu > .active > a:hover, +.dropdown-menu > .active > a:focus { + color: #fff; + text-decoration: none; + background-color: #337ab7; + outline: 0; +} +.dropdown-menu > .disabled > a, +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + color: #777; +} +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + text-decoration: none; + cursor: not-allowed; + background-color: transparent; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.open > .dropdown-menu { + display: block; +} +.open > a { + outline: 0; +} +.dropdown-menu-right { + right: 0; + left: auto; +} +.dropdown-menu-left { + right: auto; + left: 0; +} +.dropdown-header { + display: block; + padding: 3px 20px; + font-size: 12px; + line-height: 1.42857143; + color: #777; + white-space: nowrap; +} +.dropdown-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 990; +} +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} +.dropup .caret, +.navbar-fixed-bottom .dropdown .caret { + content: ""; + border-top: 0; + border-bottom: 4px dashed; + border-bottom: 4px solid \9; +} +.dropup .dropdown-menu, +.navbar-fixed-bottom .dropdown .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 2px; +} +@media (min-width: 768px) { + .navbar-right .dropdown-menu { + right: 0; + left: auto; + } + .navbar-right .dropdown-menu-left { + right: auto; + left: 0; + } +} + +.dropdown-menu li { + margin-bottom: 10px; +} + +.dropdown-menu li div { + padding-left: 5px; +} + +.dropdown-menu li div i { + margin-right: 5px; +} + +td > .btn-group > .btn { + min-width: 0; + color: #0568ae; +} + +td > .btn-group > .btn> i { + font-size: 30px; +} + +li > a.active { + font-weight: bolder; + outline: thin dotted #666; +} + +tr:hover { + background-color: #f2f2f2; +} + +tr:focus { + background-color: #f2f2f2; +} + +.modalwrapper.modal-docked .modal-jumbo { + max-height: 100%; + height: 100%; + overflow: hidden; + top: 0; + width: 100%; + max-width: 100%; +} + +#addAppDiv { + padding-left: 10px; + background: lightgray; + border-radius: 5px; + padding-bottom: 15px; +} + +.field-group.error .error-msg { + color: red; + display: block; + font-size: 14px; + line-height: 14px; + font-family: "Omnes-ATT-W02-Medium"; + position: relative; + padding-left: 18px; + margin-top: 10px; +} + +.heading-page { + margin-bottom: 20px; +} diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom_spa.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom_spa.html index 47eac2d..9ad1410 100644 --- a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom_spa.html +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/home/oom_spa.html @@ -4,7 +4,7 @@ OOM Dashboard - + @@ -18,11 +18,12 @@ - + - + - + + @@ -34,8 +35,8 @@ - - + + @@ -47,33 +48,44 @@ - - - - - - - - + + + + + + + + + - - - - - - - + + + + + + + + + + + + + + - - - - - - - + + + + + + + + + + @@ -91,7 +103,7 @@ - + + +
+

{{ecdapp.label}}

+
+ +
+
+ +
+
+
+ + Blueprint {{ecdapp.serviceType.typeName}} upload is in progress... +
+
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+ + *Owner +
+
+ +
+ + +
+
+
+
+ +
+ + + + +
+
+
+ +
+ + + + +
+
+
+
+
+
+ + *Blueprint Template +
+
+ +
+ + +
+
+
+
+ + Blueprint {{ecdapp.serviceType.typeName}} upload is in progress... +
+
+
+
+ + + + + + + + + + diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_blueprint_table.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_blueprint_table.html new file mode 100644 index 0000000..687c304 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_blueprint_table.html @@ -0,0 +1,190 @@ +
+ +

EOM Inventory > Blueprints

+ +
+
+ + Please wait while the content loads. +
+
+ +
+
+ + + Create + + + + + + + + + +
+
+ + + +
+
+
+ +
+ {{ecdapp.errMsg}} +
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ApplicationComponentNameVersionCreated DateDeployments + +
+
+ + Deployment Info is loading +
+
+
ActionsOwnerID
+ + + + + + {{rowData.deployments.totalCount}} + + + +
+ + +
+
+ +
+

Expanded Row details for {{rowData.deployments}}

+
    +
  • +
    {{$index+1}}
    +
    + Deployment ID + +
    +
    + Created timestamp + +
    +
    + Modified timestamp + +
    +
  • +
    +
+
+
+ +
+
+ +
+ +
+ +
+ +
diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_popups.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_popups.html new file mode 100644 index 0000000..e9bf3ea --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_popups.html @@ -0,0 +1,657 @@ + + + + + + + + + + + diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_table.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_table.html new file mode 100644 index 0000000..3e404b5 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_deployment_table.html @@ -0,0 +1,148 @@ +
+ +

EOM Inventory > Deployments

+ + +
+
+ + Please wait while the content loads. +
+
+ +
+
+
+
+ + + +
+
+
+ +
+ {{ecdapp.errMsg}} +
+ +
+
+ + + + + + + + + + + + + + + + + + +
Service ID/Deployment Ref.CreatedModifiedTenant + +
+
+ + Tenant and Status Info loading +
+
+
Install StatusActions
+ + + + + + + +
+ + +
+
+
+ +
+
+ +
+
+ +
+ +
+ +
+ +
diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_execution_popups.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_execution_popups.html new file mode 100644 index 0000000..7fa380c --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/inventory_execution_popups.html @@ -0,0 +1,255 @@ + \ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/test.js b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/test.js new file mode 100644 index 0000000..f2f1df2 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/inventory/test.js @@ -0,0 +1,3 @@ +/** + * + */ \ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/dbcl_view.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/dbcl_view.html new file mode 100644 index 0000000..da9fb74 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/dbcl_view.html @@ -0,0 +1,6 @@ +
+

DMaap Bus Controller

+ +
\ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs-view-controller.js b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs-view-controller.js new file mode 100644 index 0000000..f37a4f0 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs-view-controller.js @@ -0,0 +1,271 @@ +appDS2.controller('tabsController', function ($rootScope, $scope, $interval, b2bDOMHelper, $timeout, $route) { + 'use strict'; + $scope.ecdapp = {}; + $scope.ecdapp.opsItem = $route.current.$$route.item; + $scope.ecdapp.activeTabsId = $scope.ecdapp.opsItem ; + $scope.ecdapp.activeTabUrl = ''; + $scope.ecdapp.isInit = false; + $scope.ecdapp.cfy = {}; + $scope.ecdapp.cfy.url = ''; //$rootScope.opsMenu[0].url; + $scope.ecdapp.cfy.site = ''; + $scope.ecdapp.cnsl = {}; + $scope.ecdapp.cnsl.url = ''; //$rootScope.opsMenu[2].url; + $scope.ecdapp.k8 = {}; + $scope.ecdapp.k8.site = ''; + $scope.ecdapp.k8.url = ''; //$rootScope.opsMenu[3].url; + $scope.ecdapp.k8.tenant = ''; + $scope.ecdapp.prom = {}; + $scope.ecdapp.prom.tenant = ''; + $scope.ecdapp.prom.site = ''; + $scope.ecdapp.prom.url = ''; //$rootScope.opsMenu[4].url; + $scope.ecdapp.grf = {}; + $scope.ecdapp.grf.site = ''; + $scope.ecdapp.grf.tenant = ''; + $scope.ecdapp.grf.url = ''; //$rootScope.opsMenu[1].url; + $scope.ecdapp.isFrameLoaded = true; + $scope.ecdapp.cfySite = ''; + $scope.ecdapp.cnslSite = ''; + $scope.ecdapp.appCluster = ''; + $scope.ecdapp.k8.cluster = ''; + $scope.ecdapp.grf.cluster = ''; + $scope.ecdapp.prom.cluster = ''; + + var key = $scope.ecdapp.opsItem; + + // if it's not already part of our keys array + if($rootScope.menuKeys.indexOf(key) === -1) { + // add it to our keys array + $rootScope.menuKeys.push(key); + for (var itemTab = 0; itemTab < $rootScope.opsMenu.length; itemTab++) { + if ($rootScope.opsMenu[itemTab].id === key) { + $rootScope.gTabs.push($rootScope.opsMenu[itemTab]); + //$scope.ecdapp.activeTabUrl = $rootScope.opsMenu[itemTab].url; + break; + } + } + } + $scope.ecdapp.gTabs = $rootScope.gTabs; + /* + angular.forEach($rootScope.opsMenu, function(item) { + if + // we check to see whether our object exists + var key = $scope.ecdapp.opsItem; + // if it's not already part of our keys array + if($rootScope.menuKeys.indexOf(key) === -1) { + // add it to our keys array + $rootScope.menuKeys.push(key); + // push this item to our final output array + $rootScope.gTabs.push(item); + $scope.ecdapp.activeTabUrl = item.url; + } else { + if (item.id === key) { + $scope.ecdapp.activeTabUrl = item.url; + } + } + }); + + + for (var menuTab = 0; menuTab < $scope.ecdapp.gTabs.length; menuTab++) { + if ($scope.ecdapp.gTabs[menuTab].id === key) { + $scope.ecdapp.activeTabUrl = $scope.ecdapp.gTabs[menuTab].url; + break; + } + } + */ + $scope.ecdapp.isInit = true; + $rootScope.activeTabsId = $scope.ecdapp.opsItem; + + $rootScope.$watch('activeTabsId', function (newVal, oldVal) { + if(newVal !== oldVal) { + var selectedTab; + for (selectedTab = 0; selectedTab < $rootScope.opsMenu.length; selectedTab++) { + if ($rootScope.opsMenu[selectedTab].id === newVal) { + //$scope.ecdapp.activeTabUrl = $rootScope.opsMenu[selectedTab].url; + break; + } + } + var selectedTabPanelElement = document.getElementById($rootScope.opsMenu[selectedTab].tabPanelId); + + var elem = null; + if (selectedTabPanelElement) { + elem = b2bDOMHelper.firstTabableElement(selectedTabPanelElement); + } + + if (elem) { + $timeout(function () { + elem.focus(); + }, 100); + } + } + }); + + + $scope.ecdapp.selectAppTenant = function(site) { + if(site != "Select Site") { + for (var indx = 0; indx < $rootScope.site_tenant_map.length; indx++) { + if ($rootScope.site_tenant_map[indx].site === site) { + $scope.ecdapp.appTenants = $rootScope.site_tenant_map[indx].tenant; + break; + } + } + } + } + + $scope.ecdapp.selectCluster = function(tenant) { + if(tenant != "Select Tenant") { + for (var indx = 0; indx < $rootScope.tenant_cluster_map.length; indx++) { + if ($rootScope.tenant_cluster_map[indx].tenant === tenant) { + $scope.ecdapp.appCluster = $rootScope.tenant_cluster_map[indx].cluster; + } + } + } + } + + var stopPolling; + //var doIframePolling; + $scope.ecdapp.appFrameReload = function(cluster, app) { + if(cluster != "Select K8s cluster") { + $scope.ecdapp.isFrameLoaded = false; + for (var indx = 0; indx < $rootScope.tenant_cluster_apps_map.length; indx++) { + if ($rootScope.tenant_cluster_apps_map[indx].cluster === cluster) { + if (app === 'prom') { + $scope.ecdapp.prom.url = $rootScope.tenant_cluster_apps_map[indx].prom; + } else if (app === 'grf') { + $scope.ecdapp.grf.url = $rootScope.tenant_cluster_apps_map[indx].grf; + } else { + $scope.ecdapp.k8.url = $rootScope.tenant_cluster_apps_map[indx].k8; + } + break; + } + } + stopPolling = $timeout(function () { + $timeout.cancel(stopPolling); + stopPolling = undefined; + $scope.ecdapp.isFrameLoaded = true; + },30000); + } + } + + $scope.ecdapp.cfyCnslFrameReload = function(site, app) { + if(site != "Select Site") { + $scope.ecdapp.isFrameLoaded = false; + for (var indx = 0; indx < $rootScope.site_cfy_cnsl_map.length; indx++) { + if ($rootScope.site_cfy_cnsl_map[indx].site === site) { + if (app === 'cfy') { + $scope.ecdapp.cfy.url = $rootScope.site_cfy_cnsl_map[indx].cfy; + } else { + $scope.ecdapp.cnsl.url = $rootScope.site_cfy_cnsl_map[indx].cnsl; + } + break; + } + } + stopPolling = $timeout(function () { + $timeout.cancel(stopPolling); + stopPolling = undefined; + $scope.ecdapp.isFrameLoaded = true; + },30000); + } + } + document.querySelector("iframe").addEventListener("load", function() { + $scope.ecdapp.isFrameLoaded = true; + $scope.$apply(); + }); + $scope.$on("$destroy",function() { + $timeout.cancel(stopPolling); + //$interval.cancel(doIframePolling); + }); + + /* + * $scope.ecdapp.selectK8Tenant = function(site) { + if(site != "Select Site") { + for (var indx = 0; indx < $rootScope.site_tenant_map.length; indx++) { + if ($rootScope.site_tenant_map[indx].site === site) { + $scope.ecdapp.k8Tenants = $rootScope.site_tenant_map[indx].tenant; + break; + } + } + } + } + + $scope.ecdapp.selectK8App = function(t) { + if(t != "Select Tenant for K8s components") { + for (var indx = 0; indx < $rootScope.tenant_cluster_map.length; indx++) { + if ($rootScope.tenant_cluster_map[indx].tenant === t) { + $scope.ecdapp.k8.url = $rootScope.tenant_cluster_map[indx].k8s; + break; + } + } + } + } + + $scope.ecdapp.selectGrfTenant = function(site) { + if(site != "Select Site") { + for (var indx = 0; indx < $rootScope.site_tenant_map.length; indx++) { + if ($rootScope.site_tenant_map[indx].site === site) { + $scope.ecdapp.grfTenants = $rootScope.site_tenant_map[indx].tenant; + break; + } + } + } + } + + $scope.ecdapp.selectGrfApp = function(t) { + if(t != "Select Tenant for Grafana") { + for (var indx = 0; indx < $rootScope.tenant_cluster_map.length; indx++) { + if ($rootScope.tenant_cluster_map[indx].tenant === t) { + $scope.ecdapp.grf.url = $rootScope.tenant_cluster_map[indx].grf; + break; + } + } + } + } + + $scope.ecdapp.selectPromTenant = function(site) { + if(site != "Select Site") { + for (var indx = 0; indx < $rootScope.site_tenant_map.length; indx++) { + if ($rootScope.site_tenant_map[indx].site === site) { + $scope.ecdapp.promTenants = $rootScope.site_tenant_map[indx].tenant; + break; + } + } + } + } + + $scope.ecdapp.selectPromApp = function(t) { + if(t != "Select Tenant for Prometheus") { + for (var indx = 0; indx < $rootScope.tenant_cluster_map.length; indx++) { + if ($rootScope.tenant_cluster_map[indx].tenant === t) { + $scope.ecdapp.prom.url = $rootScope.tenant_cluster_map[indx].prom; + break; + } + } + } + } + + doIframePolling = $interval(function () { + if(document.querySelector("iframe") && + document.querySelector("iframe").contentDocument.head && + document.querySelector("iframe").contentDocument.head.innerHTML != '') + { + $interval.cancel(doIframePolling); + doIframePolling = undefined; + $timeout.cancel(stopPolling); + stopPolling = undefined; + $scope.ecdapp.isCfyLoadDone = true; + } + },400); + + stopPolling = $timeout(function () { + //$interval.cancel(doIframePolling); + //doIframePolling = undefined; + $timeout.cancel(stopPolling); + stopPolling = undefined; + $scope.ecdapp.isCfyLoadDone = true; + },30000); + } + } + + */ + + +}); \ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs_view.html b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs_view.html new file mode 100644 index 0000000..aa5b1f8 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/ccsdk/ops/tabs_view.html @@ -0,0 +1,131 @@ +
+
+ + + {{tab.title}} + + +
+ +
+
+
+
+ + +
+
+
+ + Please wait while the content loads. +
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + Please wait while the content loads. +
+ +
+
+
+
+ + +
+
+
+ + Please wait while the content loads. +
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + Please wait while the content loads. +
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + Please wait while the content loads. +
+ +
+
+ +
\ No newline at end of file diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/b2b-angular.css b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/b2b-angular.css new file mode 100644 index 0000000..7689dd7 --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/b2b-angular.css @@ -0,0 +1,13365 @@ +/*B2B-Angular v1.1.6*/ +.b2b-horizontal-table ::-webkit-scrollbar { + height: 10px; } + +.b2b-horizontal-table ::-webkit-scrollbar-thumb { + background: #666666; + border-radius: 5px; } + +.b2b-horizontal-table .b2b-frozen-col { + font-size: 12px; + font-weight: normal; + font-style: italic; } + +.b2b-horizontal-table .b2b-horizontal-table-inner-container { + overflow-x: auto; } + +.b2b-horizontal-table .b2b-horizontal-table-column-info { + text-align: center; } + +.b2b-horizontal-table .b2b-horizontal-table-legend div[b2b-flyout-toggler] { + color: #0568ae; + cursor: pointer; } + +.b2b-horizontal-table .b2b-horizontal-table-legend .b2b-frozen-cell { + width: 16px; + height: 16px; + background-color: #F2F2F2; + display: inline-block; + margin-right: 10px; } + +.b2b-horizontal-table .b2b-horizontal-table-arrows { + margin-bottom: 20px; } + .b2b-horizontal-table .b2b-horizontal-table-arrows .b2b-disabled-text { + color: #767676; } + .b2b-horizontal-table .b2b-horizontal-table-arrows .b2b-next-link { + padding-right: 15px; } + .b2b-horizontal-table .b2b-horizontal-table-arrows .b2b-prev-link { + padding-left: 15px; } + +@-moz-document url-prefix() { + .b2b-horizontal-table td:first-child { + border-top: none; } } +* { + box-sizing: border-box; } + +:root { + -ms-overflow-style: -ms-autohiding-scrollbar; + overflow-y: scroll; + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + box-sizing: border-box; + font: 0.625pc/1.5 sans-serif; + text-rendering: optimizeLegibility; } + +html { + overflow-y: scroll; + -webkit-overflow-scrolling: touch; + height: 100%; + position: relative; } + +h1, +h2, +h3, +h4, +h5, +p, +blockquote, +figure, +ol, +ul { + margin: 0; + padding: 0; } + +/* a:focus { + outline: thin dotted #191919; +} */ +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: top; } + +sup { + top: .75em; + display: inline-block; } + +sub { + bottom: -0.25em; } + +img { + max-width: 100%; + height: auto; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; } + +.img-no-rwd { + max-width: inherit !important; } + +svg { + display: inline-block; } + +.responsive-img { + width: 100%; + height: auto; } + +button, +input, +select, +textarea { + margin: 0; + font-size: 100%; + vertical-align: middle; } + +::-moz-focus-inner { + padding: 0; + border: 0; } + +button, +html input[type="button"], +input[type="reset"], +input[type="submit"] { + appearance: button; + cursor: pointer; } + +label, +select, +button, +input[type="button"], +input[type="reset"], +input[type="submit"], +input[type="radio"], +input[type="checkbox"] { + cursor: pointer; } + +input[type=search] { + -webkit-appearance: textfield; } + +input[type=search]:-webkit-search-cancel-button, +input[type=search]:-webkit-search-decoration { + -webkit-appearance: none; } + +textarea { + overflow: auto; + vertical-align: top; + resize: none; } + +select { + -moz-appearance: none; + -webkit-appearance: none; } + +[aria-busy=true] { + cursor: progress; } + +[aria-controls] { + cursor: pointer; } + +body { + background-color: #ffffff; + color: #191919; + font-family: "Omnes-ATT-W02", Arial; + font-size: 1.6rem; + line-height: 2rem; + margin: 0; + position: relative; + width: 100%; + -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; } + +small { + font-size: 1.6rem; } + +.container { + margin: 0 auto; + padding: 0; } + +.tooltip { + display: inline-block; + height: 20px; + margin: 1px 0 0 7px; + vertical-align: middle; } + +.tooltip-wrapper { + display: none; } + +@font-face { + font-family: "Omnes-ATT-W02"; + src: url("fonts/Omnes_ATTW02.eot"); + src: url("fonts/Omnes_ATTW02.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02.woff") format("woff"), url("fonts/Omnes_ATTW02.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Medium"; + src: url("fonts/Omnes_ATTW02Medium.eot"); + src: url("fonts/Omnes_ATTW02Medium.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Medium.woff") format("woff"), url("fonts/Omnes_ATTW02Medium.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Italic"; + src: url("fonts/Omnes_ATTW02Italic.eot"); + src: url("fonts/Omnes_ATTW02Italic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Italic.woff") format("woff"), url("fonts/Omnes_ATTW02Italic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Light"; + src: url("fonts/Omnes_ATTW02Light.eot"); + src: url("fonts/Omnes_ATTW02Light.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Light.woff") format("woff"), url("fonts/Omnes_ATTW02Light.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Bold"; + src: url("fonts/Omnes_ATTW02Bold.eot"); + src: url("fonts/Omnes_ATTW02Bold.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Bold.woff") format("woff"), url("fonts/Omnes_ATTW02Bold.woff2") format("woff2"), url("fonts/Omnes_ATTW02Bold.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Light-Italic"; + src: url("fonts/Omnes_ATTW02LightItalic.eot"); + src: url("fonts/Omnes_ATTW02LightItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02LightItalic.woff") format("woff"), url("fonts/Omnes_ATTW02LightItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02LightItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Medium-Italic"; + src: url("fonts/Omnes_ATTW02MediumItalic.eot"); + src: url("fonts/Omnes_ATTW02MediumItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02MediumItalic.woff") format("woff"), url("fonts/Omnes_ATTW02MediumItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02MediumItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Bold-Italic"; + src: url("fonts/Omnes_ATTW02BoldItalic.eot"); + src: url("fonts/Omnes_ATTW02BoldItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02BoldItalic.woff") format("woff"), url("fonts/Omnes_ATTW02BoldItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02BoldItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +/* TODO: Build a reference page for these classes */ +.font-regular { + font-family: "Omnes-ATT-W02" !important; } + +.font-light { + font-family: "Omnes-ATT-W02-Light" !important; } + +.font-italic { + font-family: "Omnes-ATT-W02-Italic" !important; } + +.font-light-italic { + font-family: "Omnes-ATT-W02-Light-Italic" !important; } + +.font-medium { + font-family: "Omnes-ATT-W02-Medium" !important; } + +.font-medium-italic { + font-family: "Omnes-ATT-W02-Medium-Italic" !important; } + +.font-reset { + font-style: normal; + font-variant: normal; + font-weight: normal; + text-transform: none; } + +.visible-phone { + display: none !important; } + +.visible-tablet { + display: none !important; } + +.hidden-desktop { + display: none !important; } + +.visible-desktop { + display: inherit !important; } + +.row, +.row-nowrap { + margin-left: 0; } + +.row:before, +.row-nowrap:before, +.row:after, +.row-nowrap:after { + display: table; + content: ""; + line-height: 0; } + +.row:after, +.row-nowrap:after { + clear: both; } + +.row:before, +.row-nowrap:before, +.row:after, +.row-nowrap:after { + display: table; + content: ""; + line-height: 0; } + +.row:after, +.row-nowrap:after { + clear: both; } + +.row, +.row-nowrap { + display: flex; } + +.row > [class*="span"], +.row-nowrap > [class*="span"] { + float: left; + margin-right: 14px; + margin-right: 1.40845%\9; } + +.row > [class*="span"]:last-child, +.row-nowrap > [class*="span"]:last-child { + margin-right: 0; } + +.row > [class*="span"].centered, +.row-nowrap > [class*="span"].centered { + margin-left: auto !important; + margin-right: auto !important; } + +.row.no-flex, +.row-nowrap.no-flex { + display: block; } + +.row.no-flex > [class*="span"], +.row-nowrap.no-flex > [class*="span"] { + margin-right: 1.408450704225352%; } + +.row.no-flex > [class*="span"]:last-child, +.row-nowrap.no-flex > [class*="span"]:last-child { + margin-right: 0; } + +.row.flex-justify, +.row-nowrap.flex-justify { + justify-content: space-between; } + +.row.flex-justify > [class*="span"], +.row-nowrap.flex-justify > [class*="span"] { + flex: 1 1 0; } + +.row.flex-justify > .flex-col, +.row-nowrap.flex-justify > .flex-col { + margin-right: 14px; + margin-right: 1.40845%\9; } + +.row.flex-wrap, +.row-nowrap.flex-wrap { + flex-wrap: wrap; } + +.align-items-top { + align-items: flex-start; } + +.align-items-center { + align-items: center; } + +.align-items-bottom { + align-items: flex-end; } + +.align-self-top { + align-self: flex-start; } + +.align-self-center { + align-self: center; } + +.align-self-bottom { + align-self: flex-end; } + +.row .fixed-230 { + flex: 0; + display: block; + width: 230px; + vertical-align: top; + min-width: 230px; + background-color: #efefef; } + +.row .fluid-space { + flex: 1 1 0; + display: block; + vertical-align: top; + padding-left: 0; + padding-right: 20px; + width: 100%; } + +.row .fixed-230 + .fluid-space { + padding-left: 20px; + padding-right: 20px; } + +.row .fluid-space:last-child { + padding-right: 0; } + +.span1 { + width: 7.042253521126761%; } + +.span2 { + width: 15.49295774647887%; } + +.span3 { + width: 23.94366197183099%; } + +.span4 { + width: 32.3943661971831%; } + +.span5 { + width: 40.84507042253521%; } + +.span6 { + width: 49.29577464788733%; } + +.span7 { + width: 57.74647887323944%; } + +.span8 { + width: 66.19718309859155%; } + +.span9 { + width: 74.64788732394367%; } + +.span10 { + width: 83.09859154929578%; } + +.span11 { + width: 91.54929577464789%; } + +.span12 { + width: 100%; } + +.offset1 { + margin-left: 8.450704225352113%; } + +.offset2 { + margin-left: 16.90140845070423%; } + +.offset3 { + margin-left: 25.35211267605634%; } + +.offset4 { + margin-left: 33.8028169%; } + +.offset5 { + margin-left: 42.25352113%; } + +.offset6 { + margin-left: 50.70422535%; } + +.offset7 { + margin-left: 59.15492958%; } + +.offset8 { + margin-left: 67.6056338%; } + +.offset9 { + margin-left: 76.05633803%; } + +.offset10 { + margin-left: 84.50704225%; } + +.offset11 { + margin-left: 92.95774648%; } + +.align-center { + margin: 0 auto; + text-align: center; } + +[class*="span"].align-center { + margin: 0 auto !important; + float: none; } + +.align-left .container { + padding-left: 0 !important; + margin: 0 !important; } + +/* BEGIN RESPONSIVE-4.LESS ************** */ +@media (min-width: 1025px) { + .row > [class*="span"], + .row-nowrap > [class*="span"] { + margin-right: 20px; + margin-right: 1.487301587301587%\9; } + .container { + padding-left: 20px; + padding-right: 20px; + max-width: 1260px; } + /* 1col = 6.878306878306879 */ + /* 1colgutter = 1.587301587301587 */ + .span0 { + display: none; } + .span1 { + width: 6.878306878306879%; } + .span2 { + width: 15.34391534391534%; } + .span3 { + width: 23.80952380952381%; } + .span4 { + width: 32.27513227513228%; } + .span5 { + width: 40.74074074074074%; } + .span6 { + width: 49.20634920634921%; } + .span7 { + width: 57.67195767195767%; } + .span8 { + width: 66.13756613756614%; } + .span9 { + width: 74.60317460317461%; } + .span10 { + width: 83.06878306878308%; } + .span11 { + width: 91.53439153439154%; } + .span12 { + width: 100%; } + .offset1 { + margin-left: 8.465608465608466%; } + .offset2 { + margin-left: 16.93121693121693%; } + .offset3 { + margin-left: 25.3968253968254%; } + .offset4 { + margin-left: 33.86243386%; } + .offset5 { + margin-left: 42.32804233%; } + .offset6 { + margin-left: 50.79365079%; } + .offset7 { + margin-left: 59.25925926%; } + .offset8 { + margin-left: 67.72486772%; } + .offset9 { + margin-left: 76.19047619%; } + .offset10 { + margin-left: 84.65608466%; } + .offset11 { + margin-left: 93.12169312%; } + .tooltip-size-control { + position: relative; + width: 400px; } + .thumbnails > li { + margin-left: 1.40845070422535%; } + .row .thumbnails { + margin-left: 0; } } + +/* END RESPONSIVE-4.LESS ****************** */ +/* BEGIN RESPONSIVE-3.LESS ******************* */ +@media (min-width: 768px) and (max-width: 1024px) { + .hidden-desktop { + display: inherit !important; } + .visible-desktop { + display: none !important; } + .visible-tablet { + display: inherit !important; } + .hidden-tablet { + display: none !important; } + .container { + width: 100%; + margin: 0 auto; + padding-left: 20px; + padding-right: 20px; } + .span0-md { + display: none; } + .span1-md { + width: 7.042253521126761%; } + .span2-md { + width: 15.49295774647887%; } + .span3-md { + width: 23.94366197183099%; } + .span4-md { + width: 32.3943661971831%; } + .span5-md { + width: 40.84507042253521%; } + .span6-md { + width: 49.29577464788733%; } + .span7-md { + width: 57.74647887323944%; } + .span8-md { + width: 66.19718309859155%; } + .span9-md { + width: 74.64788732394367%; } + .span10-md { + width: 83.09859154929578%; } + .span11-md { + width: 91.54929577464789%; } + .span12-md { + width: 100%; } + .offset1-md { + margin-left: 8.450704225352113%; } + .offset2-md { + margin-left: 16.90140845070423%; } + .offset3-md { + margin-left: 25.35211267605634%; } + .offset4-md { + margin-left: 33.8028169%; } + .offset5-md { + margin-left: 42.25352113%; } + .offset6-md { + margin-left: 50.70422535%; } + .offset7-md { + margin-left: 59.15492958%; } + .offset8-md { + margin-left: 67.6056338%; } + .offset9-md { + margin-left: 76.05633803%; } + .offset10-md { + margin-left: 84.50704225%; } + .offset11-md { + margin-left: 92.95774648%; } + .tooltip-size-control { + position: relative; + width: 300px; } } + +/* END RESPONSIVE-3.LESS ******************* */ +/* BEGIN RESPONSIVE-2.LESS *************** */ +@media (max-width: 767px) { + .hidden-desktop { + display: inherit !important; } + .visible-desktop { + display: none !important; } + .visible-phone { + display: inherit !important; } + .visible-tablet { + display: inherit !important; } + .hidden-phone { + display: none !important; } + .hidden-tablet { + display: none !important; } + .container { + width: auto; + padding-left: 15px; + padding-right: 15px; } + /*.row{ display:block; }*/ + .row > [class*="span"] { + float: none; + margin-left: 0; + margin-right: 0; + width: 100%; } + .row { + display: block; } + .row.flex > .flex-col, + .row-nowrap.flex > .flex-col { + margin-right: 0; } + .row .fixed-230 { + display: block; + width: 100%; } + .row .fluid-space { + display: block; + padding-left: 0; + padding-right: 0; + width: auto; } + .row .fluid-space + .fixed-230 { + padding-left: 0; } + .row .fluid-space:last-child { + padding-right: 0; } + .span0-sm { + display: none; } + .span1-sm { + width: 7.042253521126761%; } + .span2-sm { + width: 15.49295774647887%; } + .span3-sm { + width: 23.94366197183099%; } + .span4-sm { + width: 32.3943661971831%; } + .span5-sm { + width: 40.84507042253521%; } + .span6-sm { + width: 49.29577464788733%; } + .span7-sm { + width: 57.74647887323944%; } + .span8-sm { + width: 66.19718309859155%; } + .span9-sm { + width: 74.64788732394367%; } + .span10-sm { + width: 83.09859154929578%; } + .span11-sm { + width: 91.54929577464789%; } + .span12-sm { + width: 100%; } + .offset1-sm { + margin-left: 8.450704225352113%; } + .offset2-sm { + margin-left: 16.90140845070423%; } + .offset3-sm { + margin-left: 25.35211267605634%; } + .offset4-sm { + margin-left: 33.8028169%; } + .offset5-sm { + margin-left: 42.25352113%; } + .offset6-sm { + margin-left: 50.70422535%; } + .offset7-sm { + margin-left: 59.15492958%; } + .offset8-sm { + margin-left: 67.6056338%; } + .offset9-sm { + margin-left: 76.05633803%; } + .offset10-sm { + margin-left: 84.50704225%; } + .offset11-sm { + margin-left: 92.95774648%; } + input { + padding: 8px 15px 8px 15px; } + .field-group input.input-emphasized[type="search"] + .reset-field:after { + top: 14px; } + .field-group input.input-emphasized[type="search"] + .reset-field { + height: 46px; + top: 1px; } + .marquee { + margin-bottom: 30px; } + .marquee .blur-overlay { + border-radius: 0; + position: absolute; + bottom: 0; + left: 0; + width: 100%; + margin: 0; + padding: 34px 15px 30px; } + .marquee + div { + margin-top: 30px; } + .marquee h1 { + font-size: 1.8rem; + letter-spacing: -0.035px; } + .marquee .lead { + font-size: 3.0rem; + line-height: 3.6rem; + margin-bottom: 0; } + .marquee p:not(.lead) { + font-family: "Omnes-ATT-W02-Light"; + font-size: 1.8rem; + margin-bottom: 0; } + .marquee .btn-fullwidth { + margin-top: 10px; + width: 100%; + float: none; } + .tooltip-size-control { + width: 100%; } + .table-wrapper, + .accordion-table-layout { + margin-left: -15px; + margin-right: -15px; } + .table-wrapper caption { + padding-left: 15px; } } + +@media (max-width: 480px) { + .span1-xsm { + width: 7.042253521126761%; } + .span2-xsm { + width: 15.49295774647887%; } + .span3-xsm { + width: 23.94366197183099%; } + .span4-xsm { + width: 32.3943661971831%; } + .span5-xsm { + width: 40.84507042253521%; } + .span6-xsm { + width: 49.29577464788733%; } + .span7-xsm { + width: 57.74647887323944%; } + .span8-xsm { + width: 66.19718309859155%; } + .span9-xsm { + width: 74.64788732394367%; } + .span10-xsm { + width: 83.09859154929578%; } + .span11-xsm { + width: 91.54929577464789%; } + .span12-xsm { + width: 100%; } + .offset1-xsm { + margin-left: 8.450704225352113%; } + .offset2-xsm { + margin-left: 16.90140845070423%; } + .offset3-xsm { + margin-left: 25.35211267605634%; } + .offset4-xsm { + margin-left: 33.8028169%; } + .offset5-xsm { + margin-left: 42.25352113%; } + .offset6-xsm { + margin-left: 50.70422535%; } + .offset7-xsm { + margin-left: 59.15492958%; } + .offset8-xsm { + margin-left: 67.6056338%; } + .offset9-xsm { + margin-left: 76.05633803%; } + .offset10-xsm { + margin-left: 84.50704225%; } + .offset11-xsm { + margin-left: 92.95774648%; } } + +/* END RESPONSIVE-2.LESS ******************* */ +/* BEGIN RESPONSIVE-1.LESS ************** */ +.xxxxxxxx-begin-responsive-480px.less { + /* placeholder */ } + +@media (max-width: 480px) { + .hidden-desktop { + display: inherit !important; } + .hidden-tablet { + display: inherit !important; } + .hidden-phone { + display: none !important; } + .visible-desktop { + display: none !important; } + .visible-tablet { + display: none !important; } + .visible-phone { + display: inherit !important; } + .container { + width: auto; + padding-left: 15px; + padding-right: 15px; } } + +@font-face { + font-family: 'icoPrimary'; + src: url("fonts/icons/icoPrimary.eot?timestamp=@@timestamp"); + src: url("fonts/icons/icoPrimary.eot?timestamp=@@timestamp#iefix") format("embedded-opentype"), url("data:font/woff2; charset=utf-8;base64,d09GMgABAAAAABD0AAsAAAAAIegAABClAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAfBEICroMr2IBNgIkA4EgC1IABCAFgyoHIBupG1GUj1aB7Gdh7HA7jbPiOgkYNpcuoRGZ37q6G3w0QpLZI9q02bs97HSRw5ogEesTAjElSqy0FGpCCRWzJBXR9DXJiydPX7T+Ip7vq3Pv2mcm2W+ShSugqkVXWVfbquUDpNKMTezCAYKwBVR91VU1+/0yazd3Lg9/AVmoSmRNKGStQEmoXKfLdLXNNyxbs5Yfwc8kTV8FeDfk73Xq+p9zCqBT5NCYYSvusE3/f1mxnmQFWA6RnaJdkoqgAvFKLJdQbnlDXMbO3TvsHZa1ZsvFBqhZqAl6879jOe2lIjbiiEUU6HPz354AaHoI7QMGgDpOXQeAvZtjQTfBi9SwGR2SIFAN8E15bK7/byAvdR15B0eq3dPoY80wQNCRBpSOYaquB+mFOI/OPmQdcg6lDWUMzf2mPPFfIgEMIB8Vhmz3g8Q/IzYiOSH/Lz9muMlr/jtGiCJVD2IyIRDYAKCZgxRuYmymuEdFrlK6KIorkyoV0Jgn91QkTcVrHlnDg0jnUvGnTA92OqstI80g6PVEEm6BJ58mg+OFFJIiZSQJRK/PEoSkZFHIMFiIwSg5iVar1xtzjZI/tyLTWigIQa1DY08zd4EUSVJK8Gz82QyGgCCkMyoZr7IHBBsvEoBwgxx6h+4EV3YeZwzc4W52q6lXGM9evr6oy1gTMmP79l5RTsJBClIq7jrFUaLH1BlHKTeOKPwhzFfAQqrZ2mdSzISbZTdbdQl5bjevMrg6SgcDfJsLwZ/gjUAu7PiWjAuyegyQbSvIRz8KdZreQMHJY91AKf2ArQnUq2M6QdzlV0h1cKvJFCQVXWrjZUR+mfsPuqrSKAw7vXHdA4jIfVYLo4QrFyzwSOWFzqWWIKXKCEE+n6FtUFH2YbuLsSii68GKBu9o6y0RSZVJ6FRPGxY6Wb2FSJub7hiVhvKqc+F2ZtFE3vy1GtWhiilfD6YouogRzzUU9QRuchi1FjSJJgeylOAoWaCMiX6CWJbjEw6CqMHl0OrKXnIfH7FAFHoZV2FPGgcTV4VSp4ELLxaGwcusuFYdvr5GheLQpKy5GMVLTbBdzuKpytLgd8xSTL08wGmaatJUkkztzRHn2w1Xct5RnWGYyhc+auWs9aErust7X2pNknPQ2B2xIlkrnvHaZA1jFaxXrNVb3cXM+hsVaV1EXdc/huV7XRgkZtxMJhCI4mMuecG0QWlOcxNicqGmtL5Yl1MtLdMuJZAYGFr+/P8+gr7e06WKrICOPml5b5Sf7tmW1JdFGrwGUEwBf/ugoV77AoqJkjXmTRyNQO+F45oBx8CweKoOWwPZj+aomITyzIUd5nHykU3h0LJjuvrUF2MQTKJTKF3omb9SMBepKzcOhZBoAWkP8+mKQRI+dD7mrTs3znGe6gr/mwGLt422RgkZnEDSK3zTEJuKNuypY3YIlACmD/E9UiDiW2pRpQFoIgY7UcwtdgFPmOI1KptGbgcZMkRPIREEQT6lN2dwYWs3U1lqLIorlivL7I4rN2oukpq/qu/QZiikJ5jZH+SjMMi4EXhLg9b7QhPFhFjkFki1i1pl8SNzSoZkDACAalthJVIMPBQdXQdiqtHyZrzsHFI1T5Gb6wPe+qNx+crLqRAFgeKxDOFLaukLuRIbl/ourN1HPnsxaSqUSLpJAXWIYs5UHlzOXzuteVtoQ9hau02jSTcwSs6UMVxp7dI8ung189KKGvmmpMtZF8G85uXCLcWOprejUii+ko1h/AYKs28W8lVRxlHzLI3XJYBelGiLoBBX01ilMCJwScYKsWmLVkmq3hLYezFPsXpoGkVE5aRiCpXBlhyDAsMTY/jqTSxhSLVsMwKRptxYOTg30SKjXESn43ch5IpJaBAUozLiiL05h3Fv0VN2IQVOPehaVXcThJXuuUP07jSi5YgkX2ndValmfTYCjkkCWR8V63ctCjduimfsyJwyXMMi0V6sJBKjXkPZ56wEKGZTEvPG49iM57DV0TwzvaYbajGyUZv0NuTSsnNYBdvKsVZ80SobcaqLo+xtycdXWB+FcsLCVjAcE0eYu6bcbIAxp3N1M+GWLWpksrCjNS5NMpa365lnKZz9bAw3TUuws386w6Zoq20INqiI5w/boj3XHG9/C3MNubDPWsPY/O5u09KaHVOf+vbCgu3+6z5//jc2vXnoO896lqr8R6+f2/+3/Id9t16NzQwm4gf+PncKN87cnnbF+sZXu3+sH5hdu8N1wRwqX6mdkxYu6pw+sW2997RlbPcH0/ZmTC8raJhvqPKYLvXHRhWudJ1Liu64Nz1W8PzkrZp6Z9LWpSP6fa/kdETO32qo9piy5EebyrZ4nnduD+7TLUhvKr613OaZIfbAshG9RfHkhuZOayS3tCbN4lZQQOUt7CEYG95Y7LrV1nEsHErjtvc7U3FsAU4PVnTl3GUMT+i0jMk+bNV9k3a984q/YP+GVL9/c+pBVZ7Gvrd4a81CErT+ojV89xV8dPwpYSkhdeQFsbU/BImq2YOBHTsCg7NnF7Smp9Vs1IHiwstT7vCvX+e/c8oU/x3r1t/pJwZ5vcwDM5Q4XaliSPRz3lVO0/posZkkb11CSuJ1weOcUyd/YPjR8IEMNpzXWqe+plZfVyty0Ta+hbOS+4Pf5+eQB1TkesscVVylVfWpwqpeIo+ZoNBXpr+m7+D83+FFaR3pYBNKfmNFtoNLqD+VsMNrGbzE/1kJMbia6E+rDmfQxMiOnos7MBPGczniMTmEC0RIN5G5tSsIWTFMdU1VqI6Xpri6VYdDOJypzNwIhQfQq/IHhgEY5LaybdyPNqvkJkJV6tvK2iyFAwbOgV9Wx9VnSraqrlGptkLhKMtVKSz+URWSxvuO4w5c+ZoW+nHfeEuEP8SwJA1THlNe7bQ/rsYFBzQfaIpwlKlCcBEi6ADB/HoNDjMowhoPzicj9C72LEWiQtTTeZbsSH8kbccSNEkpuNMeSQ9V0ZlhnvATXeK1XMiOLlVcNbkokdXLjVbLbcF2Y2BnWSxWtjMQKN8Jesoj7q5ySmoZhELhgawx451aHRErl0sOS5WjK7SR/70L9DPSJxQFHJCod5eSp4TGVrqNha981GKj7l0W2QAYb4DIgf7MRzL6D3oWg0RR8Hob0w/2ZzyS2Y+CrO0HbWQjILQRItofbI/YPtamLAOeQjAgH0d4IjtMVhCykoSZ7YHKsCquropUYZpZHT90yiY4+ECT4RefbRyPNykYkPewzh5K73tqrO/kkiUnfWPHCirpaTkWfa3vxypHHMydVDyqsTnYNtppK0W+fwozn7eXbcxSxhQIuIX6Wr1GH9Sr9SEi9YvM8YU/+8jIKk8QNbnTIquTCzti6ZyeS491FCYtiZvjFpYTzJp41vJp4J6lULO3NnWBM700r7aqrZmaIBZaBzeGbWVzV84YVf1EU853ybe8b7QojW6d5HDbeafdSdEgB2+32+D3NRpj54fZLwvC99mVzccCu8LEiqxx2YNZWEaH0/677E86jRpT8it4PjlV+Mu6J0Vh144nfrg77dq1wLWe/Y6994T//mvZWSjZN5H8ePVdv36Wwf/u1Y8JAkAIsBKbl47Ll9++2wzmu9/e9HFLzbIYIO41PbOPPMdEOCU/3Sg9a3bX57+hFtVv1NVXWUINujqdSpevU+q862up1UEROWGr63KbvtWcZYFjgd1WQeQIQKfv/fRKVdLxpCkCVlC7aAVO2p58udqwMfsljBIv7tt1UNKjATlYVfE1pmhKf10H3qktgGC/kYk6imEfAALQvGuq/BZoxCaUw2EsjWDQX9RTmMJJxqqDJLXLkXA4UU8z1DHto99cmRs9NvfsBpBnVCcfwc3xBfAZHKQp6yrHAetqau7Y/3qvEfPOzguH15gjv45zhAYoTAEAlYrW3iuxRcuBeAgAUCkE0ttVJq/ZnGKiMV2qMXtN5OxaIKljlsAszEVLJyYof/m8/L/cdcydFqyuDKfkeZiudqlBdxIAGK4b9JUNAEBS0cjW0hKqLzrGGiOnh3KQ/zP+avzv3uyVqkr6jqEERzETpZddeWYZuMFzMCckS8bWU8OdbYMBh8s10jG433q4j128fIas0f1p8rkb6jweLnX7OtuL+kpGBcrKgoESn9SsUvR4Pc0KX6atPtKUnJ3lTw6Sw8xTjUZQsArReKdhKA8Z9axQK95JCQIbf6d4dVoFXum8/L+RPeZOzU+iJ4+kzV/xyvj1IhSXlObJifEYeN2dxp+mD3oyxtTWTEjLz2e60vNVeAbz3vOiChblVxi/NFbko0rPy+6g473UEa6BhoHqSRNqfVRa3Zz9L9FcPLKtpDTQVjywaMCVMuJm0JFLXsOki3ypXQ70cBq6yXYAgEmkm0C6ZmZzjMlyCROr6iq6K1Zs7MovYVA47f9pWVit40j6vHVwGk/4uay9spjYHWVCzCIMeS7ceBFT4sNoRzwPXw8b/4KIjNR2D+hitbmpNR9o86D4fgvE4DgMWLpa1aARLEtHarsBwkeHS20xkbBYWCwsnsd7PCixPw2A8gwfyq3D5A8Mhu/kYWNu5IP+rfKHhvF4EcYMAOT+kX3gyOjgct+RvgW99/bc+9z5vp4+wyP3Htnx8PupRCcPPCfxIznC8Yh7PMBL3FtWTrcBOMK32gxsKw22MVvMd9ga1ZzZ3+N2thOtW3R/Z88Do5MDPzmEW/zAvoN37evbJ++7d9+F3fLaiznEQ/7Gp5K2Jw8OmgJasSIPEpK3UzRDYiWL8KxtIc2veoLtVb+vYS8K+/MXt7erb7Bu9U2WvS5eavPNPl/Fq+ol0Tlzoxnq1WS5trnU5LReMjlMTxQvdmm411KfpVyhbFzALMcLnn7llvEH1e+z6sfZCer3QJ4ozNngqVQ8oPAiWV332kDBUz0DlqjlkpUniltC1ktm3OZRj7ZDe4nEtHFtjFw6J46fLsQdzCbqh5kOvOkqu3czy/E2vJzB8xBjE47hSeAQUDQ+NIIJJHcgc33JO5go3T5nbvdKNih/LyMcY/AKjIRcPkhVk/UiuI5Kobe/Wfmb29tOdK4Y3xGNAZo99oRLIycsxqF/53E//4rOrZ7IcyUrz1zamdx7l22wa9VPbTt/+3RpwS7XGPXTfznuQ4seHl/I1Bfh7v704h7DbJ1YrZ9fk1Cjh89vud1+e6Dn9oLND1k2nyGb15Py4uQHm/bPPjd6TvWE86Nnb7oWF5eHKmfisSDQBo638MeOe4u9vwwNv3pLvPs/SCLXK3U61/uidPwYDwAaoAEAXk1sFTnoJryR2CFc6H1YnqgROygXnEj8QI9B6wABAAJ4aV5G3xSx/DcViwEA4HX9bwcnNv8/hYF6CgBUCoBj8/ctSgEwLfAaYK1MjKj3JKNalv6Np+hn6IVTECHLyhCO9gGOC0EIQwCL8Cq+AZgJs8mkBPDCFHwJcAOWw3x4DAZhFkRgrBZK8p8ApGFPeAVEoOa7qxHgnjy5EWikZwYFSliTQYMGqgAL+zIYYCE5QwEamBTUgAXu+SEdYXWNHjSQQYEAm5G2CX7EEE5kMCBDFiogxGbRQD5cnhVZ8IcXEWAWRGABBGDxrs+DaZm26jMzoXkuN4Qh+sQlDhpwMeaDHfLABW7SRUiQ/qzjCjAKohCDZTA3bBHS848Uz/MxDNlf8H9qtgQaVMKluR6D6M4VxWl3PQozoE+HVbPq54ZtzPEO3AU0bAAAAAA=") format("woff2"), url("data:application/font-woff; charset=utf-8;base64,d09GRgABAAAAACJAAAsAAAAAIfQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABCAAAAGAAAABgEAQFaGNtYXAAAAFoAAAAfAAAAHy9F7zuZ2FzcAAAAeQAAAAIAAAACAAAABBnbHlmAAAB7AAAHRgAAB0Yg9YlNWhlYWQAAB8EAAAANgAAADYLSS2jaGhlYQAAHzwAAAAkAAAAJAbOAvZobXR4AAAfYAAAAKAAAACglK4SEGxvY2EAACAAAAAAUgAAAFKIhIEEbWF4cAAAIFQAAAAgAAAAIAA4ANNuYW1lAAAgdAAAAaoAAAGq0IdVx3Bvc3QAACIgAAAAIAAAACAAAwAAAAMD6QGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA6jwCzP7NATMCzAEzAAAAAQAAAAAAAAAAAAAAIAAAAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEAGAAAAAUABAAAwAEAAEAIOkb6SLpJekn6WzqPP/9//8AAAAAACDpAOkf6SXpJ+ls6jz//f//AAH/4xcEFwEW/xb+FroV6wADAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAYACf7JA/0CtwASAC0ATABzAJgArQAAFx4DMzI+AjcOAyMiJicFMj4CNz4BNz4BNw4DIyIuAiceAzMnIi4CJxQWFx4BFx4DMzI+Ajc+AT0BDgMjAQ4BBwYWFx4DMzI+Ajc2NCcuAScWDgIjIi4CNT4BNTIwIyUeARUUDgIjIiY1NDY3DgEHDgEVFB4CMzI+AjU0JicuAScnLgEjIgYHDgEVFBYzMj4CNTYmJ8ogSE5ULDBbVE0hDzlUbkN1mSgBWC9gWk8dEh4PCRAGHGuLpFU8eWxXGRddf55YiGGQYzYHBAQCDQsXU3mhZYqwaC0GCQsJda3SZv6cCxYEAgMCDEmExolTkXBJCwQEBxELAXarvEZKhmQ7AgQCAgMXAgE+c6VmmFcJCxMjEQcHVIeqVluGWCoPEw0ZDUo6gElJgzoRFJCEQXFUMAIPD84ZJxsOESEuHQodGxQqGBoNGiYaDCYYDiEPKUQvGhMmOCYzTjQb3ig8Rx8VMBMJGA0YNy8eJzY2DxVGIh0lUEMsAaIVQRMJCgcYPDMjFCc5JQ0fExUwEzFQOB8cMEIlCxEGogIFBBU2LyBWJQwaDRMlFQgQBCY+LBgbKzYbExsWDRYKNiIlJSQJEgogORIcJBIGDggAAAEA+gCaAw0A5gANAAAlISImNTQ2MyEyFhUUBgLg/kAOGBURAcYPGBqaFRERFRURERUAAAACAAD+wAQAAsAAEwAnAAABIi4CNTQ+AjMyHgIVFA4CAyIOAhUUHgIzMj4CNTQuAgIAarqLUVGLumpquotRUYu6al+of0pKfqlfX6h/Skp+qf7AUYu6amq6i1FRi7pqarqLUQPQSn6pX1+of0pKf6hfX6h/SgAAAAADAEn/UgO3Ai4AEAAgADAAAAEhIgYdARQWMyEyNj0BNCYjESEiBh0BFBYzITI2PQE0JgMhIgYdARQWMyEyNj0BNCYDkvzcDxYWDwMkDxYWD/zcDxYWDwMkDxYWD/zcDxYWDwMkDxYWAi4WD0kPFhYPSQ8W/tsVD0oPFRUPSg8V/twWD0kPFhYPSQ8WAAQAqv8VA1YCawAPAB0AKgA7AAABISIGFREUFjMhMjY1ETQmAyMiJjU0NjsBMhYVFAY3DgEHBiY3PgE3NhYHNxQGIyEiJjURNDYzITIWFREDIv28Fh4eFgJEFh4ew0QJDQ0JRAkMDIQCEgwWHwQDEgwWHwUbDAj97ggLCwgCEggMAmseFf0QFR4eFQLwFR785QwJCQ0NCQkMDQwSAgQfFQwSAwQfFmwIDAwIAlYICwsI/aoAAAYAnP8VA2QCawAQACEASABUAGEAbwAAATQmIyEiBhURFBYzITI2NREDISImNQM0NjMhMhYVERQGIwMRFAYjISImNTQ2MyEyNjURNCYjISIGFREUBiMiJjURNDYzITIWFQMiBhUUFjMyNjU0JgciJjU0NjMyFhUUBiMnFAYrASImNTQ2OwEyFgNkHRT9mhQdHRQCZhQdMf2aCxABEQsCZgwQEAwYEg3+CAUGBgUB+AQFBQT+CAQFBwQFBhINAfgNElERGRkREhgYEggNDQgJDAwJTQYEVgQGBgRWBAYCOxQcHBT9ChQcHBQC9vzvEAsC9gsQEAv9CgsQAtT92Q0RBgUEBgUEAicDBQUD/pQEBwcEAWwMEhIM/ZwYEREYGBERGD0MCAgMDAgIDBQEBgYEBQYGAAAAAgBj/24DnQIBACIAMwAAASEiBhURFBYzIRUjIgYVFBYzITI2NTQmKwE1ITI2NRE0JiMDFAYjISImNRE0NjMhMhYVEQNp/S4WHh4WAU2IDBAQDAFIDBAQDIgBTRYeHhYFDAn9YgkMDAkCngkMAgEeFf5IFh47EQwLERELDBE7HhYBuBUe/i8JDAwJAYQIDAwI/nwAAAMAdf9/A4sCGgAiADIAWQAAASEiBhURFBYzIRUjIgYVFBYzITI2NTQmKwE1ITI2NRE0JiMTFAYjISImNRE0NjMhMhYVBxEUBiMhIiY1NDYzITI2NRE0JiMhIgYVERQGIyImNRE0NjMhMhYVA2X9NhAWFhABWpkEBwcEAUgEBwcEmQFaEBYWEBEKB/02BwoKBwLKBwonDgr9yQQHBwQCNwECAgH9kgECBgUEBg4KAm4KDgIaFw/+CRAWQgcEBAcHBAQHQhYQAfcPF/3jBwkJBwH3BwkJBzD+bgoOBgUEBgIBAZIBAgIB/vYEBwcEAQoKDg4KAAADAQT/DwL8AngAHAAqADsAAAEuASsBIgYHDgEVERQWFx4BOwEyNjc+ATURNCYnAyMiJjU0NjsBMhYVFAY3FAYjISImNRE0NjMhMhYVEQKrJHUPBg91JCgpKSgkdQ8HDnUkKCkpKIBWDRISDVYNEhKLDAj+oggMDAgBXggMAnMDAgIDBCsm/UolKwQDAgIDBCslArYmKwT82BINDRITDA0ShwgMDAgCFgkMDAn96gAAAAIAAP7ABAACwAATACcAAAEiLgI1ND4CMzIeAhUUDgIDIg4CFRQeAjMyPgI1NC4CAgBquotRUYu6amq6i1FRi7pqUIxoPD1ojE9QjGg8PGiM/sBRi7pqarqLUVGLumpquotRA4A8aIxQUIxoPD1ojE9QjGg8AAAAAAEAAP7ABAACwAAoAAABBx4BFRQOAiMiLgI1ND4CMzUiDgIVFB4CMzI+AjU0LgInA2lYMzw9aIxPT4xoPT1ojE9quotRUYu6amq6i1EVJzgjAilbM4xPT4xoPT1ojE9PjGg9gFGLumpquotRUYu6ajVlXFEiAAAAAAIA+v+6Aw0BxgANABsAAAUiJjURNDYzMhYVERQGNyEiJjU0NjMhMhYVFAYCAA4YFRERFRjS/kAOGBURAcYPGBpGFREBwA4YFRH+Og8R4BURERUVEREVAAAFAQD/DAMAAnsAHAA6AEkAVwB+AAABLgEjIgYHDgEVERQWFx4BMzoBMTI2Nz4BNRE0JhMUBgcOASMiJicuATURNDY3PgEzOgExMhYXHgEVEScjIgYVFBY7ATI2NTQmIxUjIiY1NDY7ATIWFRQGExEUBiMhIiY1NDYzITI2NRE0JiMhIgYVERQGIyImNRE0NjMhMhYVAqsngAQEgCcqKysqJHMQAgIEgCcqKysVHyIngQEBgSciHx8iI3YNAgEBgSciH79WERgYEVYRGBgRVggMDAhWCAwMlRMN/rAFBgYFAVAFBgYF/rAFBgYEBQYTDQFQDRMCdgQBAQQDLSj9SictBAMBAQMELScCtigt/PUfIAMEAQEEAyAfArYfIQMEAQEEAyEf/UorGBERGRkRERg+DAkIDAwICQwCnf3hDhIGBQQGBgUCHwQGBgT+fwQGBgQBgQ0SEg0AAAMAVf8VA6sCawAUAC4APwAAJRQOAiMiLgI1ND4CMzIeAhUFMzQ2NTQmIyIGFRQWNz4BMzIWFRQGBwYWMQcUFjsBMjY9ATQmKwEiBh0BA6tDdJxYWJx0Q0N0nFhYnHRD/iM+lFNKU040AQUwNigtgQgBAQ0VFAoUFhYUChQVwFicdENDdJxYWJx0Q0N0nFhoTzBdOEhVIh8LAiM8JiA7KmgHAnEUFBQUCRQWFhQJAAAAAwBV/xUDqwJrABQAKwA7AAAlFA4CIyIuAjU0PgIzMh4CFSUTHgE7ATI2NxM2JicuASsBIgYHDgEXEzQmKwEiBh0BFBY7ATI2NQOrQ3ScWFicdENDdJxYWJx0Q/4cGAEKEQkRCwIXAgQHBxMMFAwTBwcEAnQcGgsZHBwZCxocwFicdENDdJxYWJx0Q0N0nFjg/vQIGxkLAQoPFwcIBwcIBxcO/kQZHBwZChkcHBkAAAACARr/YQLmAh8AIQAyAAAlPgM1NCYjIgYHBiY1ND4CMzIWFRQOAgcOASMiJjcTMzI2PQE0JisBIgYdARQWMwGvATlENzQxQ0AFAVwcOVc7bHk8ST8CAx4XGiECMRAhJCMiECEhIx91QkAlICImK04rAxA2GzoxIGVSQD8sLi8ODRgY/uwhIA0iISIhDSAhAAACANL/hAMrAesAEQAjAAAXIiYnJjQ3ATYyFxYUBwEOASMhIiYnASY0NzYyFwEWFAcOASP3ChIJDg4CDw8qEQ8P/fEIEgsCDwsSCP3xDg4PKhECDw8PCRIKfAgGDyoRAg8PDw8qEf30CAkIBgIPDyoRDw/98Q4qEgYIAAAAAgAA/sAEAALAABMAJwAAASIuAjU0PgIzMh4CFRQOAgMiDgIVFB4CMzI+AjU0LgICAGq6i1FRi7pqarqLUVGLumpfqH9KSn6pX1+of0pKfqn+wFGLumpquotRUYu6amq6i1ED0Ep+qV9fqH9KSn+oX1+of0oAAAAAAQDV/4oDLgHcABYAAAkBDgEjIiYvASY2Nz4BHwEBPgEXHgEHAy7+yQgcDw4ZCb8LAw0NJg2jASILJhAQCAoBnP4MDhANC/AOJgwMAQySAZAPBwsKJhAAAAMAaP9SA5kCLgAuAEUAVQAABRQGBw4BIyEiJicuATU0MDE8ATE0NjU+ATcBPgEzMTIWFwEeARcUFhUwFhU4ARUBFx4BOwEyNj8BNiYnLgErASIGBw4BFxM0JisBIgYdARQWOwEyNjUDmRANDiUU/ZcVJQ4NDwECCAYBNQ4rGRkrDgE1BggCAQH+PRIBBwwHDQcCEQIEBQQOCQ8JDgUFBAJWFRMIExQUEwgTFVwRIQsLCgoLCyERAQEBBAgEChUKAhcZHh4Z/ekKFQoECAQBAQEBkcUGFBMIxAoRBgUGBgUGEAv+uRMVFRMHExQUEwAAAAEAav+DA6EB/QBIAAABIS4BJy4BKwEiBhUUFjsBEhY5AR4BFw4BFRQWMzI2NTQmJzMUBhUUFjMyNjU0JicmIisBIiYnITgBMzgBMTI2PwI0NjU0JiMDcf3hBQkEAg8KnwsREQuIPhcJJR4DBCodHSoBAYwBKR4dKiYaAgQB/zQsCQGTAREaBD4BAR0TAZoVJxEJDREMCxH+7mQmMw0HDwgdKiodBAcDAwcEHSoqHRwoAgEhHRQQ6QUCBAIUHQAAAAQAXf9zA6QB5wAuAGsAkwCuAAAlMCIxISImNTQ2MzEFMDI5ATI2PwEwNDU0JiMhIiY1NDYzMSEyFhUcARUPAQ4BIxcUBiMiJjU8ATcjHAEVFAYjIiY1NDY3LgEnMCYDIyImNTQ2OwEyFhcUHgIVHgEXPgEzMhYXMz4BMzIWFSUxLgEnOAExLgEnLgEjIgYHMQ4BBzgBMQ4BBzEOARUUFjMyNjU0JjUFNCYjIgYHMQ4BBzgBMQ4BBzEUBhUUFjMyNjUDNgH+bwQHBwQBkQEKDgI/EAv96wQGBgQCFRQcAT4EGhElMCEiMAGYMCEiMAYGExoIF0GWBAYGBJ4EBgEcIhwHFhALHREZKQmjCigZIjD+sAEBAQEDAQgbEAsUCAIEAgEDAgMFJBkZIwEBOyQYERoIAgMBAQEBASQZGCRLBwQFBgELCe0DAQsQBwQEBx0UAgQCBekQFIchMDAhAwUDAwUDITAwIQwVCRAwIGUBHwYFBAYEBAJ6k3sCHSkOCwwcFhYcMCILAwUDAwUCDRAIBwIDAgMEAgcPCBgkJBgDBQMLGSQQDQIFAwMFAwMFAxgkJBgAAAABADP/MQPNAlUANQAAJTQmIyE1NC4CIyIOAh0BOAExFBYzMjY1OAE5ATU0NjMyFh0BIyIGFTERMRQWMyEyNjUxEQPNIBb+eiZBVzEyV0ElHRUUHVI6OVILFyAgFwH0FyChFh+YMFQ/JCQ/VDAdFR0dFR03TU03mB8W/sQWHh4WATwAAAAEAF//SgOhAjYADQAbAG4AgAAABSEiJjU0NjMhMhYVFAYnISImNTQ2MyEyFhUUBjc0JiMhNTQuAiMiDgIdARQWFx4BMzI2PQE0NjMyFh0BFBYzMjY9ATQmIyIGHQEUBiMiJicuAT0BND4CMzIeAh0BIyIGBxEeATMhMjY3MxEDFAYjISImNRE0NjMhMhYVERUDMf7HBQYGBQE5BAcHBP7HBQYGBQE5BAcHbCIX/rQjPFEuLlI8IwgIBxIKEyBHMjJHBgQFBlM7O1QVCAYLBAQFIDdJKilKNiBHFyEBASEXAagVHwQBFRUP/lgOFRUOAagPFT8GBQQGBgQFBnYHBAQHBwQEB1YWIZwsTjoiIjpOLEILEwcFBxkYQjBFRTBCBAYGBEI5UVE5QhALAwQDCwZCKEY0Hx80RiicIRf+9RcgGhIBF/70DhQUDgELDhQUDv79CAAAAgDP/zEDMQJVACAAKgAAJTQmKwE1NC4CIyIOAh0BIyIGFTERMRQWMyEyNjUxESU0NjMyFh0BITUDMSAXCyVBVzIxV0EmCxcgIBcB9Bcg/kRSOTpS/umhFh+YMFQ/JCQ/VDCYHxb+xBYeHhYBPM03TU03mJgAAAAABQDN/xQDMwJsAB8ARABdAGsAeQAAJTQmJzU0LgIjIg4CHQEOAQcjERUzHgEzITI2NzMRATIeAh0BIzU0JiMiBh0BFBYzMjY9ATQ2MzIWHQEhNTQ+AjMBFAYjISImJzURNT4BMyE4ATkBMzIWFRMHJyEiJjU0NjMhMhYVFAYnISImNTQ2MyEyFhUUBgMzIBcoRFw0NFxEKBQeBAEBBCQXAeYXJAQB/s0wVD4lRl5DQl4GBQQGUjk6Uf6PJD9ULwEdGRH+GhIYAQEZEQGJXREZAQFp/pkFBgYFAWcEBgYE/pkFBgYFAWcEBgaFFyIDuTJYQiYmQlgyuQIcFP7DCxUeHhUBPgHRIjxQLri4QFxcQEoFBgYFSjhOTji4uC5QPCL8/BEXFxEDASwDERgYEf7ZC0sGBAUGBgUEBocHBAQHBwQEBwAADQB2/1QDhQJQACIAMgBCAEkAWQBpAHkAiQCZAKAAsADAANAAAAEjNTQmIw4BHQEhNTQmIw4BHQEjIgYVERQWMyEyNjURNCYjARQGKwEiJj0BNDY7ATIWFTUUBisBIiY9ATQ2OwEyFhUnLgE1MxQGExQGKwEiJj0BNDY7ATIWFTUUBisBIiY9ATQ2OwEyFhUTFAYrASImPQE0NjsBMhYVNRQGKwEiJj0BNDY7ATIWFTUUBisBIiY9ATQ2OwEyFhU3MxQGJy4BExQGKwEiJj0BNDY7ATIWFTUUBisBIiY9ATQ2OwEyFhU1FAYrASImPQE0NjsBMhYVA2ZhGRERFv6TGRERFmENEhINAtENEhIN/c8GBXEEBgYEcQUGBgVxBAYGBHEFBhgRFlEZuQYEcQUGBgVxBAYGBHEFBgYFcQQGsgYEcQQGBgRxBAYGBHEEBgYEcQQGBgRxBAYGBHEEBhtRGRERFpgGBHIEBgYEcgQGBgRyBAYGBHIEBgYEcgQGBgRyBAYB/ikRGAEaESYpERgBGhEmEg39lA0SEg0CbA0S/ZoFBgYFbAUGBgVCBAYGBG0EBgYE+gEXERIY/ewFBgYFbAUGBgVCBAYGBG0EBgYE/uUFBgYFbAUGBgVCBAYGBG0EBgYEQQQGBgRtBAYGBHUSGAEBF/3TBQYGBWwFBgYFQgQGBgRtBAYGBEEEBgYEbQQGBgQAAA8Abv9mA5ICdwApAC4AMgA2ADoAPgBCAFAAXgCEAIkAkQCVAJkAoQAAJTgBNRE0JisBNTQmIyIGHQEhNTQmIyIGHQEjIgYVERQWMyEyNjUROAE1BTMVIzU7ARUjJSM1MwcjNTMXMxUjNzMVIwM0NjMyFh0BFAYjIiY1JTQ2MzIWHQEUBiMiJjUnNDY7ARUUFjMyNj0BIRUUFjMyNj0BMzIWFREjNTMyNjU0JiMhNRcVIzUzAyImPQEzFSMzNTMVMzUzFTMjNTMVFAYjA5IeFkweFRUf/qkeFRUeTBYeHhYCvBYe/PGyssirqwFwr6/Fq6sWr6/Fq6sQEQ0MEhIMDRH+QhIMDBISDAwSgBINTB4VFR4BVx8VFR5MDRGsMAQHBwT9g7KyspMNErKTqasWr6ONqxENwQEBMRUfHBYeHhYcHBYeHhYcHxX9phUeHhUBJwELlpaWq6KioreWlpYCIw0REQ1RDBISDFENERENUQwSEgwBDBIfFR4eFR8fFR4eFR8SDP7YogYFBAZxhqKi/g4SDHKQkJCQkJByDBIAAAAAAQC6/3kDSAIHAB8AACUUBisBFRQGIyImPQEjIiY1NDY7ATU0NjMyFh0BMzIWA0gpHrkpHh0quR0qKh25Kh0eKbkeKcAdKrkdKioduSodHSq5HSoqHbkqAAEAuQB5A0cBBwANAAAlISImNTQ2MyEyFhUUBgMA/gAdKiodAgAdKip5Kh0dKiodHSoAAAAGAGn/ZAOdAhYADQAbADoARwBWAGcAAAE0JisBIgYVFBY7AT4BFzQmIyEiBhUUFjMhPgEXIzU0Ji8BLgEjISIGFREjIgYdARQWMyEyNj0BLgEjATQ2MyEVFBY7ARUhEQMiJjU0NjsBMhYVFAYrAQUUBiMhIiY9ATQ2MyEyFh0BAiYMC6oJDgwLqgsMig0L/tAJDw0LATAJD6w9CAdsBxMJ/oYRGDoYIyMYAr4YIwMkGv26CAcBRwgEb/4vWwkODAtbCQ4MC1sCLAgG/k4GCAgGAa8GCAFKCA8NCgsNAg1PCQ4MCwsNAwxD0gkUBm0GCBcS/rYjG8cYIiIYxx0kASoHCG8FB8EBLf5sDQsJDgwLCQ+ABwgIBxEHCAgHEQAAAAAIAGP/XgOfAh8AEAAhAC8APQBLAFkAhACHAAAFISImPQE0NjMhMhYdAQ4BIwEiBh0BFBYzITI2PQE0JiMhFzQmKwEiBhUUFjsBMjYFNCYjISIGFRQWMyEyNgM0JiMhIgYVFBYzITI2JzQmKwEiBhUUFjsBMjYlJy4BIyEiBhURFBYzMjY1ETQ2MyEyFhcVFBY7ARQWHQEUFjMyNj0BLgEnJxcjA1z9SBonJxoCuxomAica/UgSFxcSArsSFxcS/UWeBwWBBAcHBIEFBwGOCAT+eAQICAQBiAQIGAcE/qMEBwcEAV0GBbUHBacEBwcEpwUHAQRsCRgL/q0WHwcFBAgTDQFTAgUCBwV9AwgEBAgFCgl4Z2eiJhrHGyYmG8caJgEzFxLHERgYEccSFzcEBwcEBQcHjgUHBwUEBwcBSQQICAQECAhQBQcHBQQIBk9tCAkfFv7/BAgIBAEBDhABAn4ECAIEA4kECAgEiQ4bBltmAAIAWP8VA60CawAUACsAAAEiDgIVFB4CMzI+AjU0LgIjFwEOASMiJi8BJjY3NjIfARM+ARceAQcCAlibdENDdJtYWZt0Q0N0m1nz/v4IFg0MFAifCQILCx8Mh/IJIA0NBwkCa0N0nFhYnHRDQ3ScWFicdEP1/l8LDQoJyAwfCwoKegFODAYJCCANAAAAAwBV/xUDqwJrABQAIQAuAAAlFA4CIyIuAjU0PgIzMh4CFQUyNiMuATcTIwMGFjMTMjY1NCYjIgYVFBYzA6tDdJxYWJx0Q0N0nFhYnHRD/j4hDAEYDAY3RTgJGyY5FRcVFBUXFRTAWJx0Q0N0nFhYnHRDQ3ScWPohAhYbAQb++ygtAaMbEw8RGxMOEgABAHb/QQOKAi4AKAAAATYyHwEeAR8BHgEPAQ4BHwEWBi8BJiIPAQYmPwE2Ji8BJjY/AT4BPwEB5QsgC1ELNBm1GQoSgxIUBB8FGhehF0AWohcZBB8EFBKDEgoZtRk0C1ECLhcXoxcmAxsDHxJ/Ej0ZtBkSC1UMDFULEhm0GT0SfxIfAxsDJhejAAAAAAEAmv/vA1cBfQAZAAATNDY3NjIfATc2MhcWFAcBDgEjIiYnAS4BNZoKChQ4FPT0FDkUFBT+7w0kExMjDv7wCgoBTA0ZChQU9PUUFBQ4FP7uDQ8PDQERChkNAAAAAQAAAAEAAJw5MTFfDzz1AAsEAAAAAADUFPWTAAAAANQU9ZMAAP7ABAACwAAAAAgAAgAAAAAAAAABAAACzP7NAAAEAAAAAAAEAAABAAAAAAAAAAAAAAAAAAAAKAQAAAAAAAAAAAAAAACuAAAEAAAJBAAA+gQAAAAEAABJBAAAqgQAAJwEAABjBAAAdQQAAQQEAAAABAAAAAQAAPoEAAEABAAAVQQAAFUEAAEaBAAA0gQAAAAEAADVBAAAaAQAAGoEAABdBAAAMwQAAF8EAADPBAAAzQQAAHYEAABuBAAAugQAALkEAABpBAAAYwQAAFgEAABVBAAAdgQAAJoAAAAAAAoAFAAeAQ4BKAFkAaoCBAKeAugDYgO6A/YEMgReBQoFYgW6BgIGQAZ8BqgHIAeACFoInAlGCYIKJAsuC/4MKgxEDNQNjA3SDhgOXg6MAAAAAQAAACgA0QAPAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABAAoAAAABAAAAAAACAAcAewABAAAAAAADAAoAPwABAAAAAAAEAAoAkAABAAAAAAAFAAsAHgABAAAAAAAGAAoAXQABAAAAAAAKABoArgADAAEECQABABQACgADAAEECQACAA4AggADAAEECQADABQASQADAAEECQAEABQAmgADAAEECQAFABYAKQADAAEECQAGABQAZwADAAEECQAKADQAyGljb1ByaW1hcnkAaQBjAG8AUAByAGkAbQBhAHIAeVZlcnNpb24gMS4wAFYAZQByAHMAaQBvAG4AIAAxAC4AMGljb1ByaW1hcnkAaQBjAG8AUAByAGkAbQBhAHIAeWljb1ByaW1hcnkAaQBjAG8AUAByAGkAbQBhAHIAeVJlZ3VsYXIAUgBlAGcAdQBsAGEAcmljb1ByaW1hcnkAaQBjAG8AUAByAGkAbQBhAHIAeUZvbnQgZ2VuZXJhdGVkIGJ5IEljb01vb24uAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") format("woff"), url("fonts/icons/icoPrimary.ttf?timestamp=@@timestamp") format("truetype"); + font-weight: normal; + font-style: normal; } + +[class*="icon-"], +.nav-links a:after, +.b2b-bellyband-link a:after, +.breadcrumb > li:after, +.checkbox input:checked + .skin:after, +.checkbox input.indeterminate + .skin:after, +.checkbox input:indeterminate + .skin:after, +.selectWrap.large:before, +.form-row.error .error-msg:before, +.close:before, +.reset-field:before, +.cssIcon-globe:before, +.selectWrap:after { + color: #0568ae; + display: inline-block; + font-family: 'icoPrimary' !important; + font-style: normal; + font-size: 20px; + font-weight: normal; + font-variant: normal; + height: 1em; + margin-right: 7px; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + position: relative; + speak: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + vertical-align: middle; + width: 1em; } + +[class*="icoWeather-"], [class*="icoTrans-"], [class*="icoBubble-"], [class*="icoRetail-"], [class*="icoPeople-"], [class*="icoNumslets-"], [class*="icoLocation-"], [class*="icoHealthcare-"], [class*="icoDocuments-"], [class*="icoDevices-"], [class*="icoDatanetwork-"], [class*="icoControls-"], [class*="icoBuilding-"], [class*="icoArrows-"] { + color: #0568ae; + display: inline-block; + font-style: normal; + font-size: 20px; + font-weight: normal; + font-variant: normal; + font-style: normal; + width: 20px; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + position: relative; + speak: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + vertical-align: middle; } + +[class*="icon-"]:before, +[class*="icon-"]:after { + box-sizing: border-box; + display: inline-block; + font-size: 1em; + height: 1em; + position: relative; + top: 0; + left: 0; + vertical-align: middle; + width: 1em; } + +.icon-att-globe:before, +.cssIcon-globe:before { + content: "\e900"; + color: #44c7f5; } + +.icon-hamburger:before { + content: "\e903"; } + +.icon-secure:before { + content: "\e918"; } + +.icon-secureL:before { + content: "\e919"; } + +.icon-padlockopen:before { + content: "\e916"; } + +.icon-padlockopenL:before { + content: "\e917"; } + +.icon-shoppingcart:before { + content: "\e914"; } + +.icon-shoppingcartL:before { + content: "\e915"; } + +.icon-print:before { + content: "\e921"; } + +.icon-printL:before { + content: "\e922"; } + +.icon-mobilesmartphone:before { + content: "\e908"; } + +.icon-mobilesmartphoneL:before { + content: "\e90c"; } + +.icon-tablet:before { + content: "\e904"; } + +.icon-tabletL:before { + content: "\e905"; } + +.icon-tv:before { + content: "\e906"; } + +.icon-tvL:before { + content: "\e907"; } + +.icon-calendar { + width: 100% !important; } + +.icon-calendar:before { + content: "\e91a"; + z-index: 1; } + +.icon-calendarL:before { + content: "\e91b"; } + +.icon-star:before { + content: "\e96c"; } + +.icon-close:before, +.close:before, +.reset-field:before { + content: "\e910"; } + +.icon-down:before { + content: "\ea3c"; } + +.checkbox input.indeterminate + .skin:after, +.icon-subtractminimize:before { + content: "\e920"; } + +.icon-add-maximize:before { + content: "\e91f"; } + +.icon-check:before, +.checkbox input:checked + .skin:after { + content: "\e912"; } + +.icon-questionmark:before { + content: "\e90f"; } + +.icon-badgealert:before, +.form-row.error .error-msg:before { + content: "\e90e"; } + +.icon-approval:before { + content: "\e925"; } + +.icon-flat-info:before { + content: "\e927"; } + +.icon-alert:before { + content: "\e913"; } + +.icon-tooltip:before, +.icon-flat-faq:before { + content: "\e90d"; } + +.icon-tooltip { + font-size: 20px; } + +.nav-links a:after, +.b2b-bellyband-link a:after, +.breadcrumb > li:after, +.icon-right:before { + content: "\ea3c"; + transform: rotate(-90deg); } + +.icon-left:before { + content: "\ea3c"; + transform: rotate(90deg); } + +.icon-accordion-plus:after, +.icon-collapsed:after, +.icon-accordion-minus:after, +.icon-expanded:after { + content: ""; + position: absolute; + top: 0; + z-index: 1; } + +.icon-accordion-minus, +.icon-expanded, +.icon-accordion-plus, +.icon-collapsed { + font-size: 20px !important; } + +:not(.ds2-no-colors) .icon-accordion-minus:before, +:not(.ds2-no-colors) .icon-expanded:before { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2021%2021%22%3E%3Cpath%20fill%3D%22%230568ae%22%20d%3D%22M15.1%2011.3H5.9c-.4%200-.8-.3-.8-.8s.3-.8.8-.8h9.3c.4%200%20.8.3.8.8s-.4.8-.9.8z%22%2F%3E%3Cpath%20fill%3D%22%23d2d2d2%22%20d%3D%22M10.5%2021C4.7%2021%200%2016.3%200%2010.5S4.7%200%2010.5%200%2021%204.7%2021%2010.5%2016.3%2021%2010.5%2021zm0-20C5.3%201%201%205.3%201%2010.5S5.3%2020%2010.5%2020s9.5-4.3%209.5-9.5S15.7%201%2010.5%201z%22%2F%3E%3C%2Fsvg%3E"); + content: ""; } + +:not(.ds2-no-colors) .icon-accordion-plus:before, +:not(.ds2-no-colors) .icon-collapsed:before { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2021%2021%22%3E%3Cpath%20fill%3D%22%230568ae%22%20d%3D%22M10.5%2015.9c-.4%200-.8-.3-.8-.8V5.9c0-.4.3-.8.8-.8s.8.3.8.8v9.3c0%20.4-.4.7-.8.7z%22%2F%3E%3Cpath%20fill%3D%22%230568ae%22%20d%3D%22M15.1%2011.3H5.9c-.4%200-.8-.3-.8-.8s.3-.8.8-.8h9.3c.4%200%20.8.3.8.8s-.4.8-.9.8z%22%2F%3E%3Cpath%20fill%3D%22%23d2d2d2%22%20d%3D%22M10.5%2021C4.7%2021%200%2016.3%200%2010.5S4.7%200%2010.5%200%2021%204.7%2021%2010.5%2016.3%2021%2010.5%2021zm0-20C5.3%201%201%205.3%201%2010.5S5.3%2020%2010.5%2020s9.5-4.3%209.5-9.5S15.7%201%2010.5%201z%22%2F%3E%3C%2Fsvg%3E"); + content: ""; } + +.ds2-no-colors .icon-accordion-minus:before, +.ds2-no-colors .icon-expanded:before { + background-image: none; + content: "\e901"; } + +.ds2-no-colors .icon-accordion-minus:after, +.ds2-no-colors .icon-expanded:after { + content: "\e902"; } + +.ds2-no-colors .icon-accordion-plus:before, +.ds2-no-colors .icon-collapsed:before { + background-image: none; + content: "\e90b"; } + +.ds2-no-colors .icon-accordion-plus:after, +.ds2-no-colors .icon-collapsed:after { + content: "\e911"; } + +.icon-circle-arrow { + outline: 1px solid transparent; + border-radius: 50%; + font-size: 20px !important; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08); + margin-right: 7px; } + +.icon-circle-arrow:after { + background-image: url("data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2036%2036%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20baseProfile%3D%22tiny%22%3E%3Ccircle%20r%3D%2217%22%20cy%3D%2218%22%20cx%3D%2218%22%20stroke-width%3D%221%22%20fill%3D%22transparent%22%20stroke%3D%22%23ccc%22%2F%3E%3C%2Fsvg%3E"); + content: ""; + position: absolute; + top: 0; + z-index: 2; } + +.icon-circle-arrow:before { + border-radius: 50%; + content: "\ea3c"; + font-size: 12px; + top: 0; + position: absolute; + transform: rotate(-90deg); + width: 20px; + z-index: 1; } + +[class*="icon-"] [class*="icon-"] { + display: inline-block; + float: left; + font-size: 1em; + margin-left: -1em; + position: absolute; } + +[class*="icon-"].white, [class^="ico"][class*="-"].white { + color: #fff; } + +[class*="icon-"].black, [class^="ico"][class*="-"].black { + color: #000; } + +[class*="icon-"].blue, [class^="ico"][class*="-"].blue { + color: #0568ae; } + +[class*="icon-"].green, [class^="ico"][class*="-"].green { + color: #007a3e; } + +@-webkit-viewport { + width: device-width; } + +@-moz-viewport { + width: device-width; } + +@-ms-viewport { + width: device-width; } + +@-o-viewport { + width: device-width; } + +@viewport { + width: device-width; } + +.clearfix:before, +.clearfix:after { + display: table; + content: ""; + line-height: 0; } + +.clearfix:after { + clear: both; } + +.pull-right { + float: right !important; } + +.pull-left { + float: left !important; } + +.float-children-left:before, +.float-children-left:after { + display: table; + content: ""; + line-height: 0; } + +.float-children-left:after { + clear: both; } + +.float-children-left > div { + float: left; + white-space: nowrap; } + +.block { + display: block !important; } + +.inline { + display: inline !important; } + +.inline-block { + display: inline-block !important; } + +.table-cell { + display: table-cell !important; + width: 1%; + vertical-align: middle; } + +@media (max-width: 767px) { + .full-bleed { + width: auto; + margin-left: -15px; + margin-right: -15px; + padding: 15px; } } + +@media (min-width: 768px) { + .full-bleed { + width: auto; + margin-left: -20px; + margin-right: -20px; + padding: 20px; } } + +@media (max-width: 480px) { + .full-bleed { + width: auto; + margin-left: -15px; + margin-right: -15px; + padding: 0 15px; } } + +.fade { + opacity: 0; + filter: alpha(opacity=0); + transition: opacity .15s linear; } + +.fade.in { + opacity: 1; + filter: alpha(opacity=100); } + +.b2bCollapse { + display: none; } + +.collapse.in { + height: auto; } + +.nowrap { + white-space: nowrap; } + +.pre { + white-space: pre; } + +.hidden-spoken { + border: 0 none !important; + clip: rect(0px, 0px, 0px, 0px) !important; + height: 1px !important; + letter-spacing: 0; + line-height: 0; + overflow: hidden !important; + margin-top: -1px; + padding: 0 !important; + position: absolute !important; + width: 1px !important; } + +[data-sr-text].hidden-spoken:before { + border: 0 none !important; + content: attr(data-sr-text); + clip: rect(0px, 0px, 0px, 0px) !important; + height: 1px !important; + letter-spacing: 0; + line-height: 0; + overflow: hidden !important; + padding: 0 !important; + position: absolute !important; + width: 100% !important; + z-index: -1; } + +[data-sr-text].hidden-spoken { + position: relative !important; + width: auto !important; } + +[data-show-between] { + display: none; + visibility: hidden; } + +.noscroll-y { + overflow-y: hidden !important; } + +.invisible { + visibility: hidden !important; + opacity: 0 !important; } + +.transparent { + background-color: rgba(255, 255, 255, 0) !important; } + +.hide { + display: none !important; } + +.show { + display: block !important; } + +.rel { + position: relative !important; } + +.legend-pad { + padding: 0 15px; } + +.border-top { + border-top-width: 1px !important; } + +.border-left { + border-left-width: 1px !important; } + +.border-right { + border-right-width: 1px !important; } + +.border-bottom { + border-bottom-width: 1px !important; } + +.border-dark { + border-color: #000; } + +.border-light { + border-color: #fff; } + +.no-border-top { + border-top-width: 0 !important; } + +.no-border-left { + border-left-width: 0 !important; } + +.no-border-right { + border-right-width: 0 !important; } + +.no-border-bottom { + border-bottom-width: 0 !important; } + +.align-middle { + margin: 0 auto !important; } + +.align-top { + position: absolute; + top: 0; } + +.align-bottom { + position: absolute; + bottom: 0; } + +.valign-top { + vertical-align: top !important; } + +.valign-middle { + vertical-align: middle !important; } + +.valign-bottom { + vertical-align: bottom !important; } + +.align-children-middle > * { + margin: 0 auto; } + +[class*="valign-children-"] { + display: table; } + +[class*="valign-children-"] > * { + display: table-cell; } + +.valign-children-top > * { + vertical-align: top; } + +.valign-children-middle > * { + vertical-align: middle; } + +.valign-children-bottom > * { + vertical-align: bottom; } + +.no-pad { + padding: 0 !important; } + +.top-space { + margin-top: 60px !important; } + +.bottom-space { + margin-bottom: 60px !important; } + +.top-pad { + padding-top: 60px !important; } + +.bottom-pad { + padding-bottom: 60px !important; } + +@media (max-width: 767px) { + .top-space { + margin-top: 30px !important; } + .bottom-space { + margin-bottom: 30px !important; } + .top-pad { + padding-top: 30px !important; } + .bottom-pad { + padding-bottom: 30px !important; } } + +.affix { + position: fixed; } + +.img-landscape, +.img-portrait { + position: relative; } + +@media (orientation: landscape) { + .img-landscape { + display: block; } + .img-portrait { + display: none !important; } } + +@media (orientation: portrait) { + .img-landscape { + display: none !important; } + .img-portrait { + display: block; } } + +.dark-bg { + background-color: #222222; } + +/* ... JAVASCRIPT HOOKS ................. + ... used by javascript ............... */ +.autoSize, +.autoSize-this { + position: relative; } + +.truncate { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } + +.placeholdersjs { + color: #5a5a5a !important; } + +.jshook-return-focus-here { + display: block; } + +.visible-print { + display: none !important; } + +.hidden-print { + display: inherit !important; } + +@media print { + .visible-print { + display: inherit !important; } + .hidden-print { + display: none !important; } + * { + color: #000 !important; + background: transparent !important; + box-shadow: none !important; } + a, + a:visited { + text-decoration: underline; } + pre, + blockquote { + border: 1px solid #000; + page-break-inside: avoid; } + thead { + display: table-header-group; } + tr, + img { + page-break-inside: avoid; } + img { + max-width: 100% !important; } + @page { + margin: 0.5cm; } + p, + h2, + h3 { + orphans: 3; + widows: 3; } + h2, + h3 { + page-break-after: avoid; } } + +.mar-top-0 { + margin-top: 0px; } + +.mar-top-30 { + margin-top: 30px; } + +a:focus { + outline: thin dotted #191919; } + +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: normal; + text-rendering: optimizeLegibility; + margin: 0; + line-height: 1; } + +.heading-page { + font-size: 3.8rem !important; + font-family: "Omnes-ATT-W02-Light"; + margin-bottom: 40px; } + +.heading-major-section { + font-size: 3rem !important; + font-family: "Omnes-ATT-W02-Light"; + margin-bottom: 40px !important; } + +.heading-sub-section { + font-size: 2.4rem !important; + font-family: "Omnes-ATT-W02"; + margin-bottom: 40px; } + +.heading-group { + font-size: 2rem !important; + font-family: "Omnes-ATT-W02-Medium"; + color: #ea7400; + margin-bottom: 20px !important; } + +.heading-medium { + font-size: 2rem !important; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + +.heading-medium-emphasis { + font-size: 2rem !important; + font-family: "Omnes-ATT-W02-Medium"; + margin-bottom: 20px; } + +.heading-small { + font-size: 1.8rem !important; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + +.heading-small-emphasis { + font-size: 1.8rem !important; + font-family: "Omnes-ATT-W02-Medium"; + margin-bottom: 20px; } + +.heading-micro { + font-size: 1.3rem !important; + font-family: "Omnes-ATT-W02-Medium"; + text-transform: uppercase; + color: #da0081; + margin-bottom: 10px; } + +* + .heading-major-section { + margin-top: 60px; } + +* + .heading-sub-section { + margin-top: 60px; } + +* + .heading-group { + margin-top: 40px !important; } + +* + .heading-medium { + margin-top: 40px; } + +* + .heading-medium-emphasis { + margin-top: 40px; } + +* + .heading-small { + margin-top: 40px; } + +* + .heading-small-emphasis { + margin-top: 40px; } + +* + .heading-micro { + margin-top: 20px; } + +.lead { + color: #666; + font-family: "Omnes-ATT-W02-Light-Italic"; + font-size: 2.4rem; + line-height: 2.8rem; + margin-top: 10px; + letter-spacing: -0.024rem; } + +.eyebrow { + text-transform: uppercase; + line-height: .65 !important; } + +.eyebrow, +.subheading { + font-size: 1.4rem !important; + font-family: "Omnes-ATT-W02-Medium"; + color: #666; } + +.eyebrow + .heading-major-section, +.eyebrow + .heading-sub-section { + margin-top: 4px; } + +.subheading { + margin-top: 10px; } + +@media (max-width: 767px) { + h1, + h2, + h3, + h4, + h5, + h6, + .heading-page { + font-size: 2rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 30px; } + .heading-major-section { + font-size: 2rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 30px; } + .heading-sub-section { + font-size: 2rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + .heading-medium { + font-size: 2rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + .heading-medium-emphasis { + font-size: 2rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + .heading-small { + font-size: 1.6rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 10px; } + .heading-small-emphasis { + font-size: 1.6rem; + font-family: "Omnes-ATT-W02-Medium"; + margin-bottom: 5px; } + * + .heading-major-section { + margin-top: 30px; } + * + .heading-sub-section { + margin-top: 30px; } + * + .heading-group { + margin-top: 20px; } + * + .heading-medium { + margin-top: 20px; } + * + .heading-medium-emphasis { + margin-top: 20px; } + * + .heading-small { + margin-top: 20px; } + * + .heading-small-emphasis { + margin-top: 20px; } + * + .heading-micro { + margin-top: 10px; } } + +/* Standard Type styles */ +.zeromargin { + margin: 0 !important; } + +a { + color: #0568ae; + text-decoration: none; } + +a:hover, +a:focus { + text-decoration: underline; } + +a:active { + color: #0568ae; } + +.a-min { + font-size: 12px; } + +.a-small { + font-size: 14px; } + +.a-max { + font-size: 18px; } + +a.show-qualifier { + margin-right: 25px; + position: relative; } + +a.show-qualifier:after { + color: #333333; + display: inline-block; + white-space: pre !important; } + +a[href$="pdf"].show-qualifier:after, +a.show-qualifier.pdf:after { + content: " (PDF)"; } + +a[href$="psd"].show-qualifier:after, +a.show-qualifier.psd:after { + content: " (PSD)"; } + +.standalone-link { + display: flex; } + +/* 20px for the icon, 10px left of icon */ +.standalone-link.small { + font-size: 1.4rem; } + +.standalone-link.small i[class*="icon-"] { + font-size: 16px; + top: 2px; } + +.standalone-link.large { + font-size: 1.8rem; } + +.standalone-link.large i[class*="icon-"] { + font-size: 24px; + top: -1px; } + +p { + margin: 0 0 12px 0; + line-height: 2rem; } + +.p-small { + font-size: 1.4rem; + line-height: 1.8rem; } + +p + .p-small { + margin: 10px 0 0; } + +.p-micro { + font-size: 1.2rem; + line-height: 1.5rem; } + +p + .p-micro { + margin: 10px 0 0; } + +.p-max { + font-size: 1.8rem; } + +p + .p-max { + margin: 10px 0 0; } + +b, +strong { + font-family: "Omnes-ATT-W02-Medium"; + font-weight: normal; } + +i, +em { + font-family: "Omnes-ATT-W02-Italic"; + font-style: normal; } + +.strike { + text-decoration: line-through; } + +sup { + display: inline-block; + font-style: normal; + height: 1em; + position: relative; + vertical-align: text-top; + width: auto; } + +.text-legal { + color: #5a5a5a; + font-size: 1.1rem; + line-height: 1.5rem; + margin: 0 0 10px; } + +.text-legal.legal-module { + line-height: 1.3rem; + margin: 0 0 12px; } + +.text-legal b, +.text-legal strong { + font-weight: bold; } + +.text-legal a { + font-family: "Omnes-ATT-W02-Medium"; } + +.text-left { + text-align: left !important; } + +.text-right { + text-align: right !important; } + +.text-center { + text-align: center !important; } + +.text-justified { + text-align: justify !important; } + +ul { + padding: 0; + margin: 0; + list-style: none; } + +ul.bullet, +ul.no-bullet, +ul.lower-alpha, +ul.lower-roman, +ol { + padding: 0; + margin: 12px 0 0 20px; } + +ul.bullet li, +ul.no-bullet li, +ul.lower-alpha li, +ul.lower-roman li, +ol li { + padding-left: 15px; + line-height: 20px; + position: relative; } + +ul.bullet li + li, +ul.no-bullet li + li, +ul.lower-alpha li + li, +ul.lower-roman li + li, +ol li + li { + margin-top: 12px; } + +ul.bullet > li:before, +ul.no-bullet > li:before, +ul.lower-alpha > li:before, +ul.lower-roman > li:before, +ol > li:before { + background-color: #333333; + border: 2px solid #333333; + border-radius: 100%; + content: " "; + display: block; + height: 1px; + left: 0; + position: absolute; + top: 8px; + width: 1px; } + +ul.bullet ul, +ul.no-bullet ul, +ul.lower-alpha ul, +ul.lower-roman ul, +ol ul, +ul.bullet ol, +ul.no-bullet ol, +ul.lower-alpha ol, +ul.lower-roman ol, +ol ol { + margin-top: 12px; } + +ul + *, +ol + * { + margin-top: 20px; } + +ul.no-bullet, +ul.lower-alpha, +ul.lower-roman { + margin: 0; } + +ul.no-bullet > li, +ul.lower-alpha > li, +ul.lower-roman > li { + padding-left: 0; } + +ul.no-bullet > li:before, +ul.lower-alpha > li:before, +ul.lower-roman > li:before { + display: none !important; } + +ol { + margin: 20px 0 0 32px; } + +ol li { + padding-left: 3px; } + +ol li:before { + display: none; } + +ol ol { + margin-left: 25px; } + +ol ul { + margin-left: -5px; } + +ul ul, +ul ol, +ol ol, +ol ul { + margin-top: 0; } + +ul.lower-roman { + list-style-type: lower-roman; + margin-top: 12px; + margin-left: 35px; + margin-bottom: 0; } + +ul.lower-alpha { + list-style-type: lower-alpha; + margin-top: 12px; + margin-left: 35px; + margin-bottom: 0; } + +dl { + display: table; + margin: 0 0 20px; + width: 100%; } + +dt, +dd { + display: table-cell; } + +.btn { + background-color: transparent; + background-clip: padding-box; + border: 1px solid transparent; + border-radius: 8px; + box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15); + cursor: pointer; + display: inline-block; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 1.9rem; + font-weight: normal; + line-height: 1; + margin: 0 7px 10px 0; + max-width: 470px; + min-width: 70px; + padding: 14px 19px 11px 18px; + position: relative; + text-align: center; + vertical-align: middle; + white-space: nowrap; + overflow: hidden; } + .btn:focus { + outline: 1px dotted #000; + outline-offset: -5px; } + .btn:last-child { + margin-right: 0; } + .btn::-moz-focus-inner { + padding: 0; + border: 0; } + .btn i[class*="icon-"].icon-small { + font-size: 24px; + top: -2px; } + .btn i[class*="icon-"].icon-medium { + font-size: 30px; + top: -2px; } + .btn i[class*="icon-"].icon-large { + font-size: 36px; + top: -2px; } + +a.btn { + vertical-align: middle; } + a.btn:hover { + text-decoration: none; } + +.field-group + .btn { + margin-left: 20px; } + +.btn-primary { + border-color: #ea7400 transparent #d16500; + background-color: #ea7400 transparent #d16500; + background: linear-gradient(to bottom, #ea7400 0%, #d16500 100%); + color: #ffffff; + font-family: "Omnes-ATT-W02"; + font-weight: bold; } + .btn-primary:hover { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + .btn-primary:focus { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + .btn-primary:active { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + +.btn-arrow { + font-family: "Omnes-ATT-W02"; + font-size: 1.6rem; + font-weight: normal; + background-color: transparent; + border: none; + padding: 5px 0 0; + top: -4px; + color: #333333; + position: relative; } + .btn-arrow:hover { + text-decoration: underline; } + .btn-arrow:hover .btn-primary { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + .btn-arrow:hover .btn-secondary { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + .btn-arrow:hover .btn-alt { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); } + .btn-arrow:hover .btn-specialty { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + .btn-arrow:focus { + text-decoration: underline; + outline: 1px dotted #666; } + .btn-arrow:focus .btn-primary { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + .btn-arrow:focus .btn-secondary { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + .btn-arrow:focus .btn-alt { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); } + .btn-arrow:focus .btn-specialty { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + .btn-arrow:active .btn-primary { + text-decoration: none; + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #d16500 0%, #ea7400 100%); } + .btn-arrow:active .btn-secondary { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + .btn-arrow:active .btn-alt { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); } + .btn-arrow:active .btn-specialty { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + .btn-arrow .btn-alt { + border-color: #087ac2 transparent #0568ae; + background-color: #0568ae; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); + color: #ffffff; } + .btn-arrow .btn-alt:hover { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + .btn-arrow .btn-alt:focus { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + .btn-arrow .btn-alt:active { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + .btn-arrow::-moz-focus-inner { + padding: 0; + border: 0; } + .btn-arrow .btn { + border: 1px solid transparent; + border-radius: 100%; + height: 36px; + margin-bottom: 0; + margin-right: 7px; + max-width: 36px; + min-width: 20px; + padding: 0; + margin-top: -4px; + vertical-align: middle; + width: 36px; } + .btn-arrow .btn .icon-left { + bottom: 0; + display: block; + height: 100%; + left: 0; + line-height: 0; + position: absolute; + right: 0; + text-indent: 0; + top: 0; } + .btn-arrow .btn .icon-left:before { + position: absolute; + font-size: 1.6rem; + left: 1px; + top: 9px; } + .btn-arrow .btn .icon-right { + bottom: 0; + display: block; + height: 100%; + left: 0; + line-height: 0; + position: absolute; + right: 0; + text-indent: 0; + top: 0; + color: #ffffff; } + .btn-arrow .btn .icon-right:before { + position: absolute; + font-size: 1.6rem; + left: 17px; + top: 9px; } + .btn-arrow .btn.btn-primary .icon-left { + color: #fff; } + .btn-arrow .btn.btn-primary .icon-right { + color: #fff; } + .btn-arrow .btn.btn-alt .icon-left { + color: #fff; } + .btn-arrow .btn.btn-alt .icon-right { + color: #fff; } + .btn-arrow .btn.btn-secondary { + border: 1px solid #d2d2d2; } + .btn-arrow .btn.btn-secondary .icon-left { + color: #0568ae; } + .btn-arrow .btn.btn-secondary .icon-right { + color: #0568ae; } + .btn-arrow .btn.btn-small { + height: 20px; + max-width: 20px; + min-width: 20px; + width: 20px; + top: -1px; } + .btn-arrow .btn.btn-small .icon-left:before { + font-size: 10px; + top: 4px; + left: 0; } + .btn-arrow .btn.btn-small .icon-right:before { + font-size: 10px; + top: 4px; + left: 10px; } + .btn-arrow .btn.btn-large .icon-left:before { + font-size: 112%; + top: 12px; + left: 23px; } + .btn-arrow .btn.btn-large .icon-right:before { + font-size: 112%; + top: 12px; + left: 23px; } + +.btn-secondary { + border: 1px solid #d2d2d2; + background-color: #f2f2f2; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + color: #0568ae; + box-shadow: 0 5px 5px -5px rgba(0, 0, 0, 0.15); + padding: 14px 18px 11px 17px; } + .btn-secondary:hover { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + .btn-secondary:focus { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + .btn-secondary:active { + color: #0568ae; + outline-color: #000000 !important; + background: linear-gradient(to bottom, #f2f2f2 0%, #fcfcfc 100%); } + +.btn-alt { + border-color: #087ac2 transparent #0568ae; + background-color: #0568ae; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); + color: #ffffff; } + .btn-alt:hover { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + .btn-alt:focus { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + .btn-alt:active { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #0568ae 0%, #087ac2 100%); } + +.btn-specialty { + border-color: #008744 transparent #007a3e; + background-color: #007a3e; + background: linear-gradient(to bottom, #008744 0%, #007a3e 100%); + color: #ffffff; } + .btn-specialty:hover { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + .btn-specialty:focus { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + .btn-specialty:active { + color: #ffffff; + outline-color: #ffffff !important; + background: linear-gradient(to bottom, #007a3e 0%, #008744 100%); } + +.btn-clear { + background: transparent !important; + border-color: transparent !important; + font-weight: normal; + font-family: "Omnes-ATT-W02"; + box-shadow: none; + text-decoration: none; + color: #0568ae; } + .btn-clear:focus { + text-decoration: underline; } + .btn-clear:hover { + text-decoration: underline; } + +.isIE .btn:focus { + outline: none !important; + text-decoration: none !important; } + .isIE .btn:focus:after { + display: block; + content: ""; + position: absolute; + top: 4px; + left: 4px; + right: 4px; + bottom: 4px; + border: 1px dotted #000; } + +.isIE .btn:active { + outline: none !important; + text-decoration: none !important; } + .isIE .btn:active:after { + display: block; + content: ""; + position: absolute; + top: 4px; + left: 4px; + right: 4px; + bottom: 4px; + border: 1px dotted #000; } + +.isIE .btn.active { + outline: none !important; + text-decoration: none !important; } + .isIE .btn.active:not(:focus):after { + border: 1px solid #000; } + .isIE .btn.active:after { + display: block; + content: ""; + position: absolute; + top: 4px; + left: 4px; + right: 4px; + bottom: 4px; + border: 1px dotted #000; } + +.isIE .btn.btn-primary:focus:after { + border: 2px dashed #fff; } + +.isIE .btn.btn-secondary:focus:after { + border: 2px dashed #fff; } + +.isIE .btn.btn-secondary.active:not(:focus):after { + border: none; } + +.isIE .btn.btn-secondary.active:after { + display: block; + content: ""; + position: absolute; + top: 4px; + left: 4px; + right: 4px; + bottom: 4px; + border: 1px dotted #fff; } + +.isIE .btn.btn-specialty:focus:after { + border: 2px dashed #fff; } + +.isIE .btn.btn-alt:focus:after { + border: 2px dashed #fff; } + +.btn.disabled { + background-image: none; + background-color: #767676; + box-shadow: none; + cursor: not-allowed; + color: #ffffff; + border-color: transparent; + outline: 0 !important; } + .btn.disabled:hover { + color: #f2f2f2; + outline: none !important; } + .btn.disabled:focus { + color: #f2f2f2; + outline: none !important; } + +.btn[disabled] { + background-image: none; + background-color: #767676; + box-shadow: none; + cursor: not-allowed; + color: #ffffff; + border-color: transparent; + outline: 0 !important; } + .btn[disabled]:hover { + color: #f2f2f2; + outline: none !important; } + .btn[disabled]:focus { + color: #f2f2f2; + outline: none !important; } + +.btn[disabled="disabled"] { + background-image: none; + background-color: #767676; + box-shadow: none; + cursor: not-allowed; + color: #ffffff; + border-color: transparent; + outline: 0 !important; } + .btn[disabled="disabled"]:hover { + color: #f2f2f2; + outline: none !important; } + .btn[disabled="disabled"]:focus { + color: #f2f2f2; + outline: none !important; } + +.btn-arrow[disabled] .btn { + background-image: none; + background-color: #767676; + box-shadow: none; + cursor: not-allowed; + color: #ffffff; + border-color: transparent; + outline: 0 !important; } + .btn-arrow[disabled] .btn:hover { + color: #f2f2f2; + outline: none !important; } + .btn-arrow[disabled] .btn:focus { + color: #f2f2f2; + outline: none !important; } + +.btn-arrow[disabled] .icon-left { + color: #fff !important; } + +.btn-arrow[disabled] .icon-right { + color: #fff !important; } + +.btn-arrow.disabled .btn { + background-image: none; + background-color: #767676; + box-shadow: none; + cursor: not-allowed; + color: #ffffff; + border-color: transparent; + outline: 0 !important; } + .btn-arrow.disabled .btn:hover { + color: #f2f2f2; + outline: none !important; } + .btn-arrow.disabled .btn:focus { + color: #f2f2f2; + outline: none !important; } + +.btn-arrow.disabled .icon-left { + color: #fff !important; } + +.btn-arrow.disabled .icon-right { + color: #fff !important; } + +.btn-medium { + padding: 12px 19px 11px 18px; + font-size: 1.7rem; } + +.btn-small { + padding: 10px 19px 9px 18px; + font-size: 1.5rem; + border-radius: 8px; } + +.btn-fullwidth { + width: 100%; } + +*:not(.btn-arrow) > .btn > i[class*="icon-"] { + margin-top: -20px; + margin-bottom: -20px; } + +.enhanced-cta-group { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: row-reverse; + flex-direction: row-reverse; + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3A%23959595%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E") !important; + background-position: 0 -1px; + background-repeat: repeat-x; } + .enhanced-cta-group > .cta-button-group { + border-top: 0; + background-image: none !important; } + .enhanced-cta-group > .cta-button-group + .cta-button-group a { + font-size: 1.4rem; + line-height: 1em; } + .enhanced-cta-group > .cta-button-group + .cta-button-group a a { + margin-right: 0; } + .enhanced-cta-group > .cta-button-group hr { + min-height: 14px; } + .enhanced-cta-group > .cta-button-group + .cta-button-group { + -ms-flex-align: center; + -ms-grid-row-align: center; + align-items: center; + -ms-flex-direction: row; + flex-direction: row; + padding: 10px 0; } + +.cta-button-group { + text-align: right; + -ms-flex-align: baseline; + align-items: baseline; + padding: 20px 0 10px; + width: 100%; } + .cta-button-group.nodots { + background-image: none !important; } + .cta-button-group .hidden-phone { + margin-right: 14px; } + .cta-button-group .btn + .btn { + margin-right: 20px !important; } + .cta-button-group .btn:not(.hidden-phone):not(.visible-phone) { + margin-right: 0; } + +.isMobile .btn-arrow .btn.btn-small .icon-left:before { + left: -1px; } + +.isMobile .btn-arrow .btn.btn-large .icon-left:before { + left: 24px; } + +.isMobile .btn-arrow .btn.btn-large .icon-right:before { + left: 24px; } + +@media (max-width: 1024px) { + .field-group + .btn { + margin-left: 15px; } } + +@media (max-width: 767px) { + .cta-button-group { + text-align: center; } + .cta-button-group > .btn { + display: block; + float: none; + width: 100%; + margin-left: auto !important; + margin-right: auto !important; } } + +.btn-group { + border-radius: 8px; + box-shadow: 0 5px 5px -5px rgba(0, 0, 0, 0.15); + display: -ms-flexbox; + display: flex; + -ms-flex-pack: justify; + justify-content: space-between; + margin-bottom: 10px; + max-width: 470px; + min-width: 290px; + position: relative; + vertical-align: middle; + width: 100%; } + .btn-group > .btn { + box-shadow: none; + -ms-flex: 1; + flex: 1; + position: relative; + float: left; + margin-right: -1px; + margin-bottom: 0; + padding-left: 0; + padding-right: 0; + text-align: center; } + .btn-group:not([data-select-color]) .btn.active:not(:first-child) { + margin-right: -1px; + border-left: 1px solid #d2d2d2 !important; } + .btn-group:not([data-select-color]) .btn[disabled]:not(:first-child) { + border-left: 1px solid #d2d2d2 !important; } + .btn-group:not([data-select-color]) .btn[disabled] + .btn[disabled] { + border-left: 1px solid #ebebeb !important; } + .btn-group:not([data-select-color]) > .btn.active { + border-color: #087ac2 transparent #0568ae; + background-color: #0568ae; + background: linear-gradient(to bottom, #087ac2 0%, #0568ae 100%); + color: #ffffff; } + .btn-group:not([data-select-color]) > .btn.active:hover { + color: #ffffff; + outline-color: #ffffff !important; + background: #0563a6; + border-color: #0563a6; } + .btn-group:not([data-select-color]) > .btn.active:focus { + color: #ffffff; + outline-color: #ffffff !important; + background: #0563a6; + border-color: #0563a6; } + .btn-group:not([data-select-color]) > .btn.active:active { + color: #ffffff; + outline-color: #ffffff !important; + background: #0563a6; + border-color: #0563a6; } + .btn-group:not([data-select-color]) > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { + border-radius: 0; } + .btn-group:not([data-select-color]) > .btn:first-child:not(:last-child):not(.dropdown-toggle) { + border-top-right-radius: 0; + border-bottom-right-radius: 0; } + .btn-group:not([data-select-color]) > .btn:last-child:not(:first-child) { + border-top-left-radius: 0; + border-bottom-left-radius: 0; } + .btn-group:not([data-select-color]) > .dropdown-toggle:not(:first-child) { + border-top-left-radius: 0; + border-bottom-left-radius: 0; } + .btn-group > .active { + text-decoration: none; + outline: 1px dotted transparent; } + .btn-group > .active:focus { + outline: 1px dotted #ffffff; } + +.btn-group.btn-fullwidth > .btn { + -ms-flex: 1; + flex: 1; } + +.btn-group[data-select-color] { + margin-top: 5px; + box-shadow: none; + -ms-flex-pack: start; + justify-content: flex-start; + -ms-flex-wrap: wrap; + flex-wrap: wrap; } + .btn-group[data-select-color] .btn { + border: 1px solid #959595; + border-radius: 4px; + box-shadow: 0 5px 5px -5px rgba(0, 0, 0, 0.15); + margin-right: 10px; + margin-bottom: 10px; + height: 40px; + font-size: 16px; + color: #333333; + max-width: 60px; + min-width: 60px; + -ms-flex: 0; + flex: 0; } + .btn-group[data-select-color] > .btn.active:focus { + outline: 1px dotted #191919; + outline-offset: 4px; } + +button .btn-fill { + background-clip: padding-box; + border: 0; + border-radius: 4px; + bottom: 0; + display: block; + height: auto; + left: 0; + margin: 5px; + position: absolute; + right: 0; + top: 0; + width: auto; } + +button .btn-fill[style*="#fff"] { + border: 1px solid #d2d2d2; } + +[data-select-color] .btn.active { + background: none !important; + outline: 0; + margin-right: 10px; + border-width: 3px; + color: #333333; + line-height: 12px; } + [data-select-color] .btn.active > .btn-fill { + margin: 3px; } + [data-select-color] .btn.active:hover { + color: #333333; } + +[data-select-color] .btn:active { + background: none !important; + outline: 0; + margin-right: 10px; + border-width: 3px; + color: #333333; + line-height: 12px; } + [data-select-color] .btn:active > .btn-fill { + margin: 3px; } + [data-select-color] .btn:active:hover { + color: #333333; } + +.btn-group[data-select-color="orange"] > .btn.active { + border-color: #ea7400; } + +.btn-group[data-select-color="blue"] > .btn.active { + border-color: #0568ae; } + +.btn-group[data-select-color="green"] > .btn.active { + border-color: #007a3e; } + +.btn-spinbutton-toggle.btn-group { + display: block !important; + height: 40px !important; + margin-top: 5px; + max-width: 138px; + min-width: 138px; + white-space: nowrap; } + +.btn-spinbutton-toggle .btn { + border-radius: 6px; + font-weight: normal; + -ms-flex: unset; + flex: unset; + height: 40px; + letter-spacing: normal; + min-width: auto; + padding: 3px 0 0; + text-align: center; + min-width: 46px; + width: 46px; } + +.btn-spinbutton-toggle .btn[data-max-value] { + border-bottom: 1px solid #d2d2d2; + border-top: 1px solid #d2d2d2; + box-shadow: 0 3px 2px -2px rgba(0, 0, 0, 0.08) inset; + background-color: #fff; + cursor: text; + font-family: "Omnes-ATT-W02"; + font-size: 2rem; + font-weight: normal; + padding: 4px 0 0; + text-align: center; + min-width: 46px !important; + width: 46px; } + .btn-spinbutton-toggle .btn[data-max-value]:focus { + border-color: #0568ae; + outline: none; } + .btn-spinbutton-toggle .btn[data-max-value]:focus + .btn { + border-left: 1px solid #0568ae; + transition: border 0.3s linear 0s; } + +.btn-spinbutton-toggle .icon-subtractminimize { + font-size: 30px !important; + color: #0568ae !important; } + +.btn-spinbutton-toggle .icon-add-maximize { + font-size: 30px !important; + color: #0568ae !important; } + +.btn-spinbutton-toggle .btn[disabled].icon-subtractminimize { + background-color: #d2d2d2; + color: #767676 !important; } + +.btn-spinbutton-toggle .btn[disabled].icon-add-maximize { + background-color: #d2d2d2; + color: #767676 !important; } + +.btn-spinbutton-toggle input.btn[disabled] { + background-color: #d2d2d2; + color: #5a5a5a; + cursor: not-allowed; } + +.btn-group.btn-spinbutton-toggle .btn[disabled] + .btn[disabled] { + border-left: 1px solid #f0f0f0 !important; } + +.btn-group.btn-spinbutton-toggle .btn[data-max-value]:focus + .btn:not(:first-child) { + border-left: 1px solid #0568ae !important; } + +@media (max-width: 480px) { + .btn-group:not([data-select-color]) > .btn { + font-size: 1.3rem; + min-width: auto; } } + +.reset-field, +.close { + float: right; + background: none; + width: 34px; + height: 34px; + padding: 0; + overflow: hidden; + display: inline-block; } + +.reset-field { + display: none; } + +.reset-field:before { + font-size: 22px; + color: #5a5a5a; } + +.input-emphasized + .reset-field:before { + font-size: 29px; + color: #5a5a5a; } + +.reset-field:active, +.reset-field:hover, +.reset-field:focus { + display: block !important; } + +button.close { + border: 0; + appearance: none; } + +.corner-button { + box-shadow: 0 -50px 0 0 #f2f2f2 inset; + height: 69px; + /*overflow: hidden;*/ + position: absolute; + right: -35px; + top: -35px; + transform: rotate(45deg); + width: 69px; } + +.corner-button .close:before { + bottom: -7px; + color: #0568ae; + display: block; + font-size: 20px; + height: 50px; + left: -11px; + position: absolute; + width: 50px; } + +.corner-button .close { + float: none; + height: 45px; + margin: 0; + position: absolute; + right: 12px; + top: 45px; + transform: rotate(45deg); + width: 45px; } + +.corner-button .close:focus { + outline: 1px dotted black; } + +.ds2-no-colors .corner-button .close { + border: 1px solid black; } + +.field-group input + .reset-field { + background: none; + height: 36px; + width: 45px; + display: none; + padding: 0; + position: absolute; + right: 0; + top: 0; + box-shadow: none; + border: none; + content: " "; } + +.field-group input[type="search"] + .reset-field, +.field-group input[type="search"] + .btn-search + .reset-field, +.tooltip-onclick input + .reset-field, +.tooltip-onclick input + .icon-tooltip + .reset-field, +.tooltip-onclick textarea + .reset-field, +.tooltip-onclick textarea + .icon-tooltip + .reset-field { + right: 45px; } + +.field-group input[type="search"] + .reset-field:after, +.field-group input[type="search"] + .btn-search + .reset-field:after, +.tooltip-onclick input + .reset-field:after, +.tooltip-onclick input + .icon-tooltip + .reset-field:after, +.tooltip-onclick textarea + .reset-field:after, +.tooltip-onclick textarea + .icon-tooltip + .reset-field:after { + background-color: #d2d2d2; + content: ""; + display: block; + height: 20px; + position: absolute; + right: 0; + top: 8px; + width: 1px; } + +.tooltip-onclick input + .reset-field, +.tooltip-onclick input + .icon-tooltip + .reset-field { + right: 50px !important; } + +.tooltip-onclick textarea + .reset-field, +.tooltip-onclick textarea + .icon-tooltip + .reset-field { + right: 45px !important; + width: 40px; } + +.field-group input.input-emphasized + .reset-field { + width: 45px; + height: 46px; + right: 6px; } + +.field-group input.input-emphasized + .reset-field:after { + top: 14px; } + +.field-group [disabled] + .reset-field { + display: none; } + +.ds2_touchevents .field-group input + .reset-field:focus, +.ds2_touchevents .field-group input:focus + .reset-field, +.ds2_touchevents textarea:focus + .reset-field, +.ds2_touchevents textarea + .reset-field:focus { + display: block; + position: absolute; + right: 0px; + top: 0; + border: none; } + +.ds2_touchevents .field-group input { + padding: 8px 55px 8px 15px; + -webkit-appearance: none; } + +.ds2_touchevents textarea:focus { + padding: 15px 55px 15px 15px; } + +.ds2_touchevents textarea:focus + .reset-field { + border: none; + position: absolute; + right: 6px; + top: 5px; } + +.ds2_touchevents textarea.hasScrollbar:focus { + padding: 15px 35px 15px 15px; } + +.ds2_touchevents textarea.hasScrollbar:focus + .reset-field { + right: 22px; } + +.ds2-no-colors .b2b-tmpl-card-corner-button { + border: none !important; } + +.ds2-no-colors .b2b-tmpl-card-corner-button .close { + border: 1px solid black; + top: 0px !important; + right: 0px !important; } + +.form-row.error .error-msg { + display: block; + font-size: 14px; + line-height: 14px; + font-family: "Omnes-ATT-W02-Medium"; + position: relative; + padding-left: 18px; } + +.form-row.error .error-msg:before { + color: #cf2a2a; + font-size: 14px; + left: 0; + line-height: 14px; + position: absolute; + vertical-align: middle; } + +.form-row.error label, +.form-row.error .error-msg, +.form-row.error button.awd-select, +.form-row.error select.awd-select + span, +.form-row.error .checkbox, +.form-row.error .radio, +.form-row.error legend.error, +.form-row.error input { + color: #cf2a2a; } + +.form-row.error .btn-group > .btn, +.form-row.error button.awd-select, +.form-row.error .awd-select-list, +.form-row.error select.awd-select + span, +.form-row.error textarea, +.form-row.error input, +.form-row.error .checkbox .skin, +.form-row.error .radio .skin { + border-color: #cf2a2a !important; } + +.form-row.error .checkbox input:checked:not(:disabled) + .skin { + background-color: #cf2a2a; } + +.form-row.error .radio input:checked + .skin:after { + background-color: #cf2a2a; } + +.error .tooltip-onclick .icon-tooltip.active + .error-msg { + margin-top: -11px; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + +.error .tooltip-onclick .icon-tooltip.active + .error-msg + .helpertext { + margin: 0 0 10px; } + +.error .tooltip-onclick .icon-tooltip.active + .error-msg + .helpertext:before, +.error .tooltip-onclick .icon-tooltip.active + .error-msg + .helpertext:after { + display: none; } + +.error .helpertext { + border-color: #cf2a2a; + /*border-radius:0;*/ } + +.error .helpertext:before { + border-top-color: #cf2a2a; } + +.error .tooltip-onfocus .helpertext { + margin: 14px 0 10px 0; } + +.error [class*="price"], +.error [class*="pricing-"] { + color: #cf2a2a; } + +input:-ms-clear { + display: none; } + +input[type]::-webkit-inner-spin-button, +input[type]::-webkit-outer-spin-button { + -webkit-appearance: none; } + +input[type] { + -moz-appearance: textfield; } + +form { + margin: 0; } + +fieldset { + padding: 0; + margin: 0; + border: 0; } + +label, +legend { + display: inline-block; + font-size: 1.4rem; + font-family: "Omnes-ATT-W02-Medium"; } + +legend { + display: block; } + +.error-msg { + display: none; } + +select, +textarea, +input { + border-radius: 6px; + color: #5a5a5a; + display: inline-block; + font-size: 1.6rem; + margin: 0px; + padding: 0 15px 0 15px; + vertical-align: middle; + line-height: normal; } + +select::-webkit-input-placeholder, +textarea::-webkit-input-placeholder, +input::-webkit-input-placeholder { + color: #5a5a5a; + font-family: "Omnes-ATT-W02-Italic"; + font-style: normal; + opacity: 1; } + +select:-moz-placeholder, +textarea:-moz-placeholder, +input:-moz-placeholder { + color: #5a5a5a; + font-family: "Omnes-ATT-W02-Italic"; + font-style: normal; + opacity: 1; } + +select::-moz-placeholder, +textarea::-moz-placeholder, +input::-moz-placeholder { + color: #5a5a5a; + font-family: "Omnes-ATT-W02-Italic"; + font-style: normal; + opacity: 1; } + +select:-ms-input-placeholder, +textarea:-ms-input-placeholder, +input:-ms-input-placeholder { + color: #5a5a5a; + font-family: "Omnes-ATT-W02-Italic"; + transition: none; + opacity: 1; } + +select:placeholder, +textarea:placeholder, +input:placeholder { + color: #5a5a5a; + font-family: "Omnes-ATT-W02-Italic"; + font-style: normal; + opacity: 1; } + +select:last-child, +textarea:last-child, +input:last-child { + margin-right: 0; } + +input:not([type="button"]) { + height: 36px; } + +input.input-emphasized { + font-size: 1.8rem; + height: 48px; + padding: 13px 20px 13px; } + +input[type="search"]:focus { + padding-right: 88px; } + +input[type="search"] { + padding-right: 40px; + -webkit-appearance: none !important; } + +input[type="search"].input-emphasized { + padding-right: 45px; } + +.btn-search[class*="btn"] { + background-color: transparent; + background-position: 50% 50%; + background-size: 20px; + background-repeat: no-repeat; + border: none; + height: 100%; + margin-left: 0; + margin-top: 0; + min-width: 45px !important; + outline-offset: 0; + padding: 0 !important; + position: absolute; + right: 0; + top: 0; + border-radius: 0 5px 5px 0; + min-width: 44px; + width: 44px; } + +.input-emphasized + .btn-search[class*="btn"], +.input-emphasized + .reset-field + .btn-search[class*="btn"] { + background-size: 26px; + height: 46px; + top: 1px; + outline-offset: -3px; + margin-bottom: 0; + border-radius: 0 5px 5px 0; } + +input[type="search"].input-emphasized + .reset-field { + right: 45px !important; } + +.search-suggestion-wrapper { + position: relative; + margin-bottom: 15px; } + +/*styles from dropdown*/ +.search-suggestion-list { + box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.15); + border-radius: 0 0 6px 6px; + position: relative; + border: 1px solid #0568ae; + border-top: 0; + padding: 15px 0; + background-color: #f2f2f2; + z-index: 1000; + width: 100%; + max-height: 400px; + overflow-y: auto; } + +.search-suggestion-list:empty { + display: none; } + +.search-suggestion-item { + position: relative; + z-index: -1; + padding: 0 15px; + line-height: 4.0rem; + color: #5a5a5a; } + +.search-suggestion-item a { + text-decoration: none; + color: #5a5a5a; } + +.search-suggestion-item:hover, +.search-suggestion-item:focus { + cursor: pointer; + background-color: #d2d2d2; } + +input[data-provide="datepicker"], +[data-provide="datepicker"]:-moz-placeholder, +[data-provide="datepicker"]:-ms-input-placeholder, +[data-provide="datepicker"]:-webkit-input-placeholder { + color: #0568ae !important; + opacity: 1; + filter: alpha(opacity=100); } + +input[disabled], +input[readonly], +select[disabled], +select[readonly], +textarea[disabled], +textarea[readonly], +i.icon-calendar.disabled, +span.icon-calendar.readonly { + cursor: not-allowed; + background-color: #f2f2f2; + box-shadow: none; + color: #5A5A5A !important; } + +i.icon-calendar.disabled input, +span.icon-calendar.readonly input { + color: #959595 !important; } + +textarea { + display: block; + width: 100%; + max-width: 100%; + padding: 15px; } + +textarea.small { + line-height: 20px; } + +textarea + .reset-field { + display: none; } + +textarea::-webkit-input-placeholder { + line-height: .99; } + +textarea:-moz-placeholder { + line-height: .99; } + +textarea::-moz-placeholder { + line-height: .99; } + +textarea:-ms-input-placeholder { + line-height: .99; } + +textarea:placeholder { + line-height: .99; } + +textarea, +input { + background-color: #ffffff; + border: 1px solid #d2d2d2; + -webkit-appearance: none; + box-shadow: 2px 3px 2px -2px rgba(0, 0, 0, 0.08) inset; + transition: border .3s linear 0s; + font-family: "Omnes-ATT-W02"; } + +textarea:focus, +input:focus { + outline: 0; + border-color: #0568ae; } + +.input-append { + display: table; } + +.input-append > div { + display: table-cell; + width: 1%; } + +.input-append > .field-group { + width: 100%; } + +.row .field-group input[class*="span"] { + float: none; } + +.field-group { + position: relative; + display: inline-block; } + +label + .field-group, +label + .input-append, +label + .row, +label + .row-nowrap, +label + .form-row { + margin-top: 5px; } + +.field-group { + position: relative; + display: block; } + +.field-group input:not([type="button"])[disabled] { + padding-right: 15px; } + +input:invalid, +textarea:invalid, +select:invalid { + outline: none !important; } + +.form-row { + margin-top: 15px; } + +.form-row.nomar { + margin: 0; } + +.row-nowrap.no-flex.form-row > label + br { + margin-bottom: 5px; } + +span.form-row { + display: inline-block; } + +legend + .form-row { + margin-top: 20px; } + +.tooltip-onclick input { + padding-right: 45px; } + +.ds2_touchevents .tooltip-onclick input:focus { + padding-right: 95px; } + +.btn-calendar-icon { + position: absolute; + background-color: transparent !important; + top: 8px; + border: 0 !important; + width: 30px; + right: 15px; } + +.btn-calendar-icon .icon-calendar:before { + position: absolute; + color: #0568ae; } + +.btn-calendar-icon .icon-calendar.disabled { + background-color: #f2f2f2; } + +.btn-calendar-icon .icon-calendar.disabled:before { + color: #959595; } + +span.icon-calendar input { + padding-left: 35px; + color: #0568ae; + transition: border-color 0.3s linear 0s; + box-shadow: 2px 3px 2px -2px rgba(0, 0, 0, 0.08) inset; + position: absolute; + top: 0; + left: 0; } + +.faux-input + input.datepicker-input:not([disabled]) { + cursor: pointer; + margin-left: 0; + background-color: #fff; + position: absolute; + left: 0; + top: 0; + z-index: 0; } + +.faux-input { + background-color: transparent !important; + border: 1px solid transparent; + border-radius: 4px; + font-size: 1.6rem; + height: 35px; + left: 0; + line-height: 35px; + margin-bottom: 10px; + margin-right: 6px; + padding: 0 0 0 35px; + position: relative; + text-align: left; + top: 0; + vertical-align: middle; + width: 100%; + z-index: 1; } + +.faux-input:disabled { + cursor: not-allowed; } + +.faux-input:focus + .datepicker-input, +[data-calendar-state="opened"] + .datepicker-input { + border-color: #0568ae; + box-shadow: 2px 3px 2px -2px rgba(5, 116, 172, 0.35) inset; + outline: 0 none; } + +.form-row.error .error-msg { + display: block; + font-size: 14px; + line-height: 14px; + font-family: "Omnes-ATT-W02-Medium"; + position: relative; + padding-left: 18px; + margin-top: 10px; } + +.form-row.error .error-msg > .icon-badgealert { + height: 14px; + width: 14px; + position: absolute; + left: 0; + margin-right: 0; } + +.form-row.error .error-msg > .icon-badgealert:before { + color: #cf2a2a; + font-size: 14px; + left: 0; + line-height: 14px; + position: absolute; + vertical-align: middle; } + +.form-row.error label, +.form-row.error .error-msg, +.form-row.error button.awd-select, +.form-row.error select.awd-select + span, +.form-row.error .checkbox, +.form-row.error .radio, +.form-row.error legend.error, +.form-row.error input, +.form-row.error textarea { + color: #cf2a2a; } + +.form-row.error .btn-group > .btn, +.form-row.error button.awd-select, +.form-row.error .awd-select-list, +.form-row.error select.awd-select + span, +.form-row.error textarea, +.form-row.error input, +.form-row.error .checkbox .skin, +.form-row.error .radio .skin { + border-color: #cf2a2a !important; } + +.form-row.error .checkbox input:checked:not(:disabled) + .skin { + background-color: #cf2a2a; } + +.form-row.error .radio input:checked + .skin:after { + background-color: #cf2a2a; } + +.error [class*="price"], +.error [class*="pricing-"] { + color: #cf2a2a; } + +.b2b-disabled-label { + color: #5A5A5A; + cursor: not-allowed; } + +hr, +.hr-or { + display: block; + height: 1px; + margin: 15px 0; + border: none; + background-repeat: repeat-x; + background-color: #959595; + position: relative; } + +hr.dark { + background-color: #959595; } + +hr.lite { + background-color: #d2d2d2; } + +.hr-or:before { + background-color: #fff; + color: #666; + content: " OR "; + display: block; + font-size: 1.4rem; + font-family: "Omnes-ATT-W02-Medium"; + height: 16px; + left: 50%; + line-height: 1.6rem; + margin-left: -15px; + margin-top: -8px; + position: absolute; + text-align: center; + top: 50%; + width: 30px; + z-index: 1111; } + +hr.hr-dotted.dark { + background-color: transparent; + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(153%2C153%2C153%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E"); + background-position: bottom; + background-repeat: repeat-x; + background-size: 4px 1px; + width: 100%; } + +hr.hr-dotted.lite { + background-color: transparent; + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(204%2C204%2C204%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E"); } + +hr.is-vertical.dark, +hr.hr-or.dark, +hr.is-vertical.lite, +hr.hr-or.lite { + display: inline-block; + height: auto; + margin: 0 15px; + min-height: 20px; + width: 1px; } + +hr.is-vertical.dark, +hr.hr-or.dark { + background-color: #959595; } + +hr.is-vertical.lite, +hr.hr-or.lite { + background-color: #d2d2d2; } + +.hr-dotted.is-vertical.dark, +.hr-dotted.is-vertical.lite { + background-color: transparent; + background-repeat: repeat-y; + background-size: 1px 4px; + height: auto; + min-height: 20px; + width: 1px; } + +.hr-dotted.is-vertical.dark { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A1px%3B%20height%3A100%25%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(153%2C153%2C153%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%22100%25%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%221%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E"); } + +.hr-dotted.is-vertical.lite { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A1px%3B%20height%3A100%25%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(204%2C204%2C204%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%22100%25%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%221%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E"); } + +.row-nowrap > .span + hr.is-vertical, +.row > .span + hr.is-vertical { + margin: 0 0 0 -20px; } + +@media (max-width: 767px) { + hr, + .hr-or { + margin: 30px 0; } + hr.full { + margin-left: -15px; + margin-right: -15px; } + .hr-or.is-vertical { + min-height: 1px; + height: 1px; + width: 100%; } + .row-nowrap > .span + hr.is-vertical { + margin: 0 0 0 -15px; } + .row > .span + hr.is-vertical { + min-height: 1px; + height: 1px; + width: 100%; + margin: 0; + display: block; } + .row > .span + hr.is-vertical.lite { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(204%2C204%2C204%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E") !important; + background-size: 4px 1px; + background-repeat: repeat-x; } + .row > .span + hr.is-vertical.dark { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(153%2C153%2C153%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E") !important; + background-size: 4px 1px; + background-repeat: repeat-x; } } + +hr.bottom-space-only { + margin-top: 0; } + +.hr-nomargin { + margin: 0; } + +.radio { + position: relative; + min-height: 24px; + font-family: "Omnes-ATT-W02"; + font-size: 1.6rem; + margin-bottom: 5px; } + .radio input { + -webkit-tap-highlight-color: transparent; + height: 10px; + margin: 6px; + opacity: 0; + outline: none; + position: absolute; + left: 1px; + top: 1px; + width: 10px; } + .radio input:focus + .skin { + border-color: #0568ae; } + .radio input:focus + .skin:before { + content: ""; + height: 34px; + left: -6px; + top: -6px; + outline: 1px dotted #000000; + position: absolute; + width: 34px; } + .radio input + .skin { + border-radius: 100%; } + .radio input:checked + .skin:after { + background-color: #0568ae; + border-radius: 100%; + border: 3px solid #FFFFFF; + content: ""; + display: block; + height: 16px; + position: absolute; + width: 16px; } + .radio input:disabled + .skin { + cursor: not-allowed; + background-color: #d2d2d2; + border-color: #d2d2d2; + color: #5A5A5A; } + .radio input:disabled + .skin + span { + cursor: not-allowed; + color: #5A5A5A; } + .radio input:disabled:checked + .skin:after { + background-color: #5A5A5A; + border: 3px solid #d2d2d2; } + .radio input:invalid + .skin { + border: solid 1px #cf2a2a; } + .radio .skin { + background-color: #FFFFFF; + border: 1px solid #d2d2d2; + border-radius: 3px; + display: inline-block; + height: 24px; + left: 0; + position: absolute; + top: 0; + width: 24px; } + .radio span { + display: inline-block; + margin-left: 34px; + margin-top: 0; + position: relative; + top: 3px; } + .radio label { + font-size: 1.6rem; + font-family: "Omnes-ATT-W02"; } + +.radio.inline { + display: inline-block; + margin-bottom: 10px; + vertical-align: middle; + margin-right: 10px; } + .radio.inline:last-child { + margin-right: 0; } + +.radio-box { + border: 1px solid #d2d2d2; + border-radius: 8px; } + .radio-box > [role="radio"] label { + padding: 15px 15px 20px 15px; + display: block; + width: 100%; } + .radio-box > [role="radio"] label .skin + span { + top: 2px; } + .radio-box > [role="radio"] + div { + padding: 0 15px 15px 47px; } + .radio-box > [aria-checked="false"] label > input { + top: 15px; + left: 15px; } + .radio-box > [aria-checked="false"] label .skin { + top: 15px; + left: 15px; } + .radio-box > [aria-checked="true"] label > input { + top: 13px; + left: 13px; } + .radio-box > [aria-checked="true"] label .skin { + top: 13px; + left: 13px; } + +.radio-box.active { + border: 3px solid #0568ae; } + .radio-box.active > [role="radio"] label { + padding: 13px 14px 19px 13px; } + +.checkbox { + position: relative; + min-height: 24px; + font-family: "Omnes-ATT-W02"; + font-size: 1.6rem; + margin-bottom: 5px; } + .checkbox input { + -webkit-tap-highlight-color: transparent; + height: 10px; + margin: 6px; + opacity: 0; + outline: none; + position: absolute; + left: 1px; + top: 1px; + width: 10px; } + .checkbox input:focus + .skin { + border-color: #0568ae; } + .checkbox input:focus + .skin:before { + content: ""; + height: 34px; + left: -6px; + top: -6px; + outline: 1px dotted #000000; + position: absolute; + width: 34px; } + .checkbox input:checked:not(:disabled) + .skin { + background-color: #0568ae; + border-color: #0568ae; } + .checkbox input:checked:disabled + .skin:after { + color: #5A5A5A; } + .checkbox input:checked + .skin:after { + height: 24px; + width: 24px; + background-color: transparent; + font-size: 23.4px; + color: #FFFFFF; + line-height: 21px; + -webkit-text-fill-color: white; } + .checkbox input:disabled + .skin { + cursor: not-allowed; + background-color: #d2d2d2; + border-color: #d2d2d2; + color: #5A5A5A; } + .checkbox input:disabled + .skin + span { + cursor: not-allowed; + color: #5A5A5A; } + .checkbox input:disabled + .skin:after { + -webkit-text-fill-color: #5A5A5A; } + .checkbox input:invalid + .skin { + border: solid 1px #cf2a2a; } + .checkbox input:indeterminate + .skin:after { + background-color: transparent; + font-size: 25px; + color: #0574ac; + content: "\e920"; } + .checkbox .skin { + background-color: #fff; + border: 1px solid #d2d2d2; + border-radius: 3px; + display: inline-block; + height: 24px; + width: 24px; + position: absolute; + left: 0; + top: 0; } + .checkbox span { + display: inline-block; + margin-left: 34px; + margin-top: 0; + position: relative; + top: 3px; } + .checkbox label { + font-size: 1.6rem; + font-family: "Omnes-ATT-W02"; } + .checkbox input { + z-index: 9999; } + .checkbox input.indeterminate + .skin:after { + font-size: 22px; + color: #0568ae; } + +.checkbox.inline { + display: inline-block; + margin-bottom: 10px; + vertical-align: middle; + margin-right: 10px; } + .checkbox.inline:last-child { + margin-right: 0; } + +.checkbox.checkbox-selectall { + margin: 20px 0 0 24px; } + +.terms-after-checkbox { + margin-top: 15px; } + +.indeterminate-margin { + padding-left: 24px; } + +.tiny-accordion { + border-bottom: 1px solid #d2d2d2; } + +.toggle-header, +.inactive-toggle-header { + border-color: #fff; + color: #0568ae; + cursor: pointer; + display: block; + font-size: 2.0rem; + line-height: 2.2rem; + min-height: 41px; + position: relative; + padding: 16px 55px 16px 15px; } + +.toggle-header.opened { + color: #333333; } + +.tiny-accordion .toggle-header, +.tiny-accordion .inactive-toggle-header { + padding: 16px 55px 16px 15px; + border-top: 1px solid #d2d2d2; } + +.tiny-accordion .toggle-header:focus { + text-decoration: underline; } + +.tiny-accordion.iconleft .toggle-header, +.tiny-accordion.iconleft .inactive-toggle-header { + padding: 15px 15px 15px 50px; } + +.accordion-content { + font-size: 1.4rem; } + +.accordion-content .toggle-header:first-child { + margin-top: 16px; } + +.tiny-accordion .toggle-header + .accordion-content { + padding: 0 50px 15px 15px; } + +.tiny-accordion.iconleft .toggle-header + .accordion-content { + padding: 0 15px 15px 50px; } + +.toggle-header .icon-accordion-plus, +.toggle-header .icon-accordion-minus { + display: inline-block; + font-size: 20px; + margin: 0; + padding: 0; + position: absolute; + right: 15px; + vertical-align: middle; + top: 16px; + font-weight: bold; } + +.tiny-accordion.iconleft .toggle-header .icon-accordion-plus, +.tiny-accordion.iconleft .toggle-header .icon-accordion-minus { + left: 15px; } + +.inactive-toggle-header:hover { + cursor: inherit; } + +.tiny-accordion-to-tabs, +.tiny-tabs { + position: relative; + width: 100%; + margin: 0px; + padding: 0px; } + +.tiny-tabs [class*="icon-accordion-"] { + display: none !important; } + +.tiny-accordion-to-tabs:before, +.tiny-accordion-to-tabs:after, +.tiny-tabs:before, +.tiny-tabs:after { + display: table; + content: ""; + line-height: 0; } + +.tiny-accordion-to-tabs:after, +.tiny-tabs:after { + clear: both; } + +.tiny-accordion-to-tabs:before, +.tiny-accordion-to-tabs:after, +.tiny-tabs:before, +.tiny-tabs:after { + display: table; + content: ""; + line-height: 0; } + +.tiny-accordion-to-tabs:after, +.tiny-tabs:after { + clear: both; } + +.tiny-tabs > .toggle-header { + display: inline-block; + float: left; + border-top: none; + overflow: hidden; + height: 70px; + text-align: center; + background-color: #fff; + border-radius: 0px; + padding: 26px 20px 25px 20px !important; + border-top: 1px solid #fff; + -webkit-filter: none; + filter: none; + background-clip: padding-box; + border-bottom: 1px solid #d2d2d2; + font-weight: normal; + border-right: 1px solid #d2d2d2; + white-space: nowrap; } + +.tiny-tabs .toggle-header + div { + left: 0px; + position: absolute; + top: 69px; + border-top: 1px solid #d2d2d2; + padding: 0; + display: block; + border-bottom: none; + width: 100%; } + +.accordion-pad { + padding-top: 30px; + padding-bottom: 30px; } + +.tiny-tabs .opened { + color: #333333; + border-top: 5px solid #0568ae !important; + padding-top: 22px !important; + border-bottom: none; + background-color: #fff; + -webkit-filter: none; + filter: none; + cursor: default; + z-index: 999; } + +.tiny-tabs .toggle-header:focus { + text-decoration: underline; + outline: thin dotted #666; + outline-offset: 0; } + +.tiny-tabs .toggle-header:first-child { + border-left: none; + margin-left: 0; } + +.tiny-tabs .toggle-header:first-child { + border-left: 1px solid #fff; } + +.tiny-tabs .opened:first-child { + border-left: 1px solid #d2d2d2; } + +.tiny-tabs .toggle-header:nth-last-of-type(2) { + border-right-color: #fff; } + +.tiny-tabs .opened:nth-last-of-type(2) { + border-right: 1px solid #d2d2d2; } + +@media (max-width: 767px) { + .tiny-accordion, + .tiny-accordion-to-tabs { + margin-left: -15px; + margin-right: -15px; + width: auto; } + .tiny-accordion-to-tabs { + display: block; + border-bottom: 1px solid #d2d2d2; } + .tiny-accordion-to-tabs .toggle-header { + display: block; + min-height: 41px; + padding: 16px 50px 16px 15px; + border-top: 1px solid #d2d2d2; } + .tiny-accordion-to-tabs .toggle-header:focus { + text-decoration: underline; } + .tiny-accordion-to-tabs .toggle-header + .accordion-content { + padding: 0 50px 15px 15px; } } + +@media (min-width: 768px) { + .tiny-accordion-to-tabs [class*="icon-accordion-"] { + display: none !important; } + .tiny-accordion-to-tabs > .toggle-header { + display: inline-block; + float: left; + border-top: none; + /*overflow: hidden;*/ + height: 70px; + text-align: center; + background-color: #fff; + border-radius: 0px; + padding: 26px 20px 25px 20px !important; + border-top: 1px solid #fff; + -webkit-filter: none; + filter: none; + background-clip: padding-box; + border-bottom: 1px solid #d2d2d2; + font-weight: normal; + border-right: 1px solid #d2d2d2; + white-space: nowrap; } + .tiny-accordion-to-tabs .toggle-header + div { + left: 0px; + position: absolute; + top: 69px; + border-top: 1px solid #d2d2d2; + padding-top: 30px; + padding-left: 20px; + display: block; + border-bottom: none; + width: 100%; } + .tiny-accordion-to-tabs .opened { + color: #333333; + border-top: 5px solid #0568ae !important; + padding-top: 22px !important; + border-bottom: none; + background-color: #fff; + -webkit-filter: none; + filter: none; + cursor: default; + text-decoration: none; + z-index: 999; } + .tiny-accordion-to-tabs .toggle-header:focus { + text-decoration: underline; + outline: thin dotted #666; + outline-offset: 0px; } + .tiny-accordion-to-tabs .toggle-header:nth-last-of-type(2) { + border-right: none; } + .tiny-accordion-to-tabs .toggle-header:first-child { + border-left: none; + margin-left: 0; } + .tiny-accordion-to-tabs .toggle-header:first-child { + border-left: 1px solid #fff; } + .tiny-accordion-to-tabs .opened:first-child { + border-left: 1px solid #d2d2d2; } + .tiny-accordion-to-tabs .opened:nth-last-of-type(2) { + border-right: 1px solid #d2d2d2; } } + +.toggle-header .tooltip .icon-tooltip { + margin-top: -5px; } + +.accordion-content { + transition: all 0.8s linear; } + +.opaque-content { + opacity: 0; } + +.tiny-tabs .toggle-header { + display: inline-block; + float: left; + border-top: none; + overflow: hidden; + height: 70px; + text-align: center; + background-color: #fff; + border-radius: 0px; + padding: 22px 20px 25px 20px !important; + border-top: 5px solid #fff; + -webkit-filter: none; + filter: none; + background-clip: padding-box; + border-bottom: 1px solid #ccc; + font-weight: normal; + border-right: 1px solid #ccc; + white-space: nowrap; } + +.tiny-tabs .toggle-header:first-child { + margin-left: 0; } + +.tiny-tabs div:first-child .toggle-header { + margin-left: 30px; } + +.tiny-tabs > div .toggle-header.opened { + border-bottom: 0 !important; } + +.tiny-accordion-to-tabs > div > div.toggle-header { + background-clip: padding-box; + background-color: #fff; + border-bottom: 1px solid #ccc; + border-radius: 0; + border-top: 5px solid #fff; + display: inline-block; + filter: none; + float: left; + font-weight: normal; + overflow: hidden; + padding: 22px 20px 21px !important; + text-align: center; + white-space: nowrap; } + +.tiny-accordion-to-tabs .toggle-header:first-child { + margin-left: 0; } + +.tiny-accordion-to-tabs div:first-child .toggle-header { + margin-left: 30px; + border-bottom: 0 !important; } + +.tiny-accordion-to-tabs > div .toggle-header.opened { + border-bottom: 0 !important; } + +@media (max-width: 767px) { + .tiny-accordion-to-tabs { + display: block !important; + border-bottom: 1px solid #ccc !important; } + .tiny-accordion-to-tabs > div > div.toggle-header { + display: block !important; + float: none; + text-align: left; + min-height: 41px !important; + padding: 15px 50px 15px 15px !important; + border-top: 1px solid #ccc; } + .tiny-accordion-to-tabs > div > div.toggle-header:first-child { + margin-left: 0 !important; } + .tiny-accordion-to-tabs > div > div.toggle-header + .accordion-content { + padding: 0 50px 15px 15px; } + .tiny-accordion-to-tabs > div > div.toggle-header .icon-accordion-plus { + background-position: 0 0; + background-size: 20px 40px; } + .tiny-accordion-to-tabs > div > div.toggle-header .icon-accordion-minus { + background-position: 0 -20px; + background-size: 20px 40px; } + .tiny-accordion-to-tabs > div > div.toggle-header .icon-accordion-plus, + .tiny-accordion-to-tabs > div > div.toggle-header .icon-accordion-minus { + display: inline-block; + height: 20px; + margin: 0; + padding: 0; + position: absolute; + right: 15px; + vertical-align: middle; + width: 20px; } } + +.alert { + background-color: #5a5a5a; + border-radius: 8px; + color: #fff; + margin-top: 15px; + padding: 0; + position: relative; + border: 0; } + +.alert h3, +.alert h4 { + color: #fff; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 1.6rem; + margin: 0 20px 5px 0; } + +.alert div { + padding: 15px 20px; } + +.alert div:first-child { + border-radius: 8px 0 0 8px; + width: 1%; } + +.alert div:first-child + div { + border: 1px solid transparent; + border-left: none; + border-radius: 0 8px 8px 0; } + +.alert-error { + background-color: #cf2a2a; + border: 1px solid #cf2a2a; } + +.alert-info { + background-color: #44c8f5; + border: 1px solid #44c8f5; } + +.alert-success { + background-color: #c5d63d; + border: 1px solid #c5d63d; } + +.alert [class*="icon-"] { + color: #fff; + font-size: 30px; + margin-right: 0; } + +.alert .close { + height: 30px; + position: absolute; + right: 1px; + top: 1px; + width: 30px; } + +.alert .close:before { + color: #fff; + margin-right: 0; + position: absolute; + right: 9px; + top: 9px; } + +.alert a { + color: #fff; + text-decoration: underline; } + +.alert .close:focus { + outline: 1px dotted #666; } + +.alert p { + font-size: 1.4rem; } + +.alert p:last-child { + margin-bottom: 0px; + margin-top: 0px; } + +.alert .standalone-link i[class*="icon-"] { + font-size: 20px; + margin-right: 5px; } + +@media (max-width: 767px) { + .alert { + border-radius: 0; + margin: 0 -15px; } + .alert + .alert { + margin-top: 4px; } + .alert div { + padding: 15px 10px; } + .alert div:first-child { + border-radius: 0; + padding: 15px; } + .alert h3, + .alert h4 { + font-size: 1.4rem; } + .alert p { + font-size: 1.2rem; } + .alert .close { + right: 5px; + top: 5px; } + .alert .standalone-link i[class*="icon-"] { + font-size: 16px; } } + +.alert h3 { + margin: 0; + font-size: 16px; } + +.alert p { + font-size: 14px; } + +.alert p a { + color: #FFFFFF; + text-decoration: underline; } + +.alert div:first-child + div { + padding-right: 20px; } + +.alert div:last-child { + padding-right: 20px !important; } + +.alert p [class*="icon-"] { + color: #fff; + font-size: 20px; + margin-right: 0; } + +@media (max-width: 767px) { + .alert h3 { + font-size: 14px; } + .alert div:first-child + div { + padding-right: 20px; } + .alert div:last-child { + padding-right: 15px !important; } + .alert div:first-child { + padding: 15px; } + .alert p { + font-size: 12px; } + .alert p [class*="icon-"] { + font-size: 16px; } } + +.b2b-audio { + width: auto; + margin: 10px auto; + height: 35px; } + .b2b-audio .controls-wrapper { + display: inline-block; + font-size: 25px; + cursor: pointer; } + .b2b-audio .controls-wrapper i { + font-size: 25px; + margin-right: 0px; + color: #444; } + .b2b-audio .controls-wrapper i:hover { + color: #0574AC; } + .b2b-audio .slider-container-wrapper { + display: inline-block; + outline: 0; + min-width: 180px; + margin-right: 10px; + margin-left: 10px; + height: 14px; + padding-top: 5px; } + .b2b-audio .slider-container-wrapper .timing-container { + padding-top: 20px; + color: #333; + font-size: 12px; } + .b2b-audio .slider-container-wrapper .timing-container .timing-container-left { + float: left; + line-height: 100%; } + .b2b-audio .slider-container-wrapper .timing-container .timing-container-right { + float: right; + line-height: 100%; } + .b2b-audio .slider-container-wrapper .timing-container .timing-container-spacer { + clear: both; } + .b2b-audio .slider-tooltip { + text-align: center; + min-width: 76px; } + +.b2b-audio-popover { + width: 22px; } + .b2b-audio-popover .volume-popover { + height: 100px !important; + width: 6px !important; + margin: 7px auto; } + .b2b-audio-popover .min-label { + margin-top: 5px; } + +.b2b-audio-native { + width: auto; + height: auto; } + +.b2b-audio-disabled { + pointer-events: none; } + .b2b-audio-disabled .controls-wrapper { + cursor: default; } + .b2b-audio-disabled .controls-wrapper i { + color: #808080; } + .b2b-audio-disabled .controls-wrapper i:hover { + color: #808080; } + .b2b-audio-disabled .b2b-flyout { + color: #808080; } + +.b2b-audio-recorder { + border: 1px solid #ccc; + box-shadow: 0px 1px 2px 0 rgba(0, 0, 0, 0.15); + height: 63px; + min-height: 63px; + min-width: 347px; } + .b2b-audio-recorder .b2b-elapsed-time { + margin: 23px 0 24px 15px; + font-size: 16px; + font-style: italic; + color: #767676; } + .b2b-audio-recorder .b2b-controls { + width: 68px; + cursor: pointer; } + .b2b-audio-recorder .b2b-controls i.icon-controls-record { + font-size: 64px; + color: black; + float: right; + margin-right: 10px; } + .b2b-audio-recorder .b2b-controls i.icon-controls-record:focus, .b2b-audio-recorder .b2b-controls i.icon-controls-record:hover { + color: #0568ae; } + .b2b-audio-recorder .b2b-controls i.icon-controls-stop { + font-size: 36px; + color: black; + float: right; + margin-right: 20px; + margin-top: 12px; } + .b2b-audio-recorder .b2b-controls i.icon-controls-stop:focus, .b2b-audio-recorder .b2b-controls i.icon-controls-stop:hover { + color: #0568ae; } + +.b2b-top-btn { + height: 36px; + width: 36px; + border-radius: 7px; } + +.b2b-top-btn > i { + position: absolute; + top: 13px; + left: 9px; + width: 11px; + height: 18px; } + +.b2b-badge { + font-family: "Omnes-ATT-W02-Medium"; + background-color: #5A5A5A; + border-radius: 12px; + color: #FFFFFF; + display: inline-block; + font-size: 1.5rem; + font-weight: normal; + height: 20px; + line-height: 0; + margin-top: 0; + min-width: 20px; + padding: 0 5px; + text-align: center; + vertical-align: baseline; } + .b2b-badge:empty { + display: none; } + +* + .b2b-heading-micro { + margin-top: 20px !important; } + +.b2b-heading-micro { + font-family: "Omnes-ATT-W02-Medium"; + font-weight: normal; + text-rendering: optimizeLegibility; + font-size: 1.2rem !important; + text-transform: uppercase !important; + margin-bottom: 20px !important; + line-height: 1.2 !important; } + +.b2b-no-colors .b2b-badge { + border: 1px solid transparent; } + +.btn > .b2b-badge { + margin-right: 5px; } + +a > .b2b-badge { + margin-right: 6px; + padding-top: 10px; } + +.b2b-badge-urgent { + background-color: #cf2a2a; } + +.b2b-bellyband-container { + margin: 0; } + +.b2b-bellyband-container:after { + clear: both; + content: ""; + display: table; } + +.b2b-bellyband-container:after { + clear: both; + content: ""; + display: table; } + +.b2b-bellyband-link { + border-top: 1px solid #d2d2d2; + padding: 0 15px; + position: relative; } + +.b2b-bellyband-link a { + display: block; + height: 40px; + line-height: 40px; + text-decoration: none; } + +.b2b-bellyband-link a:hover > div span, +.b2b-bellyband-link a:focus > div span { + text-decoration: underline; } + +.b2b-bellyband-link .icon-right { + display: none; } + +.bg-att-digital-black { + background-color: #191919; } + .bg-att-digital-black a span { + text-decoration: underline; } + .bg-att-digital-black .make-all-white *, .bg-att-digital-black a:after { + color: white; } + +.ds2-pad { + margin: 0 -20px; + padding: 20px; } + +.b2b-bellyband-link img[src$="svg"].hidden-desktop, +.b2b-bellyband-link [class*="icon-"].hidden-desktop { + display: inline-block !important; + float: left; + font-size: 24px; + height: 24px; + margin-right: 5px; + margin-top: 8px; + width: 24px; } + +.bg-att-digital-black .b2b-bellyband-link [class*="icon-"].hidden-desktop, +.bg-att-digital-black .b2b-bellyband-link [class*="icon-"].visible-desktop { + color: #fff; } + +.b2b-bellyband-link img[src$="svg"].visible-desktop { + display: none !important; } + +.b2b-bellyband-link p { + margin-top: -10px; + margin-left: 29px; + font-size: 1.4rem; + color: #5a5a5a; } + +@media (min-width: 768px) { + .b2b-bellyband-group { + margin: 0; + max-width: 100%; + display: -ms-flexbox; + display: flex; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + -ms-flex-pack: center; + justify-content: center; } + .b2b-bellyband-group .row { + display: block; } + .b2b-bellyband-group .row .span { + float: none; + margin-right: 0; + margin-bottom: 30px; + display: -ms-flexbox; + display: flex; + -ms-flex-pack: justify; + justify-content: space-between; } + .b2b-bellyband-link { + border-top: none; + -ms-flex: 0 0 auto; + flex: 0 0 auto; + margin-right: 0; + margin-bottom: 30px; } + .b2b-bellyband-link:last-child { + margin-right: 0; } + .b2b-bellyband-link a { + height: auto; + line-height: 1; + text-align: center; } + .b2b-bellyband-link a:after { + display: none; } + .b2b-bellyband-link img[src$="svg"].hidden-desktop, + .b2b-bellyband-link [class*="icon-"].hidden-desktop { + display: none !important; } + .b2b-bellyband-link img[src$="svg"].visible-desktop, + .b2b-bellyband-link [class*="icon-"].visible-desktop { + display: block !important; + font-size: 50px; + height: 50px; + margin-right: 0; + margin-top: 0; + margin-left: auto; + margin-right: auto; + width: auto; } + .b2b-bellyband-link a span { + display: block; + margin-top: 12px; + line-height: 2rem; } + .b2b-bellyband-link p { + display: block; + text-align: center; + margin-top: 6px; + margin-left: 0; + padding-left: 0 !important; + line-height: 1.8rem; } } + +@media (min-width: 480px) and (max-width: 767px) { + .b2b-bellyband-container { + display: -ms-flexbox; + display: flex; + margin: 0; } + .b2b-bellyband-group { + -ms-flex-line-pack: start; + align-content: flex-start; + -ms-flex-align: stretch; + align-items: stretch; + display: -ms-inline-flexbox; + display: inline-flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + margin-top: 1px; + width: 100%; } + .b2b-bellyband-group.span6-sm .span12-sm { + margin-right: 10px; } + .b2b-bellyband-group.span6-sm + .span6-sm .b2b-bellyband-link { + margin-left: 10px; } + .b2b-bellyband-link { + padding-top: 0; + padding-left: 0; + position: relative; + border-top: none; + margin-bottom: 20px; + width: 50%; } + .b2b-bellyband-link a { + height: auto; + line-height: inherit; + display: -ms-flexbox; + display: flex; + padding: 0; } + .b2b-bellyband-link a:after { + display: none; } + .b2b-bellyband-link a span { + display: block; + padding-top: 10px; } + .b2b-bellyband-link p { + display: block; + padding: 0 15px 0 29px; + margin-bottom: 0; + margin-left: 0; + margin-top: 0; } + .b2b-bellyband-link a + p { + margin-top: -2px; } + .b2b-bellyband-link a:focus p { + text-decoration: none; } + .b2b-bellyband-group > [class*="span"]:empty { + display: none; } } + +@media (max-width: 479px) { + .b2b-bellyband-container { + margin: 0 -15px; } + .b2b-bellyband-link { + padding: 0 0 0 15px; } + .b2b-bellyband-link .icon-right { + color: #959595; + display: block; + font-size: 24px; + position: absolute; + right: 0; + margin-top: -12px; + top: 50%; } + .bg-att-digital-black .b2b-bellyband-link .icon-right { + color: #fff; } + .b2b-bellyband-link > a { + -ms-flex-align: center; + align-items: center; + display: -ms-flexbox; + display: flex; + line-height: 1; + margin-top: 0; + height: 40px; } + .b2b-bellyband-link > a span { + -ms-flex: 1 1 auto; + flex: 1 1 auto; } + .b2b-bellyband-link img[src$="svg"].hidden-desktop, + .b2b-bellyband-link [class*="icon-"].hidden-desktop { + margin-top: 0; } + .b2b-bellyband-container.border-bottom { + border-top: 1px solid #d2d2d2; } + .b2b-bellyband-container.border-bottom .b2b-bellyband-link { + border-bottom: 1px solid #d2d2d2; + border-top: none; } + .b2b-bellyband-link-tall a { + height: auto; + padding: 8px 0; + outline-offset: -3px; } + .b2b-bellyband-link p { + line-height: 1.8rem; + margin-bottom: 0; + padding-right: 40px; + padding-bottom: 10px; } + .b2b-bellyband-link-tall > a:after { + margin-top: -8px; + top: 50%; } + .b2b-bellyband-group > [class*="span"]:empty { + display: none; } } + +.b2b-boardstrip { + display: inline-block; + width: 100%; + border-bottom: 1px solid #9d9d9d; + position: relative; + padding-top: 15px; } + .b2b-boardstrip .boardstrip-reel { + margin-bottom: 15px; } + .b2b-boardstrip .boardstrip-item--add { + border: 1px dashed #ccc; + background: #FFFFFF; + color: #0574ac; + width: 140px; + height: 80px; + font-size: 14px; + font-family: "Omnes-ATT-W02"; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + position: absolute; + left: 29px; + top: 15px; } + .b2b-boardstrip .boardstrip-item--add:hover, .b2b-boardstrip .boardstrip-item--add:focus { + border: 2px solid #007A3E; + cursor: pointer; } + .b2b-boardstrip .boardstrip-item--add i { + font-size: 14px; + margin-left: auto; + margin-right: auto; + text-align: initial; } + .b2b-boardstrip .boardstrip-item--add .centered { + margin-left: auto; + margin-right: auto; + margin-top: 27px; + margin-bottom: 35px; + display: block; } + .b2b-boardstrip .board-viewport { + float: left; + margin-left: 210px; + max-height: 95px; + position: relative; + height: 95px; + overflow: hidden; + width: 0px; } + .b2b-boardstrip .board-viewport .boardstrip-container { + width: 0px; + margin-left: 0; + left: 0px; + position: absolute; + list-style: none; + -webkit-transition: left 1000ms; + transition: left 1000ms; } + .b2b-boardstrip .board-viewport .board-item { + width: 140px; + height: 80px; + border: 1px solid #ccc; + margin: 0 15px 15px 0; + background-color: #FFFFFF; + border-radius: 3px; + float: left; + overflow: hidden; } + .b2b-boardstrip .board-viewport .board-item:hover, .b2b-boardstrip .board-viewport .board-item:focus { + border: 2px solid #007A3E; + background-color: white; + cursor: pointer; } + .b2b-boardstrip .board-viewport .board-item .board-img { + width: 61px; + height: 40px; + margin: 0 auto; } + .b2b-boardstrip .board-viewport .board-item .board-img img { + max-width: 100%; } + .b2b-boardstrip .board-viewport .board-item .title { + text-align: center; + line-height: 16px; + color: #666; + font-size: 14px; + font-family: "Omnes-ATT-W02"; + padding: 10px 0; } + .b2b-boardstrip .board-viewport .board-item.selected { + background-color: #FFFFFF; + border: 2px solid #0574ac; } + .b2b-boardstrip .board-viewport .board-item .board-caret { + cursor: default; + outline: 0; + position: absolute; + bottom: 7px; } + .b2b-boardstrip .board-viewport .board-item .board-caret .board-caret-indicator { + border-left: 8px solid transparent; + border-right: 8px solid transparent; + border-bottom: 8px solid #999; + width: 0px; + height: 0px; + position: absolute; + left: 61px; + bottom: -7px; } + .b2b-boardstrip .board-viewport .board-item .board-caret .board-caret-arrow-up { + width: 0px; + height: 0px; + border-style: solid; + border-width: 0 8px 8px 8px; + border-color: transparent transparent #FFFFFF transparent; + left: 61px; + position: absolute; } + .b2b-boardstrip .arrow { + font-size: 14px; + cursor: pointer; + color: #0574ac; } + .b2b-boardstrip .arrow:hover { + color: #0574ac; } + .b2b-boardstrip .arrow.disabled { + color: #767676 !important; + cursor: not-allowed; } + .b2b-boardstrip .prev-items { + display: inline-block; + margin-top: auto; + margin-bottom: auto; + margin-right: 15px; + position: absolute; + left: 0; + top: 45px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + -o-user-select: none; + user-select: none; } + .b2b-boardstrip .next-items { + display: inline-block; + margin-top: 30px; + margin-bottom: auto; + margin-left: 10px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + -o-user-select: none; + user-select: none; } + .b2b-boardstrip .centered { + display: table-cell; + text-align: center; + vertical-align: middle; } + .b2b-boardstrip .offscreen-text { + position: fixed; } + +.breadcrumb { + padding: 10px 15px; + height: 40px; + list-style: none; + border-bottom: 1px solid #d2d2d2; + font-size: 1.2rem; + width: 100%; + z-index: 1000; } + +.breadcrumb > li { + position: relative; + display: inline-block; + margin-right: 15px; } + +.breadcrumb > li:after { + font-size: 8px; + margin-right: 0; + right: -8px; + color: #333333; } + +.breadcrumb > li:last-child { + color: #333333; } + +.breadcrumb > li:last-child:after { + content: ""; } + +.breadcrumb li > * { + float: none !important; + margin: 0; } + +.breadcrumb { + padding: 10px 15px !important; } + +/* ARROW */ +/* spanish */ +.datepicker { + background-color: #FFFFFF; + padding: 0; + border-radius: 5px; + direction: ltr; } + .datepicker > div { + display: none; } + .datepicker table { + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + margin: 0 0 0 0; } + .datepicker td { + text-align: center; + display: block; + width: 30px; + height: 30px; + border: none; } + .datepicker td span { + display: block; + width: 23%; + height: 54px; + line-height: 54px; + float: left; + margin: 1%; + cursor: pointer; + border-radius: 4px; } + .datepicker td span:hover { + background: #eeeeee; } + .datepicker td span.disabled { + background: none; + color: #5A5A5A; + cursor: default; } + .datepicker td span.disabled:hover { + background: none; + color: #5A5A5A; + cursor: default; } + .datepicker td span.active { + color: #FFFFFF; + background-color: #0568ae; + border-color: #357ebd; } + .datepicker td span.active:hover { + color: #FFFFFF; + background-color: #0568ae; + border-color: #357ebd; } + .datepicker td span.active.disabled { + color: #FFFFFF; + background-color: #0568ae; + border-color: #357ebd; } + .datepicker th { + text-align: center; + display: block; + width: 30px; + height: 30px; + border: none; } + .datepicker tbody:focus { + outline: none; } + .datepicker td.day { + background-color: transparent; + color: #0568ae; + cursor: pointer; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 16px; + height: 34px; + line-height: 30rem; + margin: -2px -1px 0 0; + overflow: hidden; + text-align: center; + width: 42px; } + .datepicker:focus { + outline: 1px dotted #191919; + outline-offset: -2px; } + .datepicker th[tabindex]:focus { + outline-offset: -15px; } + .datepicker td.day.focused { + background: #ededed; + cursor: pointer; } + .datepicker td.day.focused.active { + background-color: #ededed; + color: #0568ae; } + .datepicker td.disabled { + font-family: "Omnes-ATT-W02"; + color: #5A5A5A; + cursor: default; } + .datepicker td.disabled:hover { + font-family: "Omnes-ATT-W02"; + color: #5A5A5A; + cursor: default; } + .datepicker td.disabled:hover .show-date { + font-family: "Omnes-ATT-W02"; + color: #5A5A5A; } + .datepicker td.disabled .show-date { + font-family: "Omnes-ATT-W02"; + color: #5A5A5A; } + .datepicker td.today { + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today:hover { + color: #FFFFFF; + background-color: #0568ae; + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today:active { + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today:focus { + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today.disabled { + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today.active { + color: #FFFFFF; + background-color: #0568ae; } + .datepicker td.today.active:hover { + color: #FFFFFF; } + .datepicker td.selected { + color: #FFFFFF; + background-color: #959595; } + .datepicker td.selected:hover { + color: #FFFFFF; + background-color: #959595; } + .datepicker td.selected.disabled { + color: #FFFFFF; + background-color: #959595; } + .datepicker td.active:not(.new) { + color: #FFFFFF; + border-color: #357ebd; } + .datepicker td.active:not(.new) .show-date { + color: #0568ae; + font-family: "Omnes-ATT-W02-Medium"; } + .datepicker td.active:hover:not(.new) { + color: #FFFFFF; + border-color: #357ebd; } + .datepicker td.active:hover:not(.new) .show-date { + color: #0568ae; + font-family: "Omnes-ATT-W02-Medium"; } + .datepicker .start-date .show-date { + background-color: #0568ae; + color: #FFFFFF !important; + border-radius: 5px 0 0 5px; + z-index: 1; } + .datepicker .start-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: 20px; + position: absolute; + width: 100%; + z-index: -1; } + .datepicker .between-date .show-date { + background-color: #0568ae; + color: #FFFFFF !important; } + .datepicker .between-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: 0; + position: absolute; + width: 100%; + z-index: -1; } + .datepicker .between-date:first-child .show-date:before { + background-color: #FFFFFF; + content: ""; + height: 26px; + position: absolute; + left: 0; + width: 8px; } + .datepicker .end-date .show-date { + background-color: #0568ae; + color: #FFFFFF !important; + border-radius: 0 5px 5px 0; } + .datepicker .end-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: -20px; + position: absolute; + width: 100%; + z-index: -1; } + .datepicker .end-date:first-child .show-date:after { + background-color: #FFFFFF; + content: ""; + height: 26px; + position: absolute; + left: 0; + width: 8px; } + .datepicker .end-date:first-child .show-date::before { + background-color: #FFFFFF; } + .datepicker tr td.start-date:last-child .show-date:after { + background-color: #FFFFFF; + content: ""; + height: 26px; + position: absolute; + right: 0; + width: 8px; } + .datepicker tr td.start-date:last-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker tr td.start-date:first-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker tr td.between-date:last-child .show-date:after { + background-color: #FFFFFF; + content: ""; + height: 26px; + position: absolute; + right: 0; + width: 8px; } + .datepicker tr td.between-date:last-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker tr td.between-date:first-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker tr td.end-date:last-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker tr td.end-date:first-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + .datepicker th.datepicker-switch { + width: 198px; + font-size: 20px; + font-weight: normal; + cursor: default !important; } + .datepicker thead tr:first-child th { + cursor: pointer; + height: 60px; + line-height: 60px; } + .datepicker thead tr:first-child th.cw { + cursor: default; + background-color: transparent; } + .datepicker tfoot tr th { + cursor: pointer; + height: 60px; + line-height: 60px; + height: auto; + line-height: normal; } + .datepicker tfoot tr th li { + margin-bottom: 5px; } + .datepicker .prev { + color: transparent; + font-size: 0; + margin: 0 -1px -1px 0; + width: 46px; } + .datepicker .prev i { + color: #0568ae; + position: absolute; + font-size: 27px; + margin: 0; + top: 15px; + left: 8px; } + .datepicker .next { + color: transparent; + font-size: 0; + margin: 0 -1px -1px 0; + width: 46px; } + .datepicker .next i { + color: #0568ae; + position: absolute; + font-size: 27px; + margin: 0; + top: 15px; + right: 8px; } + .datepicker .cw { + font-size: 10px; + width: 12px; + padding: 0 2px 0 5px; + vertical-align: middle; } + .datepicker .due-date .show-date { + font-family: "Omnes-ATT-W02-Medium"; + background-color: #cf2a2a; + border-radius: 5px; + color: #FFFFFF !important; } + .datepicker .day.active .show-date:after { + border: 2px solid #0568ae; + border-radius: 7px; + content: ""; + display: block; + height: 30px; + left: 4px; + position: absolute; + top: 0; + width: 30px; } + .datepicker .day:focus .show-date:after { + border: 2px solid #0568ae; + border-radius: 7px; + content: ""; + display: block; + height: 30px; + left: 4px; + position: absolute; + top: 0; + width: 30px; + height: 30px; + left: 4px; + top: 0; + width: 30px; } + .datepicker .due-date.disabled .show-date:after { + border: 2px solid #0568ae; + border-radius: 7px; + content: ""; + display: block; + height: 30px; + left: 4px; + position: absolute; + top: 0; + width: 30px; } + .datepicker .day.due-date:focus .show-date:after { + height: 30px; + left: 4px; + top: 0; + width: 30px; } + .datepicker .due-date.old:after { + visibility: hidden; } + .datepicker .due-date.new:after { + visibility: hidden; } + .datepicker .due-date.active:after { + border-color: #FFFFFF; } + .datepicker .due-date.active.focused { + color: #0568ae !important; } + .datepicker .due-date.active.focused:after { + border-color: #cf2a2a !important; } + .datepicker .dow { + height: 24px; + width: 42px; + font-weight: normal; + position: relative; + overflow: hidden; + color: transparent; + letter-spacing: -6px; + margin: 0 -1px -1px 0; } + .datepicker .dow span[aria-hidden="true"] { + bottom: 0; + color: #5A5A5A; + display: block; + left: 1px; + letter-spacing: 0; + line-height: .9; + margin: 0 auto; + padding: 0; + position: relative; + width: 22px; } + .datepicker .calendar-legend { + margin-top: 3px; + margin-bottom: 20px; } + .datepicker .calendar-legend li { + font-size: 1.4rem; + font-weight: normal; + margin-bottom: 5px; + padding-left: 10px; + padding-top: 5px; + position: relative; } + .datepicker i.legend-due-date { + background-color: #cf2a2a; + border-radius: 5px; + height: 18px; + width: 18px; + margin-right: 8px; + vertical-align: middle; + display: inline-block; } + .datepicker i.legend-selected-date { + background-color: #FFFFFF; + border: 2px solid #0568ae; + border-radius: 5px; + height: 18px; + width: 18px; + margin-right: 8px; + vertical-align: middle; + display: inline-block; } + .datepicker i.legend-selectedisdue { + background-color: #FFFFFF; + border: 2px solid #0568ae; + border-radius: 5px; + display: inline-block; + height: 18px; + margin-right: 8px; + position: relative; + vertical-align: middle; + width: 18px; } + .datepicker i.legend-selectedisdue:after { + background-color: #cf2a2a; + border-radius: 3px; + content: ""; + display: block; + height: 10px; + left: 2px; + position: absolute; + top: 2px; + width: 10px; } + .datepicker .text-left { + width: 100%; } + .datepicker .active.old { + background-color: #ededed !important; + color: #ededed !important; } + +.datepicker-inline { + width: 220px; } + +.datepicker.datepicker-rtl { + direction: rtl; } + .datepicker.datepicker-rtl td span { + float: right; } + +.datepicker-dropdown { + top: 0; + left: 0; } + .datepicker-dropdown:before { + content: " "; + display: inline-block; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-bottom: 10px solid #d2d2d2; + border-top: 0; + border-bottom-color: rgba(0, 0, 0, 0.2); + position: absolute; } + .datepicker-dropdown:after { + content: " "; + display: inline-block; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-bottom: 10px solid #fff; + border-top: 0; + position: absolute; } + +.datepicker-dropdown.datepicker-orient-left:before { + left: 16px; } + +.datepicker-dropdown.datepicker-orient-left:after { + left: 16px; } + +.datepicker-dropdown.datepicker-orient-right:before { + right: 16px; } + +.datepicker-dropdown.datepicker-orient-right:after { + right: 16px; } + +.datepicker-dropdown.datepicker-orient-top:before { + top: -10px; } + +.datepicker-dropdown.datepicker-orient-top:after { + top: -9px; } + +.datepicker-dropdown.datepicker-orient-bottom:before { + bottom: -7px; + border-bottom: 0; + border-top: 7px solid #959595; } + +.datepicker-dropdown.datepicker-orient-bottom:after { + bottom: -6px; + border-bottom: 0; + border-top: 6px solid #fff; } + +.datepicker.days div.datepicker-days { + display: block; } + +.datepicker.months div.datepicker-months { + display: block; } + +.datepicker.years div.datepicker-years { + display: block; } + +.show-date { + font-family: "Omnes-ATT-W02-Medium"; + color: #0568ae; + height: 26px; + line-height: 26px; + margin: 4px auto 0; + width: 26px; } + +.input-group.date .input-group-addon i { + cursor: pointer; + width: 16px; + height: 16px; } + +.datepicker.dropdown-menu { + box-shadow: 0 10px 15px -10px rgba(0, 0, 0, 0.7); + position: absolute; + top: 100%; + left: 0; + float: left; + display: none; + margin-top: 13px; + width: 290px; + list-style: none; + background-color: #FFFFFF; + border: 1px solid #d2d2d2; + border: 1px solid rgba(0, 0, 0, 0.2); + border-radius: 5px; + color: #333333; + font-size: 13px; + line-height: 1.428571429; + z-index: 1050; } + .datepicker.dropdown-menu th { + display: block; + float: left; + padding: 0; + position: relative; } + .datepicker.dropdown-menu td { + display: block; + float: left; + padding: 0; + position: relative; } + +.s { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: -62px 0; } + +.m { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: -5px 0; } + +.t { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: -19px 0; } + +.w { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: -34px 0; } + +.f { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: -49px 0; } + +.d { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: 0 0; } + +.l { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: 0 0; } + +.v { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: 0 0; } + +.j { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: #FFFFFF; + background-repeat: no-repeat; + background-position: 0 0; } + +.b2b-card-container { + background-color: #f2f2f2; + padding: 10px 10px 10px 14px; } + .b2b-card-container .b2b-card-wid { + padding-bottom: 24px; } + .b2b-card-container .b2b-card-footer-flyout, .b2b-card-container .b2b-card-footer { + float: right; + font-family: Omnes-ATT-W02; + font-size: 16px; + line-height: 20px; + color: #0568ae; } + .b2b-card-container .b2b-card-footer-flyout { + margin-right: -8px; } + .b2b-card-container .b2b-card-header { + padding-bottom: 10px; + font-family: Omnes-ATT-W02-Medium; + font-size: 18px; + line-height: 27px; + color: #191919; + margin-top: -3px; + margin-left: -3px; } + .b2b-card-container .b2b-cards { + padding: 20px 20px 34px 20px; + margin-left: -5px; + margin-bottom: -5px; + background-color: #ffffff; } + .b2b-card-container .b2b-card-content { + padding-bottom: 20px; + font-family: Omnes-ATT-W02-Medium; + font-size: 14px; + line-height: 18px; + color: #191919; + overflow: hidden; } + .b2b-card-container .icon-misc-gripper { + font-size: 30px; + margin-top: -3px; + margin-left: -7px; } + .b2b-card-container .b2b-title { + margin-left: -13px; } + .b2b-card-container .b2b-title-checkbox { + margin-left: 36px; + margin-top: -38px; } + .b2b-card-container .b2b-card-header-checkbox { + margin-top: 0px; + padding-bottom: 15px; + font-size: 18px; + line-height: 27px; + color: #191919; + font-family: Omnes-ATT-W02-Medium; } + .b2b-card-container .checkbox { + font-size: 0px; } + +.b2b-coachmark-label { + z-index: 1060; + opacity: 1; + cursor: not-allowed; + position: relative; } + +.b2b-coachmark-highlight { + border: 1px solid #d3d3d3; + cursor: default; + z-index: 1045; + opacity: 1; + background-color: #ffffff; + border-radius: 10px; + position: relative; + box-shadow: 0 5px 6px 0 rgba(0, 0, 0, 0.25); + padding: 10px; + position: absolute; } + +.b2b-coachmark-highlight-mask { + z-index: 1100; + opacity: .1; } + +.b2b-coachmark-container [class*="icon-misc-"] { + color: #191919; } + +.b2b-coachmark-container { + border: 1px solid #cccccc; + width: 316px; + pointer-events: auto; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + font-size: 16px; + -webkit-transition: opacity .2s ease-out; + -moz-transition: opacity .2s ease-out; + transition: opacity .2s ease-out; + background: #fff; + border-radius: 10px; + box-shadow: 0 6px 6px 0 rgba(0, 0, 0, 0.15); + color: #333; + line-height: 20px; + position: absolute; + top: 50px; + left: -97px; + display: block; + background-color: #ffffff; + z-index: 1050; + opacity: 1; } + .b2b-coachmark-container i.b2b-coachmark-caret { + position: absolute; + top: -12px; + left: 47%; + opacity: 1; + z-index: 1050; } + .b2b-coachmark-container i.b2b-coachmark-caret:before { + content: ""; + border-left: 12px solid transparent; + border-right: 12px solid transparent; + border-bottom: 12px solid #d3d3d3; + position: absolute; + top: -1px; } + .b2b-coachmark-container i.b2b-coachmark-caret:after { + content: ""; + border-left: 12px solid transparent; + border-right: 12px solid transparent; + border-bottom: 12px solid #fff; + position: absolute; } + .b2b-coachmark-container .b2b-coachmark-header { + position: relative; + height: 47px; + overflow: hidden; } + .b2b-coachmark-container .b2b-coachmark-header .corner-button { + box-shadow: 0 -30px 0 0 #f2f2f2 inset; + height: 69px; + position: absolute; + right: -33px; + top: -38px; + transform: rotate(45deg); + width: 69px; } + .b2b-coachmark-container .b2b-coachmark-countlabel { + font-size: 12px; + font-family: "Omnes-ATT-W02"; + color: #333333; + margin-left: 20px; + margin-top: 20px; } + .b2b-coachmark-container .b2b-coachmark-content { + padding: 0px 20px 20px 20px; + float: left; } + .b2b-coachmark-container .b2b-coachmark-content .icon-misc-dimmer { + font-size: 32px; + float: left; + margin-right: 10px; + width: 32px; } + .b2b-coachmark-container .b2b-coachmark-content .offscreen-text { + position: absolute; + left: -10000px; + top: auto; + width: 1px; + height: 1px; + overflow: hidden; } + .b2b-coachmark-container .b2b-coachmark-content .b2b-coachmark-content-header { + font-size: 16px; + color: #333333; + line-height: 18px; + float: left; + width: 220px; + margin-top: 10px; } + .b2b-coachmark-container .b2b-coachmark-content .b2b-coachmark-description { + font-size: 14px; + line-height: 18px; + color: #333333; + width: 100%; + float: left; + margin-top: 15px; } + .b2b-coachmark-container .b2b-coachmark-content .b2b-coachmark-btn-group { + margin-top: 20px; + float: left; + text-align: right; + width: 100%; } + .b2b-coachmark-container .b2b-coachmark-content .b2b-coachmark-btn-group .b2b-coachmark-link { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 15px; + color: #0574ac; + line-height: 18px; + margin-right: 20px; } + .b2b-coachmark-container .b2b-coachmark-content .b2b-coachmark-btn-group button { + font-size: 15px; + margin: 0px; } + +.datepicker { + background-color: #fff; + padding: 0; + border-radius: 5px; + direction: ltr; } + +.datepicker-inline { + width: 220px; } + +.datepicker.datepicker-rtl { + direction: rtl; } + +.datepicker.datepicker-rtl td span { + float: right; } + +.datepicker-dropdown { + top: 0; + left: 0; } + +/* ARROW */ +.datepicker-dropdown:before { + content: " "; + display: inline-block; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-bottom: 10px solid #d2d2d2; + border-top: 0; + border-bottom-color: rgba(0, 0, 0, 0.2); + position: absolute; } + +.datepicker-dropdown:after { + content: " "; + display: inline-block; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-bottom: 10px solid #fff; + border-top: 0; + position: absolute; } + +.datepicker-dropdown.datepicker-orient-left:before, +.datepicker-dropdown.datepicker-orient-left:after { + left: 255px; } + +.datepicker-dropdown.datepicker-orient-right:before, +.datepicker-dropdown.datepicker-orient-right:after { + right: 16px; } + +.datepicker-dropdown.datepicker-orient-top:before { + top: -10px; } + +.datepicker-dropdown.datepicker-orient-top:after { + top: -9px; } + +.datepicker-dropdown.datepicker-orient-bottom:before { + bottom: -7px; + border-bottom: 0; + border-top: 7px solid #959595; } + +.datepicker-dropdown.datepicker-orient-bottom:after { + bottom: -6px; + border-bottom: 0; + border-top: 6px solid #fff; } + +.datepicker > div { + display: none; } + +.datepicker.days div.datepicker-days { + display: block; } + +.datepicker.months div.datepicker-months { + display: block; } + +.datepicker.years div.datepicker-years { + display: block; } + +.datepicker table { + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + margin: 0 0 0 0; } + +.datepicker td, +.datepicker th { + text-align: center; + display: block; + width: 30px; + height: 30px; + border: none; } + +.datepicker tbody :focus { + outline: none; } + +.datepicker td.day { + background-color: transparent; + color: #0568ae; + cursor: pointer; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 16px; + height: 34px; + line-height: 30rem; + margin: -2px -1px 0 0; + overflow: hidden; + text-align: center; + width: 42px; } + +.datepicker :focus { + outline: 1px dotted #000; + outline-offset: -2px; } + +.datepicker td.day.focused { + background: #ededed; + cursor: pointer; } + +.datepicker td.day.focused.active { + background-color: #ededed; + color: #0568ae; } + +.datepicker td.disabled, +.datepicker td.disabled:hover { + font-family: "Omnes-ATT-W02"; + color: #5a5a5a; + cursor: default; } + +.datepicker td.today, +.datepicker td.today:hover, +.datepicker td.today.disabled { + color: #fff; + background-color: #0568ae; } + +.datepicker td.today.active, +.datepicker td.today:active, +.datepicker td.today:hover, +.datepicker td.today:focus { + color: #fff; + background-color: #0568ae; } + +.datepicker td.today.active:hover { + color: #fff; } + +.datepicker td.selected, +.datepicker td.selected:hover, +.datepicker td.selected.disabled { + color: #ffffff; + background-color: #959595; } + +.datepicker td.active:not(.new), +.datepicker td.active:hover:not(.new) { + color: #ffffff; + border-color: #357ebd; } + +.show-date { + font-family: "Omnes-ATT-W02-Medium"; + color: #0568ae; + height: 26px; + line-height: 26px; + margin: 4px auto 0; + width: 26px; } + +.datepicker .start-date .show-date, +.datepicker .between-date .show-date, +.datepicker .end-date .show-date { + background-color: #0568ae; + color: #fff !important; } + +.datepicker .start-date .show-date { + border-radius: 5px 0 0 5px; + z-index: 1; } + +.datepicker .start-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: 20px; + position: absolute; + width: 100%; + z-index: -1; } + +.datepicker .between-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: 0; + position: absolute; + width: 100%; + z-index: -1; } + +.datepicker .end-date .show-date { + border-radius: 0 5px 5px 0; } + +.datepicker .end-date .show-date:before { + background-color: #0568ae; + content: ""; + display: block; + height: 26px; + left: -20px; + position: absolute; + width: 100%; + z-index: -1; } + +.datepicker .between-date:first-child .show-date:before { + background-color: #fff; + content: ""; + height: 26px; + position: absolute; + left: 0; + width: 8px; } + +.datepicker .end-date:first-child .show-date:after { + background-color: #fff; + content: ""; + height: 26px; + position: absolute; + left: 0; + width: 8px; } + +.datepicker .end-date:first-child .show-date::before { + background-color: #fff; } + +.datepicker tr td.start-date:last-child .show-date:after, +.datepicker tr td.between-date:last-child .show-date:after { + background-color: #fff; + content: ""; + height: 26px; + position: absolute; + right: 0; + width: 8px; } + +.datepicker tr td.start-date:last-child:focus .show-date:after, +.datepicker tr td.end-date:last-child:focus .show-date:after, +.datepicker tr td.between-date:last-child:focus .show-date:after, +.datepicker tr td.start-date:first-child:focus .show-date:after, +.datepicker tr td.end-date:first-child:focus .show-date:after, +.datepicker tr td.between-date:first-child:focus .show-date:after { + height: 30px; + width: 30px; + background-color: transparent; } + +.datepicker td.active:not(.new) .show-date, +.datepicker td.active:hover:not(.new) .show-date { + color: #0568ae; + font-family: "Omnes-ATT-W02-Medium"; } + +.datepicker td.disabled .show-date, +.datepicker td.disabled:hover .show-date { + font-family: "Omnes-ATT-W02"; + color: #5a5a5a; } + +.datepicker td span { + display: block; + width: 23%; + height: 54px; + line-height: 54px; + float: left; + margin: 1%; + cursor: pointer; + border-radius: 4px; } + +.datepicker td span:hover { + background: #eeeeee; } + +.datepicker td span.disabled, +.datepicker td span.disabled:hover { + background: none; + color: #5a5a5a; + cursor: default; } + +.datepicker td span.active, +.datepicker td span.active:hover, +.datepicker td span.active.disabled { + color: #ffffff; + background-color: #0568ae; + border-color: #357ebd; } + +.datepicker th.datepicker-switch { + width: 198px; + font-size: 20px; + font-weight: normal; + cursor: default !important; } + +.datepicker thead tr:first-child th, +.datepicker tfoot tr th { + cursor: pointer; + height: 60px; + line-height: 60px; } + +.datepicker tfoot tr th { + height: auto; + line-height: normal; } + +.datepicker tfoot tr th li { + margin-bottom: 5px; } + +.datepicker .prev, +.datepicker .next { + color: transparent; + font-size: 0; + margin: 0 -1px -1px 0; + width: 46px; } + +.datepicker .prev i, +.datepicker .next i { + color: #0568ae; + position: absolute; + font-size: 27px; + margin: 0; + top: 15px; } + +.datepicker .prev i { + left: 8px; } + +.datepicker .next i { + right: 8px; } + +.datepicker .cw { + font-size: 10px; + width: 12px; + padding: 0 2px 0 5px; + vertical-align: middle; } + +.datepicker thead tr:first-child th.cw { + cursor: default; + background-color: transparent; } + +.input-group.date .input-group-addon i { + cursor: pointer; + width: 16px; + height: 16px; } + +.datepicker.dropdown-menu { + box-shadow: 0 10px 15px -10px rgba(0, 0, 0, 0.7); + position: absolute; + top: 100%; + left: 0; + float: left; + display: none; + margin-top: 13px; + width: 290px; + list-style: none; + background-color: #ffffff; + border: 1px solid #d2d2d2; + border: 1px solid rgba(0, 0, 0, 0.2); + border-radius: 5px; + color: #333333; + font-size: 13px; + line-height: 1.428571429; + z-index: 1050; } + +.datepicker.dropdown-menu th, +.datepicker.dropdown-menu td { + display: block; + float: left; + padding: 0; + position: relative; } + +.datepicker .due-date .show-date { + font-family: "Omnes-ATT-W02-Medium"; + background-color: #cf2a2a; + border-radius: 5px; + color: #fff !important; } + +.datepicker .day.active .show-date:after, +.datepicker .day:focus .show-date:after, +.datepicker .due-date.disabled .show-date:after { + border: 2px solid #0568ae; + border-radius: 7px; + content: ""; + display: block; + height: 30px; + left: 4px; + position: absolute; + top: 0; + width: 30px; } + +.datepicker .day:focus .show-date:after { + height: 30px; + left: 4px; + top: 0; + width: 30px; } + +.datepicker .day.due-date:focus .show-date:after { + height: 30px; + left: 4px; + top: 0; + width: 30px; } + +.datepicker .due-date.old:after, +.datepicker .due-date.new:after { + visibility: hidden; } + +.datepicker .due-date.active:after { + border-color: #fff; } + +.datepicker .due-date.active.focused { + color: #0568ae !important; } + +.datepicker .due-date.active.focused:after { + border-color: #cf2a2a !important; } + +.datepicker .dow { + height: 24px; + width: 42px; + font-weight: normal; + position: relative; + overflow: hidden; + color: transparent; + letter-spacing: -6px; + margin: 0 -1px -1px 0; } + +.datepicker .dow span[aria-hidden="true"] { + bottom: 0; + color: #5a5a5a; + display: block; + left: 1px; + letter-spacing: 0; + line-height: .9; + margin: 0 auto; + padding: 0; + position: relative; + width: 22px; } + +.datepicker .calendar-legend { + margin-top: 3px; + margin-bottom: 20px; } + +.datepicker .calendar-legend li { + font-size: 1.4rem; + font-weight: normal; + margin-bottom: 5px; + padding-left: 10px; + padding-top: 5px; + position: relative; } + +.datepicker i.legend-due-date { + background-color: #cf2a2a; + border-radius: 5px; + height: 18px; + width: 18px; + margin-right: 8px; + vertical-align: middle; + display: inline-block; } + +.datepicker i.legend-selected-date { + background-color: #fff; + border: 2px solid #0568ae; + border-radius: 5px; + height: 18px; + width: 18px; + margin-right: 8px; + vertical-align: middle; + display: inline-block; } + +.datepicker i.legend-selectedisdue { + background-color: #fff; + border: 2px solid #0568ae; + border-radius: 5px; + display: inline-block; + height: 18px; + margin-right: 8px; + position: relative; + vertical-align: middle; + width: 18px; } + +.datepicker i.legend-selectedisdue:after { + background-color: #cf2a2a; + border-radius: 3px; + content: ""; + display: block; + height: 10px; + left: 2px; + position: absolute; + top: 2px; + width: 10px; } + +.datepicker .text-left { + width: 100%; } + +.datepicker .active.old { + background-color: #ededed !important; + color: #ededed !important; } + +.s, +.m, +.t, +.w, +.f, +.d, +.l, +.v, +.j { + display: block; + height: 20px; + width: 12px; + margin: 0 auto; + background-color: white; + background-repeat: no-repeat; } + +.s { + background-position: -62px 0; } + +.m { + background-position: -5px 0; } + +.t { + background-position: -19px 0; } + +.w { + background-position: -34px 0; } + +.f { + background-position: -49px 0; } + +/* spanish */ +.d { + background-position: 0 0; } + +.l { + background-position: 0 0; } + +.v { + background-position: 0 0; } + +.j { + background-position: 0 0; } + +.datepicker-container { + position: relative; } + +.btn-calendar-icon:focus .icon-calendar { + outline: 1px dotted #191919; } + +.btn-calendar-icon:focus { + outline: none; } + +/* remove focus outline when dropdown is opened */ +/*resolve blue focus outline over dropdown with error*/ +select { + margin-right: -1; + max-width: 100%; + height: 36px; + line-height: 25px; + width: auto; + background-color: #FFFFFF; } + +.selectWrap.disabled .icon-down { + color: #767676; } + +.selectWrap.disabled input.awd-select { + z-index: 0; + padding: 10px 45px 10px 15px; + text-indent: 0; } + +.selectWrap.disabled button.awd-select { + z-index: 0; + text-indent: 15px; } + +.selectWrap.disabled:after { + color: #5A5A5A; + cursor: not-allowed; } + +input.awd-select { + background-color: transparent; + border: 1px solid #d2d2d2; + border-radius: 6px; + box-shadow: 1px 5px 2px -5px rgba(0, 0, 0, 0.15); + color: #333333; + display: block; + font-family: "Omnes-ATT-W02"; + font-size: 1.6rem; + height: 36px; + line-height: 0; + margin-bottom: 0; + position: relative; + text-align: left; + top: 0; + width: 100%; + z-index: 10; + padding: 12px 45px 8px 15px; + user-select: none; } + input.awd-select:focus { + border-color: #0568ae !important; + text-overflow: ellipsis; + padding-right: 45px; } + +button.awd-select { + background-color: transparent; + border: 1px solid #d2d2d2; + border-radius: 6px; + box-shadow: 1px 5px 2px -5px rgba(0, 0, 0, 0.15); + color: #333333; + display: block; + font-family: "Omnes-ATT-W02"; + font-size: 1.6rem; + height: 36px; + line-height: 36px; + margin-bottom: 0; + position: relative; + text-align: left; + top: 0; + width: 100%; + z-index: 10; } + button.awd-select:not(.large) { + text-indent: 15px; + white-space: nowrap; + overflow: hidden; + text-overflow: clip; + text-overflow: ellipsis; } + button.awd-select img { + height: 26px; + margin-right: 7px; + margin-top: -10px; + position: relative; + top: 2px; + vertical-align: text-bottom; } + button.awd-select:focus { + border-color: #0568ae !important; } + button.awd-select i { + font-size: 23px; + position: absolute; + right: 33px; + top: 5px; + z-index: 1000; } + +button.awd-select.large { + align-items: center; + display: flex; + height: 60px; + line-height: 20px; + overflow: hidden; + padding-left: 70px; + vertical-align: middle; } + button.awd-select.large img { + height: 40px; + left: 20px; + position: absolute; + top: 20px; + width: 40px; } + +.selectWrap.large { + height: 60px; } + .selectWrap.large .awd-select-list-item { + align-items: center; + display: flex; + height: 60px; + line-height: 20px; + overflow: hidden; + padding-left: 70px; + vertical-align: middle; } + .selectWrap.large .awd-select-list-item img { + height: 40px; + left: 20px; + position: absolute; + top: 20px; + width: 40px; + top: 10px; } + +button.awd-select.active { + border-radius: 6px 6px 0 0; } + button.awd-select.active:focus { + border-color: #d2d2d2 !important; } + +input.awd-select.active { + border-radius: 6px 6px 0 0; } + input.awd-select.active:focus { + border-color: #d2d2d2 !important; } + +.selectWrapper { + position: relative; } + +span.selectWrap input[readonly]:focus { + color: transparent; + text-shadow: 0 0 0 #000; } + +.isIE.ds2-no-colors .awd-select:focus { + outline: 1px dashed transparent; } + +.awd-select-list { + box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.15); + border-radius: 0 0 6px 6px; + position: absolute; + border: 1px solid #d2d2d2; + border-top: 0; + padding: 0; + background-color: #f2f2f2; + z-index: 1000; + width: 100%; + max-height: 320px; + overflow-y: auto; } + +.awd-select-list-item { + cursor: pointer; + height: 100%; + min-height: 36px; + line-height: 20px; + overflow: hidden; + padding: 8px 15px; + position: relative; + z-index: 1000; } + .awd-select-list-item:hover { + cursor: pointer; + background-color: #d2d2d2; + outline: 1px dashed transparent; } + .awd-select-list-item:focus { + cursor: pointer; + background-color: #d2d2d2; + outline: 1px dashed transparent; } + .awd-select-list-item img { + margin-top: 0; + margin-right: 7px; + height: 26px; + width: 26px; } + +.selectWrap { + border-radius: 6px; + position: relative; + height: 36px; + line-height: 28px; + display: block; + margin: 0; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="@att-gray-highlight", endColorstr="@att-functional-bg-gray", GradientType=0); } + .selectWrap:not(.large) .awd-select-list-item:first-child { + margin-top: 15px; } + .selectWrap:not(.large) .awd-select-list-item:last-child { + margin-bottom: 15px; } + .selectWrap .icon-down { + font-size: 23px; + margin-top: -11px; + position: absolute; + right: 4px; + top: 50%; } + .selectWrap + [aria-expanded="true"] { + padding-bottom: 9px; + padding-top: 20px; } + +.awd-select-list-item[data-hover="true"] { + background-color: #d2d2d2; } + +span input.awd-select { + width: 100%; + cursor: pointer; + text-overflow: ellipsis; + padding-right: 45px; } + +li.optgroup-wrapper { + font-family: "Omnes-ATT-W02-Medium"; + cursor: default !important; + padding: 0px 15px; } + li.optgroup-wrapper:first-child { + padding-top: 10px; } + li.optgroup-wrapper:hover { + background-color: #f2f2f2; } + +ul.optgroup { + font-family: "Omnes-ATT-W02"; + cursor: pointer !important; + margin: 0 -15px; } + ul.optgroup li { + padding: 9px 0 0 33px; } + +label + .selectWrap { + margin-top: 4px; } + +.selectorModule { + border-radius: 6px; + position: relative; + height: 36px; + line-height: 28px; + display: block; + margin: 0; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="@att-gray-highlight", endColorstr="@att-functional-bg-gray", GradientType=0); } + +.group .selectWrap { + margin: 0 0 10px 0; } + +select.awd-select { + position: relative; + top: 0; + left: 0; + font-size: 16px; + z-index: 1010; + height: 33px; + min-width: 100%; + opacity: 0.01; } + select.awd-select > optgroup { + padding-left: 8px; + font-style: normal; + margin-top: 10px; } + select.awd-select > optgroup:first-child { + margin-top: 0; } + select.awd-select > optgroup > option { + padding-left: 8px; } + select.awd-select > option { + padding-left: 8px; } + select.awd-select + span { + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="@att-gray-highlight", endColorstr="@att-functional-bg-gray", GradientType=0); + position: absolute; + top: 0; + left: 0; + z-index: 0; + display: block; + border: 1px solid #d2d2d2; + border-radius: 6px; + height: 35px; + line-height: 0; + padding: 18px 45px 15px 15px; + width: 100%; + font-size: 1.6rem; + padding-right: 45px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } + select.awd-select + span > i { + font-size: 23px; + position: absolute; + right: 33px; + top: 5px; + z-index: 1000; } + select.awd-select + span > i:before { + left: 1px; + position: absolute; + top: -1px; } + select.awd-select:focus + span { + border-color: #0568ae; } + +.isIE select.awd-select + span { + line-height: 1; } + +[data-default-option="true"] { + color: #767676 !important; + font-family: "Omnes-ATT-W02-Italic"; } + +.placeholdercolor { + color: #767676 !important; + font-family: "Omnes-ATT-W02-Italic"; } + +.filterTank button.awd-select { + border-color: #d2d2d2; + background-color: #333333; + color: #FFFFFF; + color: #333333; } + .filterTank button.awd-select:after { + background-color: #FFFFFF !important; + border-color: #d2d2d2; } + +.utility-bg button.awd-select { + border-color: #d2d2d2; + background-color: #333333; + color: #FFFFFF; + color: #333333; } + .utility-bg button.awd-select:after { + background-color: #FFFFFF !important; + border-color: #d2d2d2; } + +.utility-bg select.awd-select + span { + border-color: #d2d2d2; + border-color: #d2d2d2; + background-color: #333333; + background-color: #333333; + color: #FFFFFF; + color: #FFFFFF; } + .utility-bg select.awd-select + span:after { + background-color: #FFFFFF !important; + background-color: #FFFFFF !important; + border-color: #d2d2d2; + border-color: #d2d2d2; } + +.utility-bg select.awd-select:focus + span { + border-color: #d2d2d2; + border-color: #d2d2d2; + background-color: #333333; + background-color: #333333; + color: #FFFFFF; + color: #FFFFFF; } + .utility-bg select.awd-select:focus + span:after { + background-color: #FFFFFF !important; + background-color: #FFFFFF !important; + border-color: #d2d2d2; + border-color: #d2d2d2; } + +.utility-bg select.awd-select:hover + span { + border-color: #d2d2d2; + border-color: #d2d2d2; + background-color: #333333; + background-color: #333333; + color: #FFFFFF; + color: #FFFFFF; } + .utility-bg select.awd-select:hover + span:after { + background-color: #FFFFFF !important; + background-color: #FFFFFF !important; + border-color: #d2d2d2; + border-color: #d2d2d2; } + +input.awd-select[disabled] { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + input.awd-select[disabled] + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + +button.awd-select[disabled] { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + button.awd-select[disabled]:after { + background-color: #d2d2d2 !important; + border-color: #d2d2d2; } + +select.awd-select[disabled] + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + select.awd-select[disabled] + span:after { + background-color: #d2d2d2 !important; + border-color: #d2d2d2; } + +select.awd-select[disabled]:focus + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + +select.awd-select[disabled]:hover + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + +input.awd-select[disabled="disabled"] { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + input.awd-select[disabled="disabled"] + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + +select.awd-select[disabled="disabled"] + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + select.awd-select[disabled="disabled"] + span:after { + background-color: #d2d2d2 !important; + border-color: #d2d2d2; } + +select.awd-select[disabled="disabled"]:focus + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + select.awd-select[disabled="disabled"]:focus + span:after { + background-color: #d2d2d2 !important; + border-color: #d2d2d2; } + +select.awd-select[disabled="disabled"]:hover + span { + cursor: not-allowed; + border-color: #d2d2d2; + background-color: #d2d2d2; + background-image: none; + color: #5A5A5A; } + select.awd-select[disabled="disabled"]:hover + span:after { + background-color: #d2d2d2 !important; + border-color: #d2d2d2; } + +.ddexpand-wrapper > h2 { + margin-bottom: 11px; } + .ddexpand-wrapper > h2 + p { + margin-bottom: 4px; } + +.ddexpand-wrapper .selectWrap + [aria-expanded="true"] .form-row { + margin-top: 11px; } + +.ddexpand-wrapper .selectWrap + [aria-expanded="true"] .row + .row .form-row { + margin-top: 14px; } + +.form-row.error button.awd-select.active:focus { + border-color: #cf2a2a !important; } + +.form-row.error input.awd-select.active:focus { + border-color: #cf2a2a !important; } + +.awd-module-list .module-list-item[aria-selected="true"] { + background-color: #f2f2f2; } + +li.module-list-item[aria-selected="true"]:before { + color: #0568ae; + display: inline-block; + font-family: "icoControls" !important; + font-style: normal; + font-size: 20px; + font-weight: normal; + font-variant: normal; + height: 1em; + margin-right: 7px; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + position: relative; + speak: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + vertical-align: middle; + width: 1em; + content: "\e907"; + box-sizing: border-box; + display: inline-block; + font-size: 2em; + height: 1em; + position: absolute; + top: 20px; + right: 0px; + vertical-align: middle; + width: 1em; + color: #007a3e; } + +@media (min-width: 768px) { + span[class*="large"] { + max-width: 370px; } + .large { + max-width: 370px; } } + +@media (max-width: 767px) { + .selectWrap.large:after { + right: 5px; } + .selectWrap.large .awd-select-list-item { + padding-right: 41px; } + .selectWrap + div > h4 { + margin-bottom: 0; + font-size: 16px; } } + +.modalwrapper:not(.modal-docked) .b2b-dropdown-desktop-list { + max-height: 200px; } + +/**********************Dropdown Chrome scrolling fix start ********************/ +input.awd-select { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; } + +/**********************Dropdown Chrome scrolling fix end ********************/ +.mpc-expanders { + border-bottom: 1px solid #e4e4e4; + border-top: 1px solid #e4e4e4; } + +.mpc-expanders + .mpc-expanders { + border-top: 0px; } + +.mpc-expanders .heading-medium { + margin-bottom: 10px; } + +.mpc-expanders .p-small { + margin-top: 5px; } + +.mpc-expander-body { + border-top: 1px solid #e4e4e4; } + +.mpc-expander-body .mpc-expanders { + border-bottom: 1px solid #e4e4e4; + border-top: 0; } + +.mpc-expander-body .mpc-expanders:last-child { + border-bottom: 0px; } + +.ddh-blue { + color: #0574ac; } + +.b2b-dragdrop { + border: 1px dashed #d2d2d2; + border-radius: 5px; + padding: 30px 20px 18px 20px; + text-align: center; + color: #191919; + font-size: 16px; + font-weight: normal; + position: relative; + font-family: "Omnes-ATT-W02-Medium"; } + +.b2b-dragdrop-over { + background: #0091d9; + color: #006496; } + .b2b-dragdrop-over:after { + content: "Drop the file"; + color: #fff; + width: 80px; + height: 20px; + overflow: hidden; + margin: auto; + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; } + +.b2b-file-container { + position: relative; + overflow: hidden; + display: inline-table; + font-weight: 400; } + .b2b-file-container [type=file] { + position: absolute; + cursor: inherit; + display: block; + font-size: 0; + opacity: 0; + height: 0; + width: 0; + left: 0; + top: 0; + -ms-filter: "alpha(Opacity=0)"; } + +.b2b-upload-link { + color: #0568ae; + font-size: 16px; + font-weight: normal; } + +.b2b-flyout { + position: relative; + display: inline-block; + cursor: default; } + +.b2b-flyout-icon { + cursor: pointer; } + .b2b-flyout-icon:focus { + outline: thin dotted #666; + outline-offset: -1px; } + +*[b2b-flyout-toggler] { + cursor: pointer; } + +.b2b-flyout .b2b-flyout-container { + border: 1px solid #d3d3d3; + width: 300px; + padding: 20px; + pointer-events: auto; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + font-size: 16px; + -webkit-transition: opacity .2s ease-out; + -moz-transition: opacity .2s ease-out; + transition: opacity .2s ease-out; + background: #fff; + border-radius: 6px; + box-shadow: 0 5px 6px 0 rgba(0, 0, 0, 0.25); + color: #333; + line-height: 20px; + position: absolute; + top: 35px; + opacity: 0; + z-index: 1010; + display: none; } + .b2b-flyout .b2b-flyout-container.open-flyout { + opacity: 1; + display: block; } + +.b2b-flyout i.b2b-flyout-caret { + position: absolute; + top: -8px; + left: 50%; + opacity: 0; + z-index: 1011; + display: none; } + .b2b-flyout i.b2b-flyout-caret.open-flyout { + opacity: 1; + display: block; } + .b2b-flyout i.b2b-flyout-caret:before { + content: ""; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + border-bottom: 8px solid #d3d3d3; + position: absolute; + top: -1px; } + .b2b-flyout i.b2b-flyout-caret:after { + content: ""; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + border-bottom: 8px solid #fff; + position: absolute; } + +.b2b-flyout .b2b-flyout-container.b2b-flyout-left i.b2b-flyout-caret { + left: 16px !important; } + +.b2b-flyout .b2b-flyout-container.b2b-flyout-right i.b2b-flyout-caret { + left: inherit !important; + right: 30px !important; } + +.b2b-flyout .b2b-flyout-container.b2b-flyout-above { + box-shadow: 0 -5px 6px 0 rgba(0, 0, 0, 0.25); } + .b2b-flyout .b2b-flyout-container.b2b-flyout-above i.b2b-flyout-caret { + top: auto; + bottom: 0px; } + .b2b-flyout .b2b-flyout-container.b2b-flyout-above i.b2b-flyout-caret:before { + top: auto; + bottom: -9px; + border-top: 8px solid #d3d3d3; + border-bottom: none; } + .b2b-flyout .b2b-flyout-container.b2b-flyout-above i.b2b-flyout-caret:after { + border-top: 8px solid #fff; + border-bottom: none; } + +.b2b-flyout .b2b-flyout-container.b2b-flyout-centerLeft i.b2b-flyout-caret { + left: inherit !important; + right: -7px !important; + top: 8px; + transform: rotate(90deg); } + +.b2b-flyout .b2b-flyout-container.b2b-flyout-centerRight i.b2b-flyout-caret { + left: -8px !important; + top: 296px; + transform: rotate(-90deg); } + +.b2b-flyout .buttons-group { + margin-top: 20px; } + .b2b-flyout .buttons-group .cta-button-group { + width: 100%; + border-top: 1px solid #ccc; + padding: 20px 0 0; } + .b2b-flyout .buttons-group .cta-button-group button { + margin-bottom: 0; } + +.b2b-flyout .heading { + font-size: 20px; + margin-bottom: 10px; } + +.b2b-flyout .body-text { + font-size: 14px; + margin-bottom: 30px; } + +.b2b-footer-wrapper { + width: 100%; + background-color: #222; } + +.b2b-footer-container { + width: 980px; + margin: 0 auto; + padding-top: 15px; } + .b2b-footer-container .footer-columns { + display: inline-block; + text-align: left; + vertical-align: top; } + .b2b-footer-container .footer-columns.three-column, .b2b-footer-container .footer-columns.four-column, .b2b-footer-container .footer-columns.five-column { + padding-top: 25px; } + .b2b-footer-container .footer-columns.three-column { + width: 33.3%; } + .b2b-footer-container .footer-columns.four-column { + width: 25%; } + .b2b-footer-container .footer-columns.five-column { + width: 20%; } + .b2b-footer-container .footer-columns .b2b-footer-header { + color: #ffffff; + font-size: 18px; + font-style: normal; + font-family: "Omnes-ATT-W02-Medium"; + margin: 0; } + .b2b-footer-container .footer-columns li { + width: 66%; + padding: 5px 0; } + .b2b-footer-container .footer-columns ul li:first-child { + padding-top: 20px; } + .b2b-footer-container .footer-columns li a { + color: #71c5e8; + font-size: 16px; + font-family: "Omnes-ATT-W02"; } + .b2b-footer-container .footer-nav-content { + padding-bottom: 1px; } + .b2b-footer-container .footer-nav-content li { + display: inline; + font-size: 14px; + color: #fff; + vertical-align: middle; } + .b2b-footer-container .footer-nav-content li a { + color: #fff; + font-size: 14px; + vertical-align: middle; + font-family: "Omnes-ATT-W02"; + padding: 0px 8px; } + .b2b-footer-container .footer-nav-content li:first-child a { + padding-left: 0px; } + +.b2b-footer-wrapper .b2b-footer-container hr { + background: #d2d2d2; + margin-top: 40px; } + +.b2b-footer-wrapper .divider-bottom-footer { + padding: 10px 0 55px 0; } + +.b2b-footer-wrapper .b2b-footer-top-bar { + height: 5px; + background-color: #009FDB; } + +.b2b-footer-wrapper .footerLogo { + vertical-align: top; + margin-top: 10px; } + .b2b-footer-wrapper .footerLogo div { + display: inline-table; } + .b2b-footer-wrapper .footerLogo .icon-att-globe { + font-size: 40px; } + .b2b-footer-wrapper .footerLogo img { + height: 36px; } + .b2b-footer-wrapper .footerLogo .logo-title { + color: #fff; + margin-left: 10px; + display: inline-block; + font-size: 26px; + margin-top: 0px; } + +.b2b-footer-wrapper .copyright-text { + color: #fff; + font-size: 11px; + text-align: left; + font-family: "Omnes-ATT-W02"; } + .b2b-footer-wrapper .copyright-text a { + color: #fff; + text-decoration: underline; + display: inline-block; } + .b2b-footer-wrapper .copyright-text a:hover { + text-decoration: none; } + +.b2b-footer-wrapper .footer-logo { + margin-left: 14%; + position: relative; + top: 14px; } + +@media (max-width: 768px) { + .b2b-footer-container { + padding: 0 20px; + width: 100%; } + .b2b-footer-container .footer-columns.three-column, .b2b-footer-container .footer-columns.four-column, .b2b-footer-container .footer-columns.five-column { + width: 50%; } + .b2b-footer-wrapper .divider-bottom-footer { + padding-top: 15px; } + .b2b-footer-wrapper .divider-bottom-footer .footer-links { + width: 100%; } + .b2b-footer-wrapper .footerLogo { + margin: 30px 0 0 0; } + .b2b-footer-wrapper .footerLogo .footer-logo { + margin: 0; + padding-left: 10px; } } + +.b2b-header-tabs { + background-color: #222; + width: 100%; + position: relative; + height: 45px; } + .b2b-header-tabs .icon-att-globe { + color: #0568ae; } + .b2b-header-tabs a:focus { + border: 1px solid white; } + .b2b-header-tabs .header__items { + width: 980px; + margin: 0 auto; + display: block; + list-style: none; + padding: 6px 0px 0px 0px; + border-spacing: 30px 0; } + .b2b-header-tabs .header__item { + display: inline-block; + text-align: left; + width: auto; + font-size: 16px; + font-family: "Omnes-ATT-W02"; + cursor: pointer; + padding: 5px 15px; + color: #fff; } + .b2b-header-tabs .header__item.b2b-headermenu { + padding: 0; } + .b2b-header-tabs .header__item.b2b-headermenu:last-child { + background: none; } + .b2b-header-tabs .header__item.b2b-headermenu a.menu__item { + color: #fff; + text-decoration: none; + display: inline-block; + padding: 5px 15px; } + .b2b-header-tabs .header__item.active { + background-color: #fff; + border-radius: 2px; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + .b2b-header-tabs .header__item.active a.menu__item { + color: #0578ae; } + .b2b-header-tabs li:focus { + outline: 2px solid #0578ae; } + .b2b-header-tabs .header__item .header-secondary-wrapper, .b2b-header-tabs .header__item .header-tertiary-wrapper { + background-color: #fff; + position: absolute; + width: 100%; + left: 0; + top: 42px; + border-bottom: solid 1px #ccc; + -webkit-box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + -moz-box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + display: none; + z-index: 111; + cursor: initial; } + .b2b-header-tabs .header-secondary, .b2b-header-tabs .header-tertiary { + background-color: #fff; + width: 980px; + margin: 0 auto; } + .b2b-header-tabs .header__item.active .header-secondary-wrapper { + display: block; } + .b2b-header-tabs .header-secondary .header-subitem { + display: inline-block; + width: auto; + margin: 0 15px; } + .b2b-header-tabs .header-secondary .header-subitem.active .header-tertiary-wrapper { + display: block; } + .b2b-header-tabs .header-secondary .header-subitem a.menu__item { + display: inline-block; + padding: 15px 0; + color: #333; } + .b2b-header-tabs .header-secondary .header-subitem a.menu__item:hover, .b2b-header-tabs .header-secondary .header-subitem a.menu__item:focus { + color: #0578ae; } + +/** Secondary Menu **/ +.b2b-labelhide { + position: absolute; + clip: rect(1px, 1px, 1px, 1px); } + +/** Tertiary Level Menu **/ +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret { + position: absolute; + z-index: 111; + top: 25px; } + .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:after, .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:before { + content: ''; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + position: absolute; + -webkit-transition: left .2s ease-out; + -moz-transition: left .2s ease-out; + transition: left .2s ease-out; } + .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:after { + border-bottom: 8px solid #fff; + top: 10px; } + .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:before { + border-bottom: 8px solid #ccc; + top: 9px; } + +.b2b-header-tabs .header-secondary .header-subitem.active .header-tertiary { + border-top: solid 1px #ccc; } + +.b2b-header-tabs .header-tertiary:after { + content: ''; + clear: both; + display: block; } + +.b2b-header-tabs .header-tertiary li { + display: inline-block; + padding: 0; + float: left; } + .b2b-header-tabs .header-tertiary li a { + color: #333; + display: block; + padding: 10px 15px; } + .b2b-header-tabs .header-tertiary li label { + text-align: left; + display: block; + font-size: 16px; + font-weight: bold; + color: #857B7B; + padding: 15px 0 0 15px; } + +.b2b-header-tabs .header__item.skip { + padding: 0; + display: inline-block; + cursor: default !important; } + .b2b-header-tabs .header__item.skip a { + color: transparent; + font-size: 12px; + line-height: 15px; + text-decoration: none; } + .b2b-header-tabs .header__item.skip a:focus { + color: #fff; + outline: 2px solid #0578ae; } + +.b2b-header-tabs .selectWrap { + min-width: 150px; } + .b2b-header-tabs .selectWrap button.awd-select { + height: 30px; + line-height: 31px; + font-size: 1rem; + display: inline-block; } + .b2b-header-tabs .selectWrap .awd-select-list { + background-color: #fff; + color: #333; + -webkit-transition: opacity .2s ease-out; + -moz-transition: opacity .2s ease-out; + transition: opacity .2s ease-out; + box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176); } + +@media (max-width: 768px) { + .b2b-header-tabs { + padding: 0 15px; } + .b2b-header-tabs .header__items, .b2b-header-tabs .header-secondary, .b2b-header-tabs .header-tertiary { + width: 100%; } + .b2b-header-tabs .header__item { + padding: 5px 0; } + .b2b-header-tabs .globe-text { + display: none; } + .b2b-header-tabs .header__item.b2b-headermenu a.menu__item { + padding: 5px 7px 9px 7px; } + .b2b-header-tabs .header__item .header-tertiary-wrapper { + top: 30px; } + .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret { + top: 14px; } + .b2b-header-tabs .header__item .header-secondary-wrapper { + top: 45px; } + .b2b-header-tabs .header__item.profile { + padding-left: 15px; + float: none; } } + +/************* Header - Start *************/ +.b2b-header-tabs { + background-color: #222; + width: 100%; + position: relative; + height: 45px; } + +.b2b-header-tabs .icon-primary-att-globe { + color: #009FDB; + font-size: 34px; + bottom: 1px; } + +/* + *TODO: delete below .icon-att-globel will not be used + *instead the one above, icon-primary-att-globe not available here + */ +.b2b-header-tabs .icon-att-globe { + color: #009FDB; + font-size: 34px; } + +.b2b-header-tabs .globe-text { + margin-left: 20px; + font-size: 2rem; } + +.b2b-header-tabs .header__items { + width: 980px; + margin: 0 auto; + display: block; + list-style: none; + border-spacing: 30px 0; + padding: 3px 0px 0px 0px; } + +.b2b-header-tabs .header__item { + display: inline-block; + text-align: left; + width: auto; + font-size: 14px; + font-family: "Omnes-ATT-W02"; + cursor: pointer; + padding: 0 15px 4px 15px; + /*margin-top:-3px;*/ + color: #fff; } + +.b2b-header-tabs .header__item.b2b-headermenu { + padding: 0; } + +.b2b-header-tabs .header__item.b2b-headermenu a.menu__item { + color: #fff; + text-decoration: none; + display: inline-block; + padding: 8px 15px 12px 15px; + font-size: 16px; } + +.b2b-header-tabs .header__item.active { + background-color: #fff; + border-radius: 2px; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + +.b2b-header-tabs .header__item.active a.menu__item { + color: #0578ae; } + +.b2b-header-tabs li:focus { + outline: 2px solid #0578ae; } + +/** profile pop Over **/ +.b2b-header-tabs .header__item.profile { + position: relative; + float: right; } + +/** Secondary Menu **/ +.b2b-header-tabs .header__item .header-secondary-wrapper, .b2b-header-tabs .header__item .header-tertiary-wrapper { + background-color: #fff; + position: absolute; + width: 100%; + left: 0; + top: 42px; + border-bottom: solid 1px #ccc; + -webkit-box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + -moz-box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.16); + display: none; + z-index: 111; } + +.b2b-header-tabs .header-secondary, .b2b-header-tabs .header-tertiary { + background-color: #fff; + width: 980px; + margin: 0 auto; } + +.b2b-header-tabs .header__item.active .header-secondary-wrapper, +.b2b-header-tabs .header-secondary .header-subitem.active .header-tertiary-wrapper { + display: block; } + +.b2b-header-tabs .header-secondary .header-subitem { + display: inline-block; + width: auto; + margin: 0 15px; } + +.b2b-header-tabs .header-secondary .header-subitem a.menu__item { + display: inline-block; + padding: 15px 0; + color: #333; + font-size: 14px; } + +.b2b-header-tabs .header-secondary .header-subitem a.menu__item:hover, .b2b-header-tabs .header-secondary .header-subitem a.menu__item:focus { + color: #0578ae; } + +.b2b-label-hide { + position: absolute; + clip: rect(1px, 1px, 1px, 1px); } + +/** Tertiary Level Menu **/ +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:after, +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:before { + content: ''; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + position: absolute; + -webkit-transition: left .2s ease-out; + -moz-transition: left .2s ease-out; + transition: left .2s ease-out; } + +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret { + position: absolute; + z-index: 111; + top: 25px; } + +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:after { + border-bottom: 8px solid #fff; + top: 10px; } + +.b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret:before { + border-bottom: 8px solid #ccc; + top: 9px; } + +/** Tertiary Level Menu **/ +.b2b-header-tabs .header-secondary .header-subitem.active .header-tertiary { + border-top: solid 1px #ccc; } + +.b2b-header-tabs .header-tertiary:after { + content: ''; + clear: both; + display: block; } + +.b2b-header-tabs .header-tertiary li { + display: inline-block; + padding: 0; + float: left; } + +.b2b-header-tabs .header-tertiary li a { + color: #333; + display: block; + padding: 7px 15px; + max-width: 228px; } + +.b2b-header-tabs .header-tertiary li label, .b2b-header-tabs .header-tertiary li span { + text-align: left; + display: block; + font-size: 14px !important; + font-weight: bold; + color: #857B7B; + padding: 15px 0 0 15px; } + +/** Quarternary Level Menu **/ +.b2b-header-tabs .header-quarternary { + width: 100%; + float: left; } + +.b2b-header-tabs .header-quarternary li { + padding-left: 15px; + font-family: "Omnes-ATT-W02"; + display: none; } + +.b2b-header-tabs .header-quarternary li.active { + display: block; } + +.b2b-header-tabs .header-quarternary li a { + color: #666666; + font-size: 14px; + padding: 0px 10px 10px 10px; } + +/** Skip Navigation**/ +.b2b-header-tabs .header__item.skip { + padding: 0; + display: inline-block; + cursor: default !important; } + +.b2b-header-tabs .header__item.skip a { + color: transparent; + font-size: 12px; + line-height: 15px; + text-decoration: none; } + +.b2b-header-tabs .header__item.skip a:focus { + color: #fff; + outline: 2px solid #0578ae; } + +/** Dropdown css inside Header ****/ +.b2b-header-tabs .selectWrap { + min-width: 150px; } + +.b2b-header-tabs .selectWrap button.awd-select, .b2b-header-tabs .selectWrap input.awd-select { + height: 36px; + line-height: 31px; + font-size: 1rem; + display: inline-block; } + +.b2b-header-tabs .selectWrap .awd-select-list { + background-color: #fff; + color: #333; + -webkit-transition: opacity .2s ease-out; + -moz-transition: opacity .2s ease-out; + transition: opacity .2s ease-out; + box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176); } + +/* + * responsive header media queries + */ +@media screen and (max-width: 1100px) { + .b2b-header-tabs .globe-text { + display: none; } + .b2b-header-tabs .header__item.profile { + padding-left: 15px; + float: none; } + .b2b-header-tabs .header__items { + padding-top: 0px; } } + +@media screen and (max-width: 950px) { + .header__item.profile { + top: 20px; } + .b2b-header-tabs { + height: 90px; } + .header__item .selectWrap { + bottom: 15px; } + .b2b-header-tabs .header__items { + padding-top: 25px; } + .b2b-header-tabs .header__item .header-secondary-wrapper, .b2b-header-tabs .header__item .header-tertiary-wrapper { + top: 80px; } + .b2b-header-tabs .header-secondary .header-subitem.active i.menuCaret { + top: 35px; } + .b2b-header-tabs .header__item.b2b-headermenu a.menu__item { + padding-bottom: 30px; } + .b2b-header-tabs .header-secondary .header-subitem.active .header-tertiary { + margin-top: -28px; } } + +/*************** Header - END ******************/ +.hp-container { + display: block; + max-width: 408px; } + .hp-container i:focus { + outline: thin dotted #666; } + .hp-container .icon-misc-pen { + cursor: pointer; } + .hp-container .icon-misc-trash { + cursor: pointer; } + +.hp-selected { + border-bottom: 1px solid #ccc; + border-bottom: 1px solid #ccc; + margin-bottom: 16px; + padding-bottom: 16px; } + .hp-selected .selected-days { + padding-bottom: 16px; } + .hp-selected .selected-days .day { + padding-top: 10px; + float: left; } + +.hp-checkbox { + padding-top: 20px; + margin: 16px auto 0 auto; } + .hp-checkbox label { + position: relative; + width: 20px; + margin-right: 34px; } + .hp-checkbox label span { + position: absolute; + top: -20px; + left: 0px; + margin-left: 0px; } + +.hp-dropdowns { + margin-top: 15px; + display: flex; + display: -webkit-flex; + display: -ms-flexbox; } + +.hp-buttons { + margin-top: 20px; + display: flex; + display: -webkit-flex; + display: -ms-flexbox; } + +.hp-dropdowns .radio-buttons { + margin-top: 30px; } + .hp-dropdowns .radio-buttons .radio { + margin-right: 15px; } + +@font-face { + font-family: "Omnes-ATT-W02"; + src: url("fonts/Omnes_ATTW02.eot"); + src: url("fonts/Omnes_ATTW02.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02.woff") format("woff"), url("fonts/Omnes_ATTW02.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Medium"; + src: url("fonts/Omnes_ATTW02Medium.eot"); + src: url("fonts/Omnes_ATTW02Medium.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Medium.woff") format("woff"), url("fonts/Omnes_ATTW02Medium.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Italic"; + src: url("fonts/Omnes_ATTW02Italic.eot"); + src: url("fonts/Omnes_ATTW02Italic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Italic.woff") format("woff"), url("fonts/Omnes_ATTW02Italic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Light"; + src: url("fonts/Omnes_ATTW02Light.eot"); + src: url("fonts/Omnes_ATTW02Light.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Light.woff") format("woff"), url("fonts/Omnes_ATTW02Light.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Bold"; + src: url("fonts/Omnes_ATTW02Bold.eot"); + src: url("fonts/Omnes_ATTW02Bold.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02Bold.woff") format("woff"), url("fonts/Omnes_ATTW02Bold.woff2") format("woff2"), url("fonts/Omnes_ATTW02Bold.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Light-Italic"; + src: url("fonts/Omnes_ATTW02LightItalic.eot"); + src: url("fonts/Omnes_ATTW02LightItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02LightItalic.woff") format("woff"), url("fonts/Omnes_ATTW02LightItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02LightItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Medium-Italic"; + src: url("fonts/Omnes_ATTW02MediumItalic.eot"); + src: url("fonts/Omnes_ATTW02MediumItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02MediumItalic.woff") format("woff"), url("fonts/Omnes_ATTW02MediumItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02MediumItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +@font-face { + font-family: "Omnes-ATT-W02-Bold-Italic"; + src: url("fonts/Omnes_ATTW02BoldItalic.eot"); + src: url("fonts/Omnes_ATTW02BoldItalic.eot?#iefix") format("embedded-opentype"), url("fonts/Omnes_ATTW02BoldItalic.woff") format("woff"), url("fonts/Omnes_ATTW02BoldItalic.woff2") format("woff2"), url("fonts/Omnes_ATTW02BoldItalic.ttf") format("truetype"); + font-weight: normal; + font-style: normal; } + +/* TODO: Build a reference page for these classes */ +.font-regular { + font-family: "Omnes-ATT-W02" !important; } + +.font-light { + font-family: "Omnes-ATT-W02-Light" !important; } + +.font-italic { + font-family: "Omnes-ATT-W02-Italic" !important; } + +.font-light-italic { + font-family: "Omnes-ATT-W02-Light-Italic" !important; } + +.font-medium { + font-family: "Omnes-ATT-W02-Medium" !important; } + +.font-medium-italic { + font-family: "Omnes-ATT-W02-Medium-Italic" !important; } + +.font-reset { + font-style: normal; + font-variant: normal; + font-weight: normal; + text-transform: none; } + +.b2b-nav-menu { + background-color: #efefef; + border: 1px solid #efefef; + width: 230px; + font-size: 1.4rem; } + +.b2b-subnav-container > ul { + padding: 0px; } + +.b2b-subnav-content { + margin: 0; + margin-bottom: 10px; } + +.b2b-subnav-content > li { + border-bottom: 1px solid #999999; + position: relative; + cursor: pointer; } + +.b2b-subnav-content > li > a { + text-decoration: none; + line-height: 18px; + display: block; + padding: 10px; } + +.b2b-subnav-content > li > a.expand { + color: #333; } + +.b2b-subnav-content > li ul { + overflow: hidden; + max-height: 0; + transition-duration: 0.5s; + transition-timing-function: cubic-bezier(0, 1, 0.5, 1); } + +.b2b-subnav-content > li ul.expand { + transition-duration: 0.7s; + transition-timing-function: ease-in-out; + max-height: 1000px; + overflow: hidden; } + +.b2b-subnav-content > li > a:focus, .b2b-subnav-content > li ul > li > a:focus { + outline: thin dotted #666; } + +.b2b-subnav-content > li ul > li > a { + line-height: 18px; + padding: 8px 0; + display: block; + outline-offset: -4px; + padding-left: 10px; } + +.b2b-icon-plus-minus { + display: inline-block; + height: 20px; + margin-right: 10px; + padding: 0; + position: absolute; + right: 0px; + top: 10px; + vertical-align: middle; + width: 20px; } + +@media (min-width: 320px) and (max-width: 767px) { + .b2b-nav-menu { + background-color: #fff; + border: 1px solid white; + width: 100%; } + .b2b-subnav-content > li { + padding-left: 10px; } + .b2b-subnav-container > ul:first-child { + border-top: 1px solid #999; } + .b2b-icon-plus-minus { + right: 10px; } + .b2b-subnav-content > li li > a.active { + color: #0574ac; + text-decoration: none; + font-family: "Omnes-ATT-W02"; } } + +.b2b-list-box-item { + white-space: nowrap; + margin: 1px; + border: 1px solid transparent; + outline: none; + visibility: inherit; + display: inherit; + text-align: left; + overflow: hidden; + cursor: pointer; + padding: 5px 0 5px; + padding-left: 15px; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; } + .b2b-list-box-item:focus { + border: 2px solid #5e8cb3; } + +.b2b-list-box-item--selected { + background-color: #cfdde9; } + +.b2b-reorder-list-item { + font-size: 14px; + color: #191919; + margin: 10px 15px 1px 1px; + float: right; + width: 96%; + height: 40px; + white-space: nowrap; + outline: none; + visibility: inherit; + display: inherit; + text-align: left; + overflow: hidden; + cursor: pointer; + padding-left: 15px; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; } + +.b2b-reorder-list { + float: left; + outline: 0px none; + overflow-x: hidden; + width: 400px; + position: relative; + height: 500px; + border: 1px solid #cccccc; + margin-bottom: 10px; } + +.list-item-index { + width: 26px; + float: left; + padding-top: 10px; } + +.list-item-content { + width: 316px; + border: 1px solid #cccccc; + border-radius: 4px; + float: right; + height: 40px; + text-align: left; + padding: 10px 0px 5px 10px; } + .list-item-content:hover { + border: 2px dotted #0568ae; } + +.b2b-reorder-list-btngroup { + width: 185px; + float: left; + margin-left: 30px; + margin-top: 120px; + text-align: center; } + .b2b-reorder-list-btngroup button { + width: 185px; + margin-bottom: 30px; + text-align: left; } + +.b2b-reorder-list-item--disabled { + background-color: #f2f2f2; + cursor: not-allowed; } + .b2b-reorder-list-item--disabled:hover { + border: 1px solid #cccccc; } + +.b2b-reorder-list-item--focussed { + border: 2px solid #0568ae; } + +.b2b-reorder-list-item--selected { + background-color: #71c5e8; } + +.seperator { + margin-left: 8px; + margin-right: 8px; } + .seperator:after { + content: '|'; } + +.b2b-list-header { + font-size: 14px; + margin-bottom: 20px; + font-weight: bold; } + +.b2b-list-header2 { + font-size: 16px; + margin-bottom: 3px; + font-weight: bold; } + .b2b-list-header2 span { + margin-left: 10px; } + +.btn.disabled[ddh-load-button] { + line-height: 46px; + padding: 0 19px 0 18px; } + +.btn.disabled[ddh-load-button] { + color: #666666; } + +.icon-spinner-ddh.large { + height: 50px; + width: 50px; } + +.icon-spinner-ddh.small { + height: 30px; + width: 30px; } + +.icon-spinner-ddh { + -webkit-animation: 1s linear infinite spinner; + animation: 1s linear infinite spinner; + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzNiAzNiIgaWQ9InN2Zy1zcGlubmVyIiB4PSIwcHgiIHk9IjBweCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CiAgIDxwYXRoIGZpbGw9IiNGNUY1RjUiIGQ9Ik0xOCAzNkM4LjEgMzYgMCAyNy45IDAgMThTOC4xIDAgMTggMHMxOCA4LjEgMTggMTgtOC4xIDE4LTE4IDE4em0wLTMxLjVjLTcuNSAwLTEzLjUgNi0xMy41IDEzLjVTMTAuNiAzMS41IDE4IDMxLjVjNy41IDAgMTMuNS02LjEgMTMuNS0xMy41IDAtNy41LTYtMTMuNS0xMy41LTEzLjV6Ii8+CiAgIDxwYXRoIGZpbGw9IiMwNTY4QUUiIGlkPSJzcGlubmVyIiBkPSJNMzAuNyA1LjNsLTMuMSAzLjJjMi40IDIuNCAzLjkgNS44IDMuOSA5LjUgMCA3LjQtNi4xIDEzLjUtMTMuNSAxMy41UzQuNSAyNS40IDQuNSAxOCAxMC42IDQuNSAxOCA0LjVWMEM4LjEgMCAwIDguMSAwIDE4czguMSAxOCAxOCAxOCAxOC04LjEgMTgtMThjMC01LTItOS41LTUuMy0xMi43eiIgdHJhbnNmb3JtPSIiPiAgICAgIAogICA8L3BhdGg+Cjwvc3ZnPg==); } + +.btn-small .icon-spinner-ddh { + height: 30px !important; + width: 30px !important; } + +.btn-small .icon-spinner { + height: 30px; + width: 30px; } + +.load-backdrop { + position: absolute; + top: 50%; + left: 50%; } + +.small-modal-loader { + width: 420px !important; + height: 212px !important; + text-align: center; } + +.small-modal-loader .icon-spinner { + margin-bottom: 5px; } + +.body.styled-by-modal { + position: fixed; } + +.b2b-modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: -1; } + +.b2b-modal-backdrop.fade { + background-color: #000; + opacity: 0; + filter: alpha(opacity=0); + transition: all 0.3s linear 0s; } + +.b2b-modal-backdrop.fade.in { + z-index: 1040; + opacity: 0.7; + filter: alpha(opacity=70); + background-color: #000; + transition: opacity 0.3s linear 0s; } + +.modalwrapper { + height: 100%; + width: 100%; + left: 0; + overflow-y: hidden; + position: absolute; + right: 0; + padding: 20px; + top: 0; + z-index: -1; } + +.modalwrapper.active { + z-index: 1050; + overflow-y: auto; } + +.modal { + background-clip: padding-box; + background-color: #ffffff; + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + box-shadow: 0 3px 5px 1px rgba(0, 0, 0, 0.4); + margin: 0 auto; + /*margin-bottom:10%;*/ + outline: medium none; + /*position: absolute;*/ + height: 0; + min-height: 150px; + overflow: hidden; + /*top: 10%;*/ + width: 100%; + z-index: -1; } + +.modalwrapper.modal-docked .modal { + max-height: 80%; + height: 80%; + overflow: hidden; + top: 0; } + +.modal.fade.in { + position: relative; + height: auto; + overflow: auto; + top: 10%; + z-index: 1060; + transition: opacity .5s linear 0s; } + +.modal.fade.in.modal-landscape { + overflow-y: auto; } + +.modal.fade { + transition: opacity .5s linear 0s; } + +.fade.in { + opacity: 1; } + +.fade { + opacity: 0; } + +.b2b-modal-header { + align-items: center; + border-radius: 8px 8px 0 0; + display: flex; + min-height: 60px; + overflow: hidden; + padding: 30px 46px 30px 30px; + position: relative; } + +.b2b-modal-header > h2 { + line-height: 1; + margin: 0; + padding: 0; } + +.modal-header-portrait { + -webkit-overflow-scrolling: auto; } + +.modal-header-landscape { + -webkit-overflow-scrolling: auto; } + +.b2b-modal-body { + -webkit-overflow-scrolling: touch; + padding: 0 30px 20px; + position: relative; + width: auto; } + +.b2b-modal-body:focus { + outline: 1px dotted #333333; } + +.modal-form { + margin-bottom: 0; } + +.b2b-modal-footer { + background-color: #fff; + width: 100%; + padding: 0 30px; + border-radius: 0; + position: absolute; + bottom: 0; } + +:not(.modal-docked) .b2b-modal-footer { + position: relative; } + +.modal-landscape .b2b-modal-footer { + position: relative; } + +.b2b-modal-footer .cta-button-group { + display: flex; + justify-content: flex-end; + padding: 20px 0 5px; + width: 100%; + border-top: 1px solid #d2d2d2; } + +.b2b-modal-footer .cta-button-group .btn { + margin-left: auto; + margin-right: auto; + float: right; } + +.b2b-modal-footer .cta-button-group .btn-footer-margin-left { + margin-left: 0px; } + +.b2b-modal-footer .cta-button-group .btn-footer-right { + margin-right: auto; } + +.b2b-modal-footer .cta-modal-footer-flex { + justify-content: flex-start; } + +.b2b-modal-footer .cta-button-group .btn + .btn { + margin-right: 0 !important; } + +[class*="modal-"] { + width: 100%; } + +.modal-small { + max-width: 420px; } + +.modal-medium { + max-width: 620px; } + +.modal-large { + max-width: 720px; } + +.modal-xlarge { + max-width: 860px; } + +.modal-jumbo { + max-width: 1000px; } + +.modalwrapper.modal-docked { + height: 100%; + display: flex; + align-items: center; } + +.modalwrapper.modal-docked .b2b-modal-body { + height: 80%; + overflow-y: scroll; + padding-bottom: 30px; } + +.modalwrapper.modal-docked .modal { + max-height: 80%; + height: 80%; + overflow: hidden; + top: 0; } + +.modalwrapper.modal-docked .b2b-modal-body > *:last-child { + margin-bottom: 60px; } + +@media (max-width: 767px) { + .modalwrapper { + padding: 15px; + overflow-x: hidden; } + .modal.fade.in { + top: 0; + right: 0; + left: 0; + margin-bottom: 15px; + border: none; } + .b2b-modal-header { + padding: 20px 46px 20px 15px; } + .b2b-modal-body { + width: 100%; + padding: 0 15px 15px; } + .modalwrapper.modal-docked { + position: absolute; + height: 100%; + padding: 0; } + .modalwrapper.modal-docked .modal.fade.in { + margin-bottom: 0; + width: 100% !important; + max-height: 100%; + height: 100%; + border-radius: 0; } + .modalwrapper.modal-docked .b2b-modal-body { + overflow-y: scroll; + height: 100%; } + .modalwrapper.modal-docked.modal-landscape { + overflow-y: hidden; + position: fixed; } + .modalwrapper.modal-docked.modal-landscape .modal { + overflow-y: scroll; + max-width: 100%; } + .modalwrapper.modal-docked.modal-landscape .b2b-modal-body { + height: auto; + overflow-y: hidden; } + .b2b-modal-footer { + padding: 0 15px; } + .b2b-modal-footer .cta-button-group { + display: block; + padding: 15px 0; } + .b2b-modal-footer .cta-button-group .btn { + float: none; } + .b2b-modal-footer .cta-button-group .btn + .btn { + margin-bottom: 0; } + .b2b-modal-footer .cta-button-group a.visible-phone { + align-items: center; + display: flex !important; + height: 42px; + justify-content: center; } } + +.b2b-modal-footer > .cta-button-group { + line-height: 40px; + padding-bottom: 12px; } + +.ajaxed, +.modal.fade.in .b2b-modal-header, +.modal.fade.in .b2b-modal-body, +.modal.fade.in .b2b-modal-footer { + animation-duration: 0.01s; + -o-animation-duration: 0.01s; + -ms-animation-duration: 0.01s; + -moz-animation-duration: 0.01s; + -webkit-animation-duration: 0.01s; + animation-name: DOMinsertion; + -o-animation-name: DOMinsertion; + -ms-animation-name: DOMinsertion; + -moz-animation-name: DOMinsertion; + -webkit-animation-name: DOMinsertion; } + +.monthselector thead tr th { + min-width: 46px; } + +.monthselector thead tr:after { + content: ""; + position: absolute; + left: 20px; + top: 52px; + height: 1px; + width: 85%; + border-bottom: 1px solid #ccc; } + +.monthselector tbody tr:last-child { + height: 50px; } + +.monthselector td.day { + margin: 1px 4px !important; + width: 64px !important; } + +.monthselector .datepicker-switch { + width: 195px !important; } + +.monthselector .show-date { + width: 30px !important; } + +.monthselector button.faux-input { + width: 100%; + top: -30px; } + .monthselector button.faux-input:focus { + border: 1px solid #0574ac; } + .monthselector button.faux-input:disabled { + cursor: not-allowed; } + +.monthselector .cta-button-group { + padding: 0 20px; } + .monthselector .cta-button-group a { + margin-right: 20px; } + +.monthselector .day.active .show-date:after, .monthselector .day:focus .show-date:after, .monthselector .due-date.disabled .show-date:after { + height: 30px; + left: 9px !important; + top: 0; + width: 42px !important; } + +.monthselector .disabled.day:focus .show-date:after { + border: none; } + +.monthselector .icon-calendar { + display: block; + padding-top: 8px; } + +.Monthpicker-input { + background-color: white !important; } + +.field-group input:not([type="button"])[disabled] { + background-color: #d2d2d2 !important; } + +.b2b-ml-nav { + padding: 0 10px 0 10px; + width: 320px; } + +.b2b-ml-nav ul { + list-style: none; + list-style-type: none; } + +.b2b-ml-nav a { + display: block; + padding: 0 0 5px 30px; + line-height: 22px; + margin-left: -10px; + color: #0568ae; + font-size: 1.4rem; } + +.b2b-ml-nav a:focus { + outline-offset: 1px; } + +.b2b-ml-nav li:focus { + outline: none; } + +.b2b-ml-nav li:focus > a { + outline: thin dotted #666; + outline-offset: 1px; } + +.b2b-ml-nav ul li { + border-left: 1px solid #ccc; } + +.b2b-ml-nav ul ul { + padding: 0 0 0 20px; } + +.b2b-ml-nav ul > li { + position: relative; + line-height: 18px; } + +.b2b-ml-nav a > span { + background-color: #FFF; + display: inline; + margin: 0; + padding: 0; + position: absolute; + left: -11px; + top: 0; } + +.b2b-ml-nav a > span > i { + font-size: 20px; } + +.b2b-ml-nav a:only-child > span { + left: -6px; + border-radius: 50%; + line-height: 7px; + top: 5px; } + +.b2b-ml-nav a:only-child > span > i { + background-color: inherit; + background: #fff; + font-size: 10px; } + +.b2b-ml-nav ul li:first-child > a:only-child > span { + left: -6px; + border-radius: 50%; + line-height: 12px; + top: 0px; } + +.b2b-ml-nav li a + ul { + display: none; } + +.b2b-ml-nav li a.active + ul { + display: block; } + +.b2b-ml-nav .selected { + color: #333; } + +/*to overide ng-doc inline property for library demo - TODO: Move to docs.css*/ +.b2b-ml-nav a [class^="icon-"], a [class*=" icon-"], a [class^="icon-"]:before, a [class*=" icon-"]:before { + display: inline-block; } + +.b2b-alerts-messages { + background-color: #fff; + border-radius: 8px; + height: auto; } + .b2b-alerts-messages h3 { + color: #191919 !important; + font-family: "Omnes-ATT-W02-Medium"; + margin-bottom: 0 !important; + line-height: 16px !important; + font-size: 16px !important; + margin-top: 0px !important; + margin-bottom: 15px !important; } + .b2b-alerts-messages h4 { + color: #191919 !important; + font-family: "Omnes-ATT-W02-Medium"; + margin-bottom: 0 !important; } + .b2b-alerts-messages .alert-info { + background-color: #0574ac; + border: 0; } + .b2b-alerts-messages .alert-error { + background-color: #cf2a2a; + border: 0; } + .b2b-alerts-messages .alert-success { + background-color: #1b7e28; + border: 0; } + .b2b-alerts-messages div:nth-child(2) { + padding: 20px; + vertical-align: baseline; } + .b2b-alerts-messages .close:before { + color: #767676; + font-size: 15px; } + .b2b-alerts-messages p { + font-size: 14px; + color: #191919; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; } + .b2b-alerts-messages p a { + color: #0568ae; + text-decoration: none; } + .b2b-alerts-messages p a:hover, + .b2b-alerts-messages p a:focus { + text-decoration: underline; } + .b2b-alerts-messages .btn-small { + margin-bottom: 0px; } + +.b2b-alerts-success { + border: 1px solid #1b7e28; } + +.b2b-alerts-error { + border: 1px solid #cf2a2a; } + +.b2b-alerts-info { + border: 1px solid #0574ac; } + +/* TODO: Rearange this and move to patches if needed */ +.b2b-breadcrumb-css-override > li { + margin-right: 24px; } + +.b2b-breadcrumb-css-override li > * { + float: left !important; } + +.b2b-css-override ul.nav-tabs { + margin-bottom: 0; } + +.b2b-css-override div.tab-content { + margin-top: 0; + border-top: none; } + +.b2b-css-override .tab-content .prettyprint, .b2b-css-override .usage .prettyprint { + max-height: 500px; + overflow-y: auto; } + +.b2b-top-nav-buttons-css-override { + margin-bottom: 0; + margin-top: 2px; } + +.b2b-auto-width { + width: auto !important; } + +.b2b-toggle-header-active { + color: #0568ae; } + +.b2b-toggle-header-inactive { + color: #333333; } + +.b2b-toggle-header-icon { + cursor: pointer; } + +.tab-content > .tab-pane { + display: none; } + +.tab-content > .active { + display: block; } + +.icon-circle:before { + background-image: url("data:image/svg+xml,%3Csvg%20baseProfile%3D%22tiny%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2036%2036%22%3E%3Ccircle%20fill%3D%22transparent%22%20stroke%3D%22%23666%22%20stroke-miterlimit%3D%2210%22%20cx%3D%2218%22%20cy%3D%2218%22%20r%3D%2216%22%2F%3E%3C%2Fsvg%3E"); + content: ""; + position: absolute; + top: 0; + z-index: 1; } + +.ds2-no-colors .icon-circle:before { + background-image: none; + content: "\e902"; } + +i:focus { + outline: thin dotted #666; } + +.p-col-md-12 { + width: 50%; } + +.pager__item { + border-radius: 0; + cursor: default; + display: inline-block; + margin: 5px; + width: 22px; + height: 23px; + vertical-align: baseline; } + +.pager { + padding-top: 10px; + padding-bottom: 20px; + text-align: center; + margin: 0 auto; } + +.pager__item--input { + color: #067ab4; + max-height: 32px; + max-width: 40px; + padding-left: 0; + padding-right: 0; + text-align: center; + margin-left: 10px; } + +.row.section-row { + margin-bottom: 20px; } + +.pager__item--active { + border-bottom: 2px solid #0574ac; + border-radius: 0; + color: #333333; } + +.pager a.pager__item--active:hover { + cursor: default; } + +.pager a:hover, .pager a:focus { + text-decoration: none; + color: #333333; + cursor: pointer; } + +.pager a.disabled:hover, .pager a.disabled:focus { + cursor: not-allowed; } + +.row.section-row.b2b-page { + display: block; } + +a.pager__item--next:focus, a.pager__item--prev:focus { + text-decoration: none; + border: 0; } + +.pager__item--next, .pager__item--prev { + margin: 5px; + padding: 1.5px 6px 1.5px 6px; } + +.pager .disabled i { + pointer-events: none; + cursor: default; + color: #c4c4c4; } + +.fieldLabel { + color: #666666; } + +.fieldLabel input { + color: #666666; } + +.pSelect { + float: right; + width: 150px; } + +.numericResult { + margin-bottom: 20px; + font-size: 1.6rem; + margin-top: 20px; + display: inline-block; + font-family: "omnes-att-w02-medium"; } + +.mobile-view > .pager__item { + margin: 5px 10px; + width: 24px; + height: 34px; + vertical-align: middle; + line-height: 34px; } + +.fade1, .fadel { + opacity: 0.4; } + +.fade2, .fadesl { + opacity: 0.6; } + +h4#pagination-truncated { + margin-top: 50px; } + +h4#pagination-large-count { + margin-top: 50px; } + +.p-col-md-12 input { + margin-left: 20px; } + +.pager a .icon-right:before { + display: inline-block; } + +.pager a .icon-left:before { + display: inline-block; } + +.page-heading { + background: white none repeat scroll 0 0; + margin-bottom: -12px; + padding-left: 10px; + padding-right: 10px; + position: relative; } + +.numericResult:focus { + outline: 1px dotted #0574ac; } + +.page-heading-group { + color: #ef6f00; + font-family: "Omnes-ATT-W02-Medium"; } + +.pager > div > span.fieldLabel { + margin-left: 18px; } + +.pager .fieldLabel .btn-arrow { + top: 0; + left: 10px; + margin-left: -5px; } + +.b2b-p-col-md-12 { + width: 50%; } + .b2b-p-col-md-12 input { + margin-left: 20px; } + +.b2b-pager__item { + border-radius: 0; + cursor: default; + display: inline-block; + margin: 0px 5px 0 5px; + height: 23px; + vertical-align: baseline; } + +.b2b-pager__item--noclick { + pointer-events: none !important; + cursor: default !important; } + +.b2b-pager__item--droppable { + pointer-events: all !important; } + +.b2b-pager { + padding-top: 10px; + padding-bottom: 20px; + text-align: center; + margin: 0 auto; } + .b2b-pager a:hover { + text-decoration: none; + color: #333333; + cursor: pointer; } + .b2b-pager a:focus { + text-decoration: none; + color: #333333; + cursor: pointer; } + .b2b-pager a .icon-right:before { + display: inline-block; } + .b2b-pager a .icon-left:before { + display: inline-block; } + .b2b-pager .disabled i { + pointer-events: none; + cursor: default; + color: #c4c4c4; } + +.b2b-pager__item--input { + color: #067ab4; + max-height: 32px; + max-width: 60px; + padding-left: 0; + padding-right: 0; + text-align: center; + margin-left: 5px; } + +.row.section-row { + margin-bottom: 20px; } + +.b2b-pager__item--active { + border-bottom: 2px solid #0574ac; + border-radius: 0; + color: #333333; } + +.row.section-row.b2b-page { + display: block; } + +a.b2b-pager__item--next:focus { + text-decoration: none; + border: 0; } + +a.b2b-pager__item--next-disabled { + outline: 0; } + +a.b2b-pager__item--next-disabled > [class^="icon-"] { + color: #cccccc; + cursor: not-allowed; + outline: 0; } + +a.b2b-pager__item--prev:focus { + text-decoration: none; + border: 0; } + +a.b2b-pager__item--prev-disabled { + outline: 0; } + +a.b2b-pager__item--prev-disabled > [class^="icon-"] { + color: #cccccc; + cursor: not-allowed; } + +.b2b-pager__item--next { + padding: 1.5px 0px 1.5px 0px; } + +.b2b-pager__item--prev { + padding: 1.5px 0px 1.5px 0px; } + +.fieldLabel { + color: #666666; } + .fieldLabel input { + color: #666666; } + .fieldLabel .btn-arrow { + top: 0; + left: 10px; } + +.b2b-pSelect { + float: right; + width: 150px; } + +.b2b-numericResult { + margin-bottom: 20px; + font-size: 1.6rem; + margin-top: 20px; } + +.b2b-mobile-view > .b2b-pager__item { + margin: 5px 10px; + min-width: 23px; + height: 34px; + vertical-align: middle; + line-height: 34px; } + +.b2b-fade1 { + opacity: 0.4; } + +.b2b-fade2 { + opacity: 0.6; } + +.b2b-fadesl { + opacity: 0.6; } + +h4#b2b-pagination-truncated { + margin-top: 50px; } + +h4#b2b-pagination-large-count { + margin-top: 50px; } + +.b2b-page-heading { + background: white none repeat scroll 0 0; + margin-bottom: -12px; + padding-left: 10px; + padding-right: 10px; + position: relative; } + +.b2b-numericResult:focus { + outline: 1px dotted #0574ac; } + +.b2b-page-heading-group { + color: #ef6f00; + font-family: "Omnes-ATT-W02-Medium"; } + +.b2b-pager > div > span.fieldLabel { + margin-left: 18px; } + +.b2b-go-to-page { + margin-top: 14px; } + +.b2b-go-to-page-inline { + display: inline-block; } + +.b2b-pages-with-input .b2b-go-to-page { + margin-top: 0px; } + +input.b2b-phone-mask-input { + padding-right: 15px; } + input.b2b-phone-mask-input:hover, input.b2b-phone-mask-input:focus { + padding-right: 15px; } + +/************************** Start - Should be removed after the styling in global is fixed *******************/ +input::-ms-clear { + display: none; } + +/************************** End - Should be removed after the styling in global is fixed *******************/ +@media (max-width: 767px) { + input::-ms-clear { + display: block; } } + +.pivot-link-group { + background-color: #5a5a5a; + border-top: 1px solid #959595; } + +.pivot-links > li { + border-bottom: 1px solid #959595; } + +.pivot-links > li > a { + color: #fff; + display: block; + padding: 12px 15px 10px; + line-height: normal; } + +.b2b-profile-block-container { + min-height: 200px; + height: auto; + background-color: #fff; + border-radius: 8px; + border: 1px solid #ccc; + box-shadow: 0px 1px 1px 1px #ccc; + display: inline-table; + margin: 15px 15px; } + +.b2b-profile-block-details p, .b2b-profile-block-details div { + padding: 2px 7px; + font-size: 1.4rem; } + +.b2b-profile-block-details .radio-label, .b2b-profile-block-details a { + font-size: 1.4rem; } + +.b2b-profile-block-details p label, .b2b-profile-block-details p span { + padding-left: 10px; } + +.b2b-profile-block-footer { + margin-bottom: 12px; + margin-top: 5px; + height: 35px; } + +.b2b-profile-block-details p { + word-wrap: break-word; + height: 61px; } + .b2b-profile-block-details p:first-child { + margin-top: 10px; } + .b2b-profile-block-details p:after { + content: ' '; + display: block; + border: 0.2px solid #ccc; + margin-top: 12px; } + +.b2b-profile-block-details .radio { + margin-left: 15px; + height: 30px; } + +.b2b-approval-icon { + color: #1b7e28; + float: right; + position: relative; + left: 10px; } + .b2b-approval-icon i { + color: #1b7e28; + float: right; } + +.b2b-profile-link { + float: right; + position: relative; + left: -4px; } + +a.link-profile { + position: relative; + left: -5px; + float: right; + margin-bottom: 16px; } + +.b2b-profile-block-radio { + position: relative; + top: -5px; } + +.b2b-profile-card { + min-width: 229px; + min-height: 354px; + margin: 10px; + border: solid 1px #CCC; + font-family: "Omnes-ATT-W02"; + display: inline-block; + vertical-align: top; } + .b2b-profile-card .top-block { + padding: 15px 20px; + background-color: #e4e4e4; + max-height: 153px; } + .b2b-profile-card .bottom-block { + padding: 15px 20px 15px 20px; + background-color: #fff; } + .b2b-profile-card .profile-image { + background: #e4e4e4; + margin-bottom: 15px; + text-align: center; } + .b2b-profile-card .profile-image .default-img { + display: inline-block; + width: 60px; + height: 60px; + margin-bottom: 10px; + border: 6px solid #fff; + border-radius: 99em; + -webkit-border-radius: 99em; + -moz-border-radius: 99em; + /* background-color: #eee; */ } + +.profile-image img { + display: inline-block; + width: 60px; + height: 60px; + margin-bottom: 10px; + border: 6px solid #fff; + border-radius: 99em; + -webkit-border-radius: 99em; + -moz-border-radius: 99em; + /* background-color: #eee; */ } + +.b2b-profile-card .profile-image .default-img { + font-family: "Omnes-ATT-W02"; + color: #333; + background-color: #fff; + font-size: 32px; + line-height: 22px; + padding: 5px; + padding-top: 13px; + width: 60px; + height: 60px; + text-transform: uppercase; } + +.b2b-profile-card .profile-image .name { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 16px; + color: #333; + text-align: center; + margin-bottom: 5px; + margin-top: 5px; + overflow: hidden; + word-break: break-word; + white-space: normal; + text-transform: capitalize; } + +.b2b-profile-card .profile-image .status-icon { + border-radius: 10px; + border: 1px solid #fff; + margin: 0 3px 0 0; + width: 10px; + height: 10px; + display: inline-block; + vertical-align: middle; } + +.b2b-profile-card .profile-image .status { + font-size: 12px; + line-height: 15px; + text-align: center; + margin: 0 15px 0 0; + color: #444; } + +.b2b-profile-card .status .circle { + width: 10px; + height: 10px; + border-radius: 50%; + margin: 30px 6px 0px 20px; + text-align: center; + background-color: #444; } + +.b2b-profile-card .profile-image .status-green { + background-color: #0c0; } + +.b2b-profile-card .profile-image .status-red { + background-color: red; } + +.b2b-profile-card .profile-image .status-blue { + background-color: #00f; } + +.b2b-profile-card .profile-image .status-yellow { + background-color: #ff0; } + +.b2b-profile-card .profile-image .status .status-badge { + margin-left: 5px; + border: dotted 1px #444; + background-color: transparent; + font-weight: 400; + color: #444; + height: 17px; + padding: 0 5px; + font-size: 11px; + padding-left: 5px; + padding-right: 5px; } + +.b2b-profile-card .profile-details { + background: #fff; } + .b2b-profile-card .profile-details label { + display: block; + cursor: text; + font-family: "Omnes-ATT-W02-Medium"; + font-weight: bolder; + font-size: 14px; + color: #333; + padding: 0; + margin: 0; } + .b2b-profile-card .profile-details div { + margin: 0; + font-size: 14px; + color: #333; + padding-bottom: 6.5px; } + +.b2b-profile-card .b2b-add-user { + background: white; + border-style: dotted; + font-size: 16px; + color: #333; + position: relative; } + .b2b-profile-card .b2b-add-user i { + font-size: 30px; + padding-bottom: 15px; } + +.b2b-profile-card .atcenter { + cursor: pointer; + margin-top: 60%; + vertical-align: middle; + text-align: center; } + +.b2b-profile-card .tooltip { + cursor: pointer; } + .b2b-profile-card .tooltip .helpertext { + position: relative; + color: white; } + +.b2b-profile-card .tooltip-wrapper { + position: relative; } + +/* Overrides for tooltip absolute positioning */ +@media (min-width: 1025px) { + .b2b-profile-card .tooltip-size-control { + width: 100% !important; } } + +@-webkit-keyframes progress-bar-stripes { + from { + background-position: 0 0; } + to { + background-position: 80px 0; } } + +@keyframes progress-bar-stripes { + from { + background-position: 0 0; } + to { + background-position: 80px 0; } } + +.progress { + background-color: #e4e4e4; + border-radius: 4px; + height: 14px; + margin-bottom: 20px; + min-width: 250px; + overflow: hidden; + padding: 0; + position: relative; } + +a .progress { + margin-bottom: 0; } + +.progress .bar { + background-color: #666; + border-radius: 4px; + display: -webkit-flex; + display: -ms-flexbox; + display: flex; + height: 100%; + width: 0; } + +.progress-arrow { + display: -webkit-flex; + display: -ms-flexbox; + display: flex; + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + -webkit-justify-content: flex-end; + -ms-flex-pack: end; + justify-content: flex-end; } + +.progress-link + .usage-bar { + margin-top: 5px; } + +.progress-success .bar, .progress .bar-success { + background-color: #1b7e28; } + +.progress-warning .bar, .progress .bar-warning { + background-color: #ef6f00; } + +.progress-danger .bar, .progress .bar-danger { + background-color: #cf2a2a; } + +.progress.increment { + display: -webkit-flex; + display: -ms-flexbox; + display: flex; } + +.progress.increment .bar:first-child:not(:last-child) { + border-right: none; + border-radius: 4px 0 0 4px; } + +.progress.increment .bar:last-child:not(:first-child) { + border-left: none; + border-radius: 0 4px 4px 0; } + +.progress.increment .bar + .bar:not(:last-child) { + border-left: none; + border-right: none; + border-radius: 0; } + +.progress.increment .bar:not(:first-child) { + border-left: 1px solid white !important; } + +.usage-bar { + display: table; + float: none; + width: 100%; + margin-bottom: 1px; } + +.usage-bar > .usage-text { + display: table-cell; + width: 1%; } + +.progress + .usage-bar { + margin-top: -15px; } + +.usage-bar .usage-text { + font-size: 1.4rem; } + +.usage-bar .usage-text:first-child { + white-space: nowrap; } + +.usage-bar .usage-text.text-right { + vertical-align: top; + font-size: 1.4rem; + width: auto !important; } + +.usage-bar .usage-text.text-right:before { + content: ""; + display: table; + height: .1em; } + +.usage-bar.billing-cycle .usage-text { + font-size: 1.4rem; } + +.usage-bar.billing-cycle .usage-text.text-right { + vertical-align: bottom; } + +.progress.autocolor [data-percentage="1"], .progress.autocolor [data-percentage="2"], .progress.autocolor [data-percentage="3"], .progress.autocolor [data-percentage="4"], .progress.autocolor [data-percentage="5"], .progress.autocolor [data-percentage="6"], .progress.autocolor [data-percentage="7"], .progress.autocolor [data-percentage="8"], .progress.autocolor [data-percentage="9"], .progress.autocolor [data-percentage="10"] .progress.autocolor [data-percentage^="2"], .progress.autocolor [data-percentage^="3"], .progress.autocolor [data-percentage^="4"], .progress.autocolor [data-percentage^="5"], .progress.autocolor [data-percentage="60"], .progress.autocolor [data-percentage="61"], .progress.autocolor [data-percentage="62"], .progress.autocolor [data-percentage="63"], .progress.autocolor [data-percentage="64"] { + background-color: #1b7e28; } + +.progress.autocolor [data-percentage="65"], .progress.autocolor [data-percentage="66"], .progress.autocolor [data-percentage="67"], .progress.autocolor [data-percentage="68"], .progress.autocolor [data-percentage="69"], .progress.autocolor [data-percentage^="7"], .progress.autocolor [data-percentage^="8"] { + background-color: #ef6f00; } + +.progress.autocolor [data-percentage^="9"], .progress.autocolor [data-percentage="100"] { + background-color: #cf2a2a; } + +.b2b-seek-bar-container { + position: relative; } + .b2b-seek-bar-container div { + position: absolute; } + .b2b-seek-bar-container .b2b-seek-bar-track-container { + width: 100%; } + .b2b-seek-bar-container .b2b-seek-bar-track { + width: 100%; + height: 6px; + background-color: #cccccc; + border-radius: 10px; } + .b2b-seek-bar-container .b2b-seek-bar-track-fill { + width: 100%; + height: 6px; + background-color: #cccccc; + border-radius: 10px; + width: 0; + background-color: #157BB2; + transition: width 0s linear; } + +.seek-bar-container .seek-bar-knob-container { + transition: left 0s linear; } + +.b2b-seek-bar-container .b2b-seek-bar-knob { + width: 14px; + height: 14px; + border-radius: 10px; + top: -4px; + left: -8px; + border: 1px solid #cccccc; + background: white; + cursor: pointer; } + +.b2b-seek-bar-container .b2b-seek-bar-knob:focus { + outline: thin dotted #666; } + +.b2b-seek-bar-container.vertical { + width: 100%; + height: 100%; + margin: 0 auto; + position: relative; + border-radius: 10px; } + .b2b-seek-bar-container.vertical .b2b-seek-bar-track-container { + position: relative; + height: 100%; } + .b2b-seek-bar-container.vertical .b2b-seek-bar-track { + position: absolute; + height: 100%; } + .b2b-seek-bar-container.vertical .b2b-seek-bar-track-fill { + position: absolute; + bottom: 0; + height: 0; + width: 100%; } + .b2b-seek-bar-container.vertical .b2b-seek-bar-knob-container { + transition: bottom .01s linear; + position: relative; + bottom: 0; } + .b2b-seek-bar-container.vertical .b2b-seek-bar-knob { + position: absolute; + border-radius: 10px; + top: -7px; + left: -4px; } + +.form-search .search-query { + width: 100% !important; } + +.form-search .well { + margin-top: 0; } + +.form-search > ul.nav > li.section { + min-height: 20px !important; } + +input.b2b-search-input-field { + margin-bottom: 0px; } + +.search-suggestion-list { + background-color: #FFFFFF; + border: 1px solid #ccc; + border-radius: 0 0 6px 6px; + box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.15); + margin-top: -5px; + max-height: 400px; + overflow-x: hidden; + overflow-y: auto; + padding: 15px 0; + position: absolute; + width: 100%; + z-index: 1000; } + .search-suggestion-list > li.active { + background-color: #cccccc; } + .search-suggestion-list:empty { + display: none; } + +.b2b-search-hightlight { + font-weight: bold; } + +input[type="text"]::-moz-placeholder { + color: #767676; + font-family: "Omnes-ATT-W02-Italic"; } + +input[type="text"]:focus { + z-index: 1000; } + +input[type="text"] + .reset-field { + background-color: #FFFFFF; + height: 90%; + top: 5%; } + +.btn-search:focus { + outline: 1px dotted #0574ac; } + +.field-group input:not([type="button"])[disabled] ~ .btn-search { + background-color: #d2d2d2; } + +.btn-search[class*="btn"] { + background-color: #FFFFFF; + background-size: 20px 20px; + border-radius: 0 1.5rem 1.5rem 0; + height: 3rem; + min-width: 4.4rem !important; + right: 0.15rem; + top: 0.15rem; + width: 4.4rem; } + +.search-suggestion-wrapper { + margin-bottom: 15px; + position: relative; } + .search-suggestion-wrapper .no-result { + padding: 0px 15px; } + +.search-suggestion-item { + color: #333333; + line-height: 4rem; + padding: 0 15px; + position: relative; + z-index: 1000; } + .search-suggestion-item:hover { + background-color: #e4e4e4; + cursor: pointer; } + .search-suggestion-item:focus { + background-color: #e4e4e4; + cursor: pointer; } + .search-suggestion-item a { + color: #333333; + text-decoration: none; } + +.btn-search i { + color: #767676; } + +input.b2b-search-input-field:focus ~ .btn-search > i, .btn-search:focus > i { + color: #0568ae; } + +button.btn-search[disabled] { + cursor: not-allowed; } + button.btn-search[disabled] i { + color: #767676; } + +.innershadow { + -webkit-background-blend-mode: mutilply; + box-shadow: 0 3px 0 2px rgba(0, 0, 0, 0.08); } + +.linkSelectorModule { + position: relative; + height: 32px; + line-height: 20px; + border: 0px; + width: auto; + display: block; } + .linkSelectorModule .icon-down { + font-size: 23px; + margin-top: -10px; + position: absolute; + top: 50%; + margin-left: -30px; } + .linkSelectorModule .selectModule { + background-color: transparent; + border: none; + color: #0568ae; + cursor: pointer; + border: 1px solid transparent; + box-shadow: none; + padding-right: 35px; + position: relative; + user-select: none; + font-size: 1.6rem; } + .linkSelectorModule .selectModule:focus { + border: 1px dotted #ccc; + box-shadow: none; + -moz-user-select: none; } + .linkSelectorModule .selectModule:hover { + text-decoration: underline; } + .linkSelectorModule .active + .moduleWrapper:before { + background-color: #FFFFFF; + border-color: #d2d2d2; + border-style: solid; + border-width: 1px 1px 0 0; + content: ""; + display: block; + height: 15px; + right: 122px; + margin: 0; + position: absolute; + top: -8px; + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + width: 15px; } + .linkSelectorModule .moduleWrapper { + top: 40px; } + .linkSelectorModule ul.awd-module-list { + border-radius: 6px 6px 0px 0px; } + +.selectorModule .icon-down { + font-size: 23px; + margin-top: -11px; + position: absolute; + right: 4px; + top: 50%; } + +.selectorModule .selectModule { + border: 1px solid #d2d2d2; + border-radius: 6px; + box-shadow: 1px 5px 2px -5px rgba(0, 0, 0, 0.15); + display: block; + width: 100%; + padding-left: 15px; + background-color: transparent; + cursor: pointer; } + .selectorModule .selectModule:focus { + border: 1px solid #0568ae; + -moz-user-select: none; } + .selectorModule .selectModule span.module-data { + position: absolute; + bottom: 6px; + line-height: 20px; } + .selectorModule .selectModule img + span.module-data { + padding-left: 45px; } + +.selectorModule .selectModule.active { + border-bottom-right-radius: 0px; + border-bottom-left-radius: 0px; } + +.selectorModule .moduleWrapper { + position: absolute; + width: 100% !important; + border-top: none; } + +.selectorModule ul.awd-module-list { + border-radius: 0px 0px 6px 6px; } + +.selectorModule .large > img { + height: 30px; + position: absolute; + width: 30px; + top: 20px; + left: 15px; } + +.selectModule { + background-color: transparent; + font-family: "Omnes-ATT-W02"; + color: #333333; + font-size: 1.6rem; + height: 36px; + line-height: 35px; + margin-bottom: 0; + position: relative; + text-align: left; + top: 0; + z-index: 10; + padding: 0px; + margin: 0px; + cursor: pointer; } + +.moduleWrapper { + background-color: #FFFFFF; + position: absolute; + color: #191919; + z-index: 9999; + box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.15); + border-radius: 0px 0px 6px 6px; } + .moduleWrapper .module-list-item img { + height: 30px; + position: absolute; + width: 30px; + top: 30px; + left: 15px; + align-self: center; } + .moduleWrapper span { + display: block; + white-space: nowrap; + font-size: 1.5rem; } + +.awd-module-list { + overflow-y: auto; + z-index: 9999; + max-height: 360px; + border: 1px solid #d2d2d2; } + .awd-module-list .module-list-item > .module-data { + overflow: ellipsis; + white-space: nowrap; + line-height: 20px; + font-size: 1.6rem; + border-bottom: 1px dotted #959595; + margin: 0px 15px 0px 15px; + padding-right: 50px; + padding-bottom: 14px; + padding-top: 14px; + align-self: center; + width: 100%; } + .awd-module-list .module-list-item:hover { + background-color: #f2f2f2; } + .awd-module-list .module-list-item:active { + background-color: #f2f2f2; } + .awd-module-list .module-list-item[aria-selected="true"] { + background-color: #f2f2f2; } + +.module-list-item { + cursor: pointer; + overflow: hidden; + position: relative; + overflow: ellipsis; + white-space: nowrap; + z-index: 1000; + color: #191919; + display: flex; } + .module-list-item:last-of-type .module-data { + border-bottom: none; } + .module-list-item img + span.module-data { + padding-left: 45px; } + +.module-groups:first-of-type .module-list-item:last-of-type .module-data { + border-bottom: 1px solid #959595; } + +.module-groupitem { + padding-bottom: 4px; } + +.selectorModule.large { + height: 72px; + vertical-align: middle; + text-align: left; } + .selectorModule.large .moduleWrapper { + top: 71px; } + .selectorModule.large input { + height: 72px; + vertical-align: middle; + text-align: left; } + .selectorModule.large button { + height: 72px; + vertical-align: middle; + text-align: left; } + .selectorModule.large .selectModule img { + left: 15px; + top: 21px; } + +ul.module-groupitem li { + margin: 0 -15px 0 -15px; } + +span.module-data span { + display: block; + line-height: 20px; + font-size: 1.5rem; } + +li.module-groups { + cursor: default !important; + padding: 18px 15px 0px 15px; } + +li.module-list-item[selected]:before { + box-sizing: border-box; + display: inline-block; + font-size: 2em; + height: 1em; + position: absolute; + top: 20px; + right: 0px; + vertical-align: middle; + width: 1em; + color: #007a3e; } + +ul.module-optinalcta { + position: relative; + height: 44px; + margin-top: 0px; + border-bottom: 1px solid #d2d2d2; + border-left: 1px solid #d2d2d2; + border-right: 1px solid #d2d2d2; + border-radius: 0px 0px 6px 6px; } + ul.module-optinalcta li { + position: absolute; + bottom: 10px; } + ul.module-optinalcta a { + text-indent: 15px; + padding: 15px; } + +.b2b-slider-container { + position: relative; } + .b2b-slider-container.slider-disabled { + cursor: not-allowed !important; } + .b2b-slider-container div { + position: absolute; } + .b2b-slider-container .slider-track-container { + width: 100%; + cursor: pointer; } + .b2b-slider-container .slider-track { + width: 100%; + height: 14px; + background-color: #cccccc; + border-radius: 4px; + border: 1px solid #cccccc; } + .b2b-slider-container .slider-snap-point { + border-left: 1px solid white; + height: 12px; + z-index: 1; } + .b2b-slider-container .slider-track-fill { + width: 100%; + height: 14px; + background-color: #cccccc; + border-radius: 4px; + width: 0; + background-color: #157BB2; + transition: width 0s linear; } + .b2b-slider-container .slider-knob-container { + transition: left 0s linear; } + .b2b-slider-container .slider-knob-container.slider-knob-hidden { + display: none !important; } + .b2b-slider-container .slider-knob { + width: 24px; + height: 24px; + border-radius: 12px; + top: -6px; + left: -8px; + border: 1px solid #cccccc; + background: white; + cursor: pointer; } + .b2b-slider-container .slider-knob:focus { + outline: thin dotted #666; } + .b2b-slider-container .tooltiptext { + visibility: hidden; + min-width: 40px; + width: auto; + background-color: #0568ae; + color: #fff; + text-align: center; + border-radius: 6px; + padding: 5px 5px; + position: absolute; + z-index: 1; + bottom: 10px; + opacity: 0; + font-size: 12px; + font-family: "Omnes-ATT-W02-Medium"; + transition: opacity 1s; + margin-left: -17px; + height: 25px; } + .b2b-slider-container .trackfill-disabled-color, .b2b-slider-container .tooltiptext.disabled-tooltip { + background-color: #767676; } + .b2b-slider-container .tooltiptext.disabled-tooltip::after { + border-color: #767676 transparent transparent transparent; } + .b2b-slider-container .tooltiptext::after { + content: ""; + position: absolute; + top: 100%; + left: 50%; + margin-left: -5px; + border-width: 5px; + border-style: solid; + border-color: #0568ae transparent transparent transparent; } + .b2b-slider-container .tooltiptext { + visibility: visible; + opacity: 1; } + +.b2b-slider-endpoints-container { + margin-top: 13px; + color: #333; + font-size: 12px; } + .b2b-slider-endpoints-container .b2b-slider-endpoints-left { + float: left; + line-height: 100%; } + .b2b-slider-endpoints-container .b2b-slider-endpoints-right { + float: right; + line-height: 100%; } + .b2b-slider-endpoints-container::after { + clear: both; + content: ""; + display: block; } + +.b2b-slider-container.vertical { + width: 100%; + height: 100%; + margin: 0 auto; + position: relative; + border-radius: 4px; } + .b2b-slider-container.vertical .slider-track-container { + position: relative; + height: 100%; + width: 14px; } + .b2b-slider-container.vertical .slider-track { + position: absolute; + height: 100%; } + .b2b-slider-container.vertical .slider-track-fill { + position: absolute; + bottom: 0; + height: 0; + width: 100%; } + .b2b-slider-container.vertical .tooltiptext { + margin-left: 25px; + top: -10px; + min-width: 30px; + padding: 4px 7px; } + .b2b-slider-container.vertical .tooltiptext::after { + content: ""; + position: absolute; + border-top: 6px solid transparent; + border-bottom: 6px solid transparent; + border-right: 6px solid #0568ae; + top: 6px; + left: -5px; } + .b2b-slider-container.vertical .tooltiptext.disabled-tooltip::after { + border-right: 6px solid #767676; } + .b2b-slider-container.vertical .slider-knob-container { + transition: bottom 0s linear; + position: relative; + bottom: 0; } + .b2b-slider-container.vertical .slider-knob-container.slider-knob-hidden { + display: none !important; } + .b2b-slider-container.vertical .slider-knob { + position: absolute; + border-radius: 12px; + top: -10px; + left: -5px; } + +.disable-slider-minus { + cursor: not-allowed; + color: #767676; } + +.icon-spinner { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2036%2036%22%20id%3D%22svg-spinner%22%20x%3D%220px%22%20y%3D%220px%22%20xml%3Aspace%3D%22preserve%22%3E%0A%20%20%20%3Cpath%20fill%3D%22%23F5F5F5%22%20d%3D%22M18%2036C8.1%2036%200%2027.9%200%2018S8.1%200%2018%200s18%208.1%2018%2018-8.1%2018-18%2018zm0-31.5c-7.5%200-13.5%206-13.5%2013.5S10.6%2031.5%2018%2031.5c7.5%200%2013.5-6.1%2013.5-13.5%200-7.5-6-13.5-13.5-13.5z%22%2F%3E%0A%20%20%20%3Cpath%20fill%3D%22%230568AE%22%20id%3D%22spinner%22%20d%3D%22M30.7%205.3l-3.1%203.2c2.4%202.4%203.9%205.8%203.9%209.5%200%207.4-6.1%2013.5-13.5%2013.5S4.5%2025.4%204.5%2018%2010.6%204.5%2018%204.5V0C8.1%200%200%208.1%200%2018s8.1%2018%2018%2018%2018-8.1%2018-18c0-5-2-9.5-5.3-12.7z%22%3E%0A%20%20%20%20%20%20%3CanimateTransform%20%0A%20%20%20%20%20%20%20%20%20attributeType%3D%22xml%22%0A%20%20%20%20%20%20%20%20%20attributeName%3D%22transform%22%0A%20%20%20%20%20%20%20%20%20type%3D%22rotate%22%0A%20%20%20%20%20%20%20%20%20from%3D%220%2018%2018%22%0A%20%20%20%20%20%20%20%20%20to%3D%22360%2018%2018%22%0A%20%20%20%20%20%20%20%20%20dur%3D%221.0s%22%0A%20%20%20%20%20%20%20%20%20repeatCount%3D%22indefinite%22%0A%20%20%20%20%20%20%2F%3E%0A%20%20%20%3C%2Fpath%3E%0A%3C%2Fsvg%3E"); + height: 50px; + width: 50px; } + +.icon-spinner.small { + margin-right: 5px; + height: 30px !important; + width: 30px !important; } + +.isIE .icon-spinner, +.isIE .icon-spinner.small { + animation: spinner 1s linear infinite; } + +.ds2-no-colors .icon-spinner { + animation: spinner 1s linear infinite; + border: 5px dotted transparent; + border-radius: 50%; } + +@keyframes spinner { + 0% { + transform: rotate(0deg); } + 100% { + transform: rotate(359deg); } } + +.b2b-status-tracker > .btn-arrow:nth-of-type(1) { + margin-right: 10px; } + +.b2b-status-tracker > .btn-arrow:nth-of-type(2) { + margin-left: 20px; } + +.b2b-status-tracker > .btn-arrow { + height: 20px; + margin-top: 25px; + overflow: visible; } + .b2b-status-tracker > .btn-arrow > .btn-secondary > .icon-left { + margin-right: 5px; + color: #0574ac; } + .b2b-status-tracker > .btn-arrow > .btn-secondary > .icon-right { + color: #0574ac; } + +.b2b-status-tracker > .b2b-status-tracker-step { + padding: 0; + position: relative; } + +.b2b-status-tracker-step { + margin-left: 5px; } + +.b2b-status-tracker > .b2b-status-tracker-step .b2b-status-tracker-heading { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 14px; + color: #191919; + margin-bottom: 10px; } + +.b2b-status-tracker > .b2b-status-tracker-step.complete > .progress > .progress-bar { + width: 100%; + background-color: #1b7e28; } + +.b2b-status-tracker > .b2b-status-tracker-step.complete .icon-controls-approval { + color: #1b7e28; } + +.b2b-status-tracker > .b2b-status-tracker-step.current > .progress > .progress-bar { + width: 100%; + background-color: #333333; } + +.b2b-status-tracker > .b2b-status-tracker-step.current .icon-misc-time { + color: #333333; } + +.b2b-status-tracker > .b2b-status-tracker-step.pending > .progress > .progress-bar { + width: 100%; + background-color: #ffb81c; } + +.b2b-status-tracker > .b2b-status-tracker-step.pending .icon-controls-statusokay { + color: #ffb81c; } + +.b2b-status-tracker > .b2b-status-tracker-step.actionRequired > .progress > .progress-bar { + width: 100%; + background-color: #cf2a2a; } + +.b2b-status-tracker > .b2b-status-tracker-step.actionRequired .icon-securityalerts-alert { + color: #cf2a2a; } + +.b2b-status-tracker > .b2b-status-tracker-step.notAvailable > .progress > .progress-bar { + width: 100%; + background-color: #767676; } + +.b2b-status-tracker > .b2b-status-tracker-step.notAvailable .icon-controls-restricted { + color: #767676; } + +.b2b-status-tracker > .b2b-status-tracker-step > .progress { + position: relative; + border-radius: 1.5px; + height: 3px; + margin-bottom: 10px; + background-color: #c5c5c5; } + .b2b-status-tracker > .b2b-status-tracker-step > .progress > .progress-bar { + width: 0; + height: 3px; } + +.b2b-status-tracker > .b2b-status-tracker-step > .b2b-status-tracker-estimate { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 14px; + color: #191919; + margin-bottom: 10px; } + +.b2b-status-tracker > .b2b-status-tracker-step > .b2b-status-tracker-description { + font-family: "Omnes-ATT-W02"; + font-size: 12px; + color: #767676; + padding-right: 15px; } + .b2b-status-tracker > .b2b-status-tracker-step > .b2b-status-tracker-description a { + cursor: pointer; } + +.step-indicator { + height: auto; + padding: 40px 0; } + +.step-heading { + color: #333333; + font-family: "Omnes-ATT-W02"; + font-size: 3.8rem; + line-height: 0.8; } + +.steps { + display: flex; + height: 5px; + margin-top: 60px; + position: relative; } + +.steps li { + color: #5a5a5a; + flex: 1; + margin-right: 5px; + background-color: #c4c4c4; + outline: 1px solid transparent; } + +.steps li:first-child { + border-radius: 4px 0 0 4px; } + +.steps li:last-child { + margin-right: 0; + border-radius: 0 4px 4px 0; } + +.steps li.step-on, +.steps li.step-done { + background-color: #007a3e; + color: #007a3e; + border: 1px solid transparent; } + +.step-text { + bottom: 29px; + display: inline-block; + font-size: 1.8rem; + margin-top: 0; + position: relative; + white-space: nowrap; } + +.step-on .step-text { + font-family: "Omnes-ATT-W02-Medium"; } + +.steps li .step-text[data-large-text]:before { + content: attr(data-large-text) " "; } + +.step-confirmation { + color: #007a3e; + margin-bottom: 30px; } + +.step-confirmation > div { + display: flex; } + +.step-confirmation > div i { + color: #007a3e; + font-size: 50px; + margin-right: 10px; } + +.step-confirmation.centered > div i { + margin-left: -60px; } + +.step-confirmation > div h3 { + font-size: 2.4rem; + margin: 26px 0 20px; } + +.step-confirmation > p { + margin: 0; } + +@media (max-width: 1024px) { + .step-indicator { + padding: 25px 0; } + .steps { + margin-top: 0; } + .step-heading { + font-size: 2.4rem; + margin-bottom: 11px; } + .step-text { + display: none; } + .step-on .step-text { + bottom: 6px; + display: block; + font-size: 1.2rem; + left: 0; + line-height: 1; + margin-top: 10px; + position: absolute; + top: 4px; } + .steps li .step-text[data-sm-text]:before { + content: attr(data-sm-text) " "; + color: #333333; } + .step-confirmation { + margin-top: 30px !important; } } + +@media (max-width: 767px) { + .step-confirmation.centered > div i { + margin-left: 0; } + .step-confirmation.centered > p { + margin-left: 40px; } + .step-confirmation > div h3 { + font-size: 1.8rem; + margin: 13px 0 10px; } + .step-confirmation > div i { + font-size: 30px; + margin-right: 10px; } } + +.step-indicator.vertical { + height: auto; } + +.vertical .step-heading { + font-size: 24px; } + +.vertical .steps { + display: block; + height: inherit; + width: 100%; } + +.vertical .steps li { + align-items: center; + background-color: transparent; + display: flex; + height: 60px; + margin: 0 0 4px; + padding: 0 0 0 20px; + position: relative; } + +.vertical .steps li .step-text { + align-self: center; + color: #0568ae; + display: block; + margin: 0; + position: relative; + font-size: 14px; + top: 0; } + +.vertical .steps li .step-text[data-large-text]:before { + content: attr(data-large-text) " "; } + +.vertical .steps li:after { + background-color: transparent; + border-left: 4px solid #d2d2d2; + content: ""; + height: 60px; + left: 0; + margin: 0; + padding: 0; + position: absolute; + top: 0; + width: 4px; } + +.vertical .steps li.step-on:after, +.vertical .steps li.step-done:after { + border-color: #0568ae; } + +.b2b-step-tracker { + height: auto; + padding: 0px 0px 0px 0px; } + .b2b-step-tracker .btn.btn-left { + margin-right: 10px; } + .b2b-step-tracker .btn.btn-right { + margin-left: 5px; } + .b2b-step-tracker .b2b-left-arrow { + float: left; + margin-top: -5px; } + .b2b-step-tracker .b2b-right-arrow { + float: right; + margin-top: -5px; } + .b2b-step-tracker .b2b-steps { + display: flex; + height: 5px; + margin-top: 30px; + position: relative; } + .b2b-step-tracker .b2b-steps li { + color: #767676; + flex: 1; + margin-right: 5px; + background-color: #767676; + outline: 1px solid transparent; + height: 3px; } + .b2b-step-tracker .b2b-steps li.b2b-step-done { + background-color: #1b7e28; + border: 1px solid transparent; + color: #007a3e; + height: 3px; } + .b2b-step-tracker .b2b-steps li.b2b-step-on { + background-color: #333333; + color: #333333; + height: 3px; + font-family: "Omnes-ATT-W02-Medium"; } + .b2b-step-tracker .b2b-steps li .b2b-step-text { + bottom: 29px; + display: inline-block; + font-size: 14px; + margin-top: 0; + position: relative; + white-space: nowrap; } + .b2b-step-tracker .b2b-steps li .b2b-step-text[data-large-text]:before { + content: attr(data-large-text) " "; } + .b2b-step-tracker .b2b-steps li:first-child { + border-radius: 2px 0 0 2px; } + .b2b-step-tracker .b2b-steps li:last-child { + margin-right: 0; + border-radius: 0 2px 2px 0; } + +@media (max-width: 1024px) { + .b2b-step-tracker { + padding: 25px 0; } + .b2b-step-tracker .b2b-steps { + margin-top: 0; } + .b2b-step-tracker .b2b-steps li .b2b-step-text { + display: none; } + .b2b-step-tracker .b2b-steps li .b2b-step-text[data-sm-text]:before { + content: attr(data-sm-text) " "; + color: #333333; } + .b2b-step-tracker .b2b-steps li.b2b-step-on .b2b-step-text { + bottom: 6px; + display: block; + font-size: 10px; + left: 0; + line-height: 1; + margin-top: 10px; + position: absolute; + top: 4px; } } + +.strength-meter-container { + height: 26px; + max-width: 450px; } + +.strength-meter-gauge { + border-radius: 2px; + background-color: #d2d2d2; + height: 5px; + display: block; + position: relative; + outline: 1px solid transparent; } + +.strength-meter-gauge-fill { + height: 100%; + display: block; + border-radius: 2px; + text-indent: -9999px; + width: 0%; + border: 2px solid transparent; } + +.strength-meter-gauge-fill.strength-meter-animate { + transition: width 0.5s linear, background-color 0.5s linear; } + +.strength-meter-animate[style*="20"] { + background-color: #cf2a2a; } + +.strength-meter-animate[style*="20"] + .strength-meter-divider + .strength-meter-content:after { + content: "Unacceptable"; } + +.strength-meter-animate[style*="40"] { + background-color: #ea7400; } + +.strength-meter-animate[style*="40"] + .strength-meter-divider + .strength-meter-content:after { + content: "Weak"; } + +.strength-meter-animate[style*="60"] { + background-color: #ea7400; } + +.strength-meter-animate[style*="60"] + .strength-meter-divider + .strength-meter-content:after { + content: "Fair"; } + +.strength-meter-animate[style*="80"] { + background-color: #007a3e; } + +.strength-meter-animate[style*="80"] + .strength-meter-divider + .strength-meter-content:after { + content: "Good"; } + +.strength-meter-animate[style*="100"] { + background-color: #007a3e; } + +.strength-meter-animate[style*="100"] + .strength-meter-divider + .strength-meter-content:after { + content: "Excellent"; } + +.strength-meter-divider { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + display: flex; + overflow: hidden; } + +.strength-meter-divider span { + background: transparent; + display: block; + flex-grow: 1; + border-right: solid 1px #fff; } + +.strength-meter-divider span:first-child { + border-radius: 2px 0 0 2px; } + +.strength-meter-divider span + .strength-meter-divider span { + border-radius: 0; } + +.strength-meter-divider span:last-child { + border-radius: 0 2px 2px 0; + border-right: 0; } + +.strength-meter-content { + font-size: 14px; + line-height: 1; + padding-top: 7px; + position: absolute; } + +.strength-meter-content:before { + font-family: "Omnes-ATT-W02"; + content: "Password strength: "; } + +.strength-meter-content:after { + font-family: "Omnes-ATT-W02-Medium"; } + +.strength-meter-container { + height: 26px; + min-width: 290px; + max-width: 450px; } + +.strength-meter-container .strength-meter-gauge { + border-radius: 2px; + background-color: #cccccc; + box-shadow: 0 1px 1px -1px #333 inset; + height: 5px; + display: block; + overflow: hidden; + position: relative; } + +.strength-meter-container > .strength-meter-gauge > .strength-meter-gauge-fill { + height: 100%; + box-shadow: 0 1px 1px -1px #999 inset; + display: block; + text-indent: -9999px; + width: 0%; } + +.strength-meter-container > .strength-meter-gauge > .strength-meter-gauge-fill.strength-meter-animate { + transition: width 0ms ease-out, background-color 0ms ease-in; } + +.strength-meter-container > .strength-meter-gauge > .strength-meter-divider { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + display: flex; } + +.strength-meter-container > .strength-meter-gauge > .strength-meter-divider span { + background: transparent; + display: block; + flex-grow: 1; + border-right: solid 1px #fff; } + +.strength-meter-container > .strength-meter-gauge > .strength-meter-divider span:last-child { + border-right: 0; } + +.strength-meter-container > .strength-meter-content { + font-family: "Omnes-ATT-W02"; + font-size: 14px; + line-height: 1; + padding-top: 7px; } + +.strength-meter-container > .strength-meter-content:before { + content: none; } + +.strength-meter-container > .strength-meter-content > .strength-meter-content-state { + font-family: "Omnes-ATT-W02-Medium"; } + +.btn-switch-label { + display: flex; + align-items: center; } + .btn-switch-label:focus .btn-switch { + outline: 1px dotted #666; + outline-offset: 5px; } + .btn-switch-label input:focus .btn-switch { + outline: 1px dotted #666; + outline-offset: 5px; } + .btn-switch-label > span { + flex: 1; } + +.btn-switch { + background-color: #fff; + border: 1px solid #d2d2d2; + border-radius: 16px; + box-shadow: 0 4px 5px -5px rgba(0, 0, 0, 0.15) inset, 0 5px 5px -5px rgba(0, 0, 0, 0.15); + height: 32px; + overflow: hidden; + position: relative; + width: 80px; + user-select: none; } + .btn-switch input[type="checkbox"] { + left: 0; + margin: 0; + opacity: 0; + position: absolute; + top: 0; + transition: none; } + .btn-switch input[type="checkbox"] + .switch-overlay .btn-slider-on .activo { + font: 0px/0 "Omnes-ATT-W02"; } + .btn-switch input[type="checkbox"] + .switch-overlay .btn-slider-on + .btn + .btn-slider-off .inactivo { + font: 0px/0 "Omnes-ATT-W02"; } + .btn-switch input[type="button"] { + left: 0; + margin: 0; + opacity: 0; + position: absolute; + top: 0; + transition: none; } + .btn-switch input[type="button"] + .switch-overlay .btn-slider-on .activo { + font: 0px/0 "Omnes-ATT-W02"; } + .btn-switch input[type="button"] + .switch-overlay .btn-slider-on + .btn + .btn-slider-off .inactivo { + font: 0px/0 "Omnes-ATT-W02"; } + .btn-switch input.checked + .switch-overlay { + left: 0; + transition: all .3s linear .0s; } + .btn-switch input.checked + .switch-overlay .switch-handle { + background-color: #007a3e; + background: linear-gradient(to bottom, #008744 0%, #007a3e 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid transparent; } + .btn-switch input:checked + .switch-overlay { + left: 0; + transition: all .3s linear .0s; } + .btn-switch input:checked + .switch-overlay .switch-handle { + background-color: #007a3e; + background: linear-gradient(to bottom, #008744 0%, #007a3e 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid transparent; } + .btn-switch input + .switch-overlay { + /*left: -48px;*/ + transition: all .3s linear .0s; } + .btn-switch input + .switch-overlay .switch-handle { + background-color: #f2f2f2; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid #d2d2d2; } + .btn-switch input[disabled] + .switch-overlay { + left: 0; + width: 100% !important; + background-color: #d2d2d2; + color: #5A5A5A !important; + cursor: not-allowed !important; } + .btn-switch input[disabled] + .switch-overlay .btn-slider-on { + display: none; } + .btn-switch input[disabled] + .switch-overlay .activo { + display: none; } + .btn-switch input[disabled] + .switch-overlay .switch-handle { + display: none; } + .btn-switch input[disabled] + .switch-overlay .btn-slider-off { + left: 0; + text-align: center; + padding: 0; } + .btn-switch input[disabled]:checked + .switch-overlay { + left: 0; + width: 100% !important; + background-color: #fff; } + .btn-switch input[disabled]:checked + .switch-overlay .btn-slider-off { + display: none; } + .btn-switch input[disabled]:checked + .switch-overlay .btn-slider-off + .inactivo { + display: none; } + .btn-switch input[disabled]:checked + .switch-overlay .switch-handle { + display: none; } + .btn-switch input[disabled]:checked + .switch-overlay .btn-slider-on { + display: block; + text-align: center; + padding: 0; + color: #007a3e !important; + font-weight: bold; } + .btn-switch input[disabled]:checked + .switch-overlay .activo { + display: block; + text-align: center; + padding: 0; + color: #007a3e !important; + font-weight: bold; } + .btn-switch input[disabled]:checked + .btn-slider-on { + display: block; } + .btn-switch input[disabled] + .btn-slider-on + .switch-handle { + width: 100%; + margin: 0; } + .btn-switch input[disabled] + .btn-slider-on + .switch-handle + .btn-slider-off { + display: block; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on { + display: none; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on .activo { + border: medium none; + color: #666; + font: 16px/32px "Omnes-ATT-W02"; + height: auto; + margin: 0 auto; + width: auto; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on .activo:before { + display: none; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on + .switch-handle + .btn-slider-off { + display: block; + padding: 0; + text-align: center; + color: #333333; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on + .switch-handle + .btn-slider-off .inactivo { + border: medium none; + color: #666; + font: 16px/32px "Omnes-ATT-W02"; + height: auto; + margin: 0 auto; + width: auto; } + .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on + .switch-handle + .btn-slider-off .inactivo:before { + display: none; } + .btn-switch input[type="checkbox"][disabled]:checked + .switch-overlay .btn-slider-on { + display: block; + padding: 0; + text-align: center; + color: #007a3e; } + .btn-switch input[type="checkbox"][disabled]:checked + .switch-overlay .btn-slider-on + .switch-handle + .btn-slider-off { + display: none; } + .btn-switch input[type="checkbox"][disabled]:checked + .switch-overlay .activo { + color: #007a3e; + font-weight: bold; } + +.switch-overlay { + border-radius: 16px; + color: black !important; + font-size: 1.6rem; + height: 32px; + left: 0; + position: absolute; + top: -1px; + width: 100%; + overflow: hidden; } + +.btn-slider-on { + left: -22px; + text-align: left; + padding-left: 0px; + display: inline-block; + font-family: "Omnes-ATT-W02"; + height: 32px; + line-height: 32px; + position: absolute; + top: 1px; + width: 80px; } + +.btn-slider-off { + display: inline-block; + font-family: "Omnes-ATT-W02"; + height: 32px; + line-height: 32px; + position: absolute; + top: 1px; + width: 80px; + right: 0px; + text-align: right; + padding-left: 50%; + padding-right: 0px; } + +.switch-handle { + border-radius: 50%; + display: inline-block; + height: 26px; + left: 50px; + position: absolute; + top: 3px; + width: 26px; } + +.activo { + display: block; + font-size: 0.1px; + line-height: 40px; + overflow: hidden; } + .activo:before { + background-image: none; + border-left: 3px solid #007a3e; + content: " "; + height: 18px; + left: 22px; + margin: 2px auto; + position: absolute; + top: 5px; + width: 0; } + +.inactivo { + font-size: 0.1px; + line-height: 40px; } + .inactivo:before { + background-image: none; + border: 3px solid #959595; + border-radius: 100%; + content: " "; + display: block; + position: absolute; + top: 4px; + right: 3px; + height: 16px; + width: 16px; } + +.btn-switch.focused { + outline: 1px dotted #000; + outline-offset: 5px; } + +.btn-swtich-label { + display: flex; } + .btn-swtich-label > span { + flex: 1; } + +.b2b-switch-span:hover { + cursor: pointer; } + +.btn-switch { + background-color: #fff; + border: 1px solid #d2d2d2; + border-radius: 16px; + box-shadow: 0 4px 5px -5px rgba(0, 0, 0, 0.15) inset, 0 5px 5px -5px rgba(0, 0, 0, 0.15); + height: 32px; + overflow: hidden; + position: relative; + width: 80px; + user-select: none; } + .btn-switch input[type="radio"] { + left: 0; + margin: 0; + opacity: 0; + position: absolute; + top: 0; + transition: none; } + .btn-switch input[type="button"] { + left: 0; + margin: 0; + opacity: 0; + position: absolute; + top: 0; + transition: none; } + .btn-switch fieldset + .switch-overlay { + left: 0; + transition: all .3s linear .0s; } + .btn-switch fieldset + .switch-overlay .switch-handle.onstate { + background-color: #007a3e; + background: linear-gradient(to bottom, #008744 0%, #007a3e 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid transparent; } + .btn-switch fieldset + .switch-overlay { + left: 0; + transition: all .3s linear .0s; } + .btn-switch fieldset + .switch-overlay .switch-handle.onstate { + background-color: #007a3e; + background: linear-gradient(to bottom, #008744 0%, #007a3e 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid transparent; } + .btn-switch fieldset + .switch-overlay { + /*left: -48px;*/ + transition: all .3s linear .0s; } + .btn-switch fieldset + .switch-overlay .switch-handle { + background-color: #f2f2f2; + background: linear-gradient(to bottom, #fcfcfc 0%, #f2f2f2 100%); + transition: background-color 0.3s linear 0s; + border: 1px solid #d2d2d2; } + .btn-switch fieldset[disabled] + .switch-overlay { + left: 0; + width: 100% !important; + background-color: #d2d2d2; + color: #959595; + cursor: not-allowed !important; } + .btn-switch fieldset[disabled] + .switch-overlay .btn-slider-on { + display: none; } + .btn-switch fieldset[disabled] + .switch-overlay .switch-handle { + display: none; } + .btn-switch fieldset[disabled] + .switch-overlay .btn-slider-off { + left: 0; + text-align: center; + padding: 0; } + .btn-switch fieldset[disabled]:checked + .switch-overlay { + left: 0; + width: 100% !important; + background-color: #fff; } + .btn-switch fieldset[disabled]:checked + .switch-overlay .btn-slider-off { + display: none; } + .btn-switch fieldset[disabled]:checked + .switch-overlay .switch-handle { + display: none; } + .btn-switch fieldset[disabled]:checked + .switch-overlay .btn-slider-on { + display: block; + text-align: center; + padding: 0; + color: #007a3e !important; + font-weight: bold; } + .btn-switch fieldset[disabled]:checked + .btn-slider-on { + display: block; } + .btn-switch fieldset[disabled] + .btn-slider-on + .switch-handle { + width: 100%; + margin: 0; } + .btn-switch fieldset[disabled] + .btn-slider-on + .switch-handle + .btn-slider-off { + display: block; } + .btn-switch .switch-overlay-element:hover { + cursor: pointer; } + +.switch-overlay { + border-radius: 16px; + color: black !important; + font-size: 1.6rem; + height: 32px; + left: 0; + position: absolute; + top: -1px; + width: 100%; + overflow: hidden; } + +.btn-slider-on { + left: -22px; + text-align: left; + padding-left: 0px; + display: inline-block; + font-family: "Omnes-ATT-W02"; + height: 32px; + line-height: 32px; + position: absolute; + top: 1px; + width: 80px; } + +.btn-slider-off { + display: inline-block; + font-family: "Omnes-ATT-W02"; + height: 32px; + line-height: 32px; + position: absolute; + top: 1px; + width: 80px; + right: 0px; + text-align: right; + padding-left: 50%; + padding-right: 0px; } + +.switch-handle { + border-radius: 50%; + display: inline-block; + height: 26px; + left: 50px; + position: absolute; + top: 3px; + width: 26px; } + +.btn-switch.focused { + outline: 1px dotted #000; + outline-offset: 5px; } + +table { + max-width: 100%; + background-color: transparent; + border-collapse: collapse; + border-spacing: 0; + width: 100%; + margin-bottom: 20px; } + +table caption { + text-align: left; } + +table thead th { + vertical-align: bottom; } + +table th, +table td { + padding: 19px 20px; + line-height: 1; + font-size: 1.4rem; + text-align: left; + vertical-align: top; + word-wrap: break-word; } + +table th { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 1.6rem; + font-weight: normal; + color: #333333; + padding: 13px 20px; } + +table tbody td { + border-left: 1px solid #d2d2d2; + border-top: 1px solid #d2d2d2; } + +table tbody td:first-child { + border-left: none; } + +.tiny-accordion.iconleft.accordion-table-layout .toggle-header, +.tiny-accordion.iconleft.accordion-table-layout .toggle-header + .accordion-content, +.tiny-accordion.iconleft.accordion-table-layout .inactive-toggle-header { + padding: 0 0 0 50px; } + +.faux-table-cell, +.inactive-toggle-header .faux-table-cell { + display: table-cell; + width: 100%; + padding: 13px 0 10px 0; + font-size: 16px; + color: #333333; } + +.accordion-content .faux-table-cell { + display: table-cell; + width: 100%; + padding: 0 0 10px 0; } + +.faux-table-cell:last-child { + text-align: right; + min-width: 100px; + max-width: 150px; + width: 1%; + background-color: #f2f2f2; + color: #333333; + font-size: 14px; + border-left: 1px solid #d2d2d2; + padding: 0 20px 0 10px; } + +.tiny-accordion.iconleft.accordion-table-layout .toggle-header.opened .hide-when-expanded { + opacity: 1; } + +.tiny-accordion.iconleft.accordion-table-layout .toggle-header.opened .hide-when-expanded { + opacity: 0; + transition: opacity .3s linear .2s; } + +@media (max-width: 767px) { + table th, + table td { + padding: 19px 10px; } + table th:first-child, + table td:first-child { + padding: 19px 15px; } } + +.data-row-list ul > li { + background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20viewport%3D%220%200%201%201%22%20style%3D%22width%3A100%25%3B%20height%3A1px%3B%22%3E%3Cstyle%3Eline%7Bstroke%3Argba(153%2C153%2C153%2C1)%3Bstroke-width%3A2%3B%7D%3C%2Fstyle%3E%3Cline%20y2%3D%221%22%20y1%3D%221%22%20x1%3D%221%22%20x2%3D%22100%25%22%20stroke-dasharray%3D%221%2C%203%22%2F%3E%3C%2Fsvg%3E") !important; } + +table { + border-bottom: 1px solid #d2d2d2; } + +table th, +table td { + padding: 15px 15px 10px; } + +.data-row .col-1 { + white-space: nowrap; + padding: 15px 15px 0 15px; + position: relative; + font-family: "Omnes-ATT-W02"; + font-size: 1.4rem; + border-top: 1px solid #d2d2d2; } + +.data-row.has-button .col-1 { + padding: 0; } + +.complex-table .data-row .col-1 { + color: #0568ae; + cursor: pointer; } + +.b2b-custom-complex-table .b2b-actions-container { + float: left; + margin-top: 20px; } + +.b2b-custom-complex-table .b2b-delete-text { + margin: 0 10px 0 10px; } + +.b2b-custom-complex-table .b2b-items-selected { + margin: 0 20px 0 15px; } + +.b2b-custom-complex-table .b2b-apply-btn { + margin-right: 10px; + margin-bottom: 0; } + +.b2b-custom-complex-table .b2b-table-actions-flyout .icon-controls-down { + margin-left: 10px; } + +.b2b-custom-complex-table .b2b-accordion-icon { + margin-left: 5px; + margin-right: 10px; } + +.b2b-custom-complex-table .b2b-account-number { + margin: 0px; } + +.b2b-custom-complex-table .b2b-first-column { + white-space: nowrap; + color: #0568AE; } + .b2b-custom-complex-table .b2b-first-column .b2b-first-column-label { + display: inline-block; + margin-left: 34px; + margin-top: 0; + position: relative; + top: -12px; } + +.b2b-custom-complex-table .b2b-expand-row td { + padding-bottom: 30px; + border-bottom: 2px solid #959595; } + +.b2b-custom-complex-table .b2b-complex-heading { + font-family: "Omnes-ATT-W02-Medium"; + color: #191919; + font-size: 14px; } + +.b2b-custom-complex-table .b2b-anchor-wrapping-icon { + text-decoration: none; } + +.b2b-custom-complex-table th { + color: #191919; } + +.b2b-custom-complex-table .data-row.opened { + border-top: 2px solid #959595; } + +.b2b-custom-complex-table tr.opened .b2b-account-number { + color: #191919; } + +@media (max-width: 479px) { + .b2b-custom-complex-table .b2b-apply-btn { + margin-right: 0px; + width: 100%; + margin-top: 30px; + margin-bottom: 20px; } + .b2b-custom-complex-table .btn-clear { + width: 100%; } } + +@media (max-width: 767px) { + .b2b-custom-complex-table .b2b-external-sort-div { + float: none; + margin-top: 30px; } + .b2b-custom-complex-table .b2b-sort-container { + display: inline-block; + width: 10%; } + .b2b-custom-complex-table .b2b-external-sort-margin { + display: inline-block; + width: 80%; } + .b2b-custom-complex-table .b2b-actions-container { + float: none; + margin-top: 0; } } + +.data-row.opened { + box-shadow: 0 -2px 0 0 #d2d2d2; } + +.data-row.opened td, +.data-row.opened th { + border-left: 1px solid transparent; + border-bottom: 1px solid transparent; } + +.data-row.opened + .data-row-list { + box-shadow: 0 1px 0 0 #d2d2d2; } + +.data-row.opened + .data-row-list > td { + padding-top: 0; } + +.data-row.opened + .data-row-list + .data-row.opened { + box-shadow: 0 -1px 0 0 #d2d2d2; } + +.data-row .col-1 i { + top: -1px; + margin-right: 10px; + display: inline-block !important; } + +.data-row-list th:first-child { + background-color: inherit !important; + border-top: none; + padding: 0 15px 15px; + font-family: "Omnes-ATT-W02"; + font-size: 1.4rem; } + +.data-row-list ul { + margin: 0 0 0 30px; } + +.data-row-list ul > li:before { + display: none; } + +.data-row-list ul > li { + /* background-image in tables.less */ + background-position: left 13px; + background-repeat: repeat-x; + background-size: 4px 1px; + display: table; + padding-left: 0; + width: 100%; } + +.data-row-list li div { + display: table-cell; + background-color: white; + float: left; + text-align: left; + padding-left: 0; + padding-right: 7px; } + +.data-row-list li div + div { + float: right; + text-align: right; + padding-right: 0; + padding-left: 7px; } + +.complex-table td:nth-child(1), +.complex-table td:nth-child(2), +.complex-table td:nth-child(3), +.complex-table td:nth-child(4), +.complex-table td:nth-child(5), +.complex-table td:nth-child(6), +.complex-table td:nth-child(7), +.complex-table td:nth-child(8), +.complex-table td:nth-child(9) { + white-space: nowrap; } + +th:nth-child(8) { + word-wrap: break-word; + word-spacing: 0; } + +.align-col-right { + text-align: right; } + +.complex-table th:not(:first-child), +.complex-table td:not(:first-child) { + text-align: right; } + +.striped tbody > tr td { + background-color: transparent !important; } + +.striped tbody > tr.data-row.odd, +.striped tbody > tr.data-row.odd + .data-row-list, +.striped tbody > tr.data-row.odd + .data-row-list li div { + background-color: #f2f2f2 !important; } + +.striped tbody > tr:not(.data-row):nth-child(even) { + background-color: #f2f2f2; } + +.b2b-table-div .b2b-external-sort-margin .selectWrap { + width: 290px; + position: relative; + display: inline-table; + margin-bottom: 0px; } + +.b2b-external-sort-div { + float: right; + padding-bottom: 30px; } + +.b2b-external-sort-div .sortButton { + font-size: 36px; + border: 1px solid #ccc; + background: #FFF; + border-radius: 6px; + text-align: center; + background: linear-gradient(#fcfcfc, #f2f2f2); + width: 1em; + height: 1em; } + +.b2b-external-sort-label { + padding-bottom: 10px; } + +.b2b-external-sort-div a:hover { + cursor: pointer; } + +.b2b-external-sort-div a:hover, .b2b-external-sort-div a:focus { + text-decoration: none; } + +.b2b-external-sort-label label { + position: relative; } + +.b2b-external-sort-margin { + margin-right: 13px !important; } + +.b2b-table-sorter-icon [class*="icon-arrows-"]:before { + font-size: 20px; + vertical-align: middle; } + +@media screen and (max-width: 950px) { + .b2b-external-sort-margin .selectWrap { + bottom: 0px !important; } } + +.tablesorter-default .tablesorter-header.sorter-false .tablesorter-header-inner { + background: 0 0; + cursor: default; } + +.tablesorter-default .tablesorter-header .tablesorter-header-inner { + /* background-image: url(images/tables/upanddown.png);*/ + background-position: center right; + background-repeat: no-repeat; + cursor: pointer; + white-space: normal; + display: inline-block; + vertical-align: baseline; + zoom: 1; + *display: inline; + *vertical-align: auto; + /* padding: 0 24px 0 0;*/ } + +.tablesorter-default .tablesorter-header.sorter-false .tablesorter-header-inner { + padding: 0; } + +.tablesorter-default .tablesorter-header.tablesort-sortable .tablesorter-header-inner span { + margin-right: 24px; + display: inline-block; } + +/* +.tablesorter-default thead .headerSortUp .tablesorter-header-inner,.tablesorter-default thead .tablesorter-headerAsc .tablesorter-header-inner,.tablesorter-default thead .tablesorter-headerSortUp .tablesorter-header-inner { + background-image: url(images/tables/up.png); +} + +.tablesorter-default thead .headerSortDown .tablesorter-header-inner,.tablesorter-default thead .tablesorter-headerDesc .tablesorter-header-inner,.tablesorter-default thead .tablesorter-headerSortDown .tablesorter-header-inner { + background-image: url(images/tables/down.png); +} +*/ +.tablesorter-default thead .headerSortUp .tablesorter-header-inner, +.tablesorter-default thead .tablesorter-headerAsc .tablesorter-header-inner, +.tablesorter-default thead .tablesorter-headerSortUp .tablesorter-header-inner, +.tablesorter-default thead .headerSortDown .tablesorter-header-inner, +.tablesorter-default thead .tablesorter-headerDesc .tablesorter-header-inner, +.tablesorter-default thead .tablesorter-headerSortDown .tablesorter-header-inner { + padding-right: 0; + line-height: 16px; } + +.tablesorter-default thead .headerSortUp .tablesorter-header-inner:after, +.tablesorter-default thead .tablesorter-headerAsc .tablesorter-header-inner:after, +.tablesorter-default thead .tablesorter-headerSortUp .tablesorter-header-inner:after { + font-family: 'icoPrimary' !important; + speak: none; + font-style: normal; + font-size: 24px; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 14px; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -moz-user-select: none; + -ms-user-select: none; + -webkit-user-select: none; + user-select: none; + content: "\ea3c"; + /* position: relative;*/ + position: absolute; + text-decoration: inherit; + display: inline-block; + transform: rotate(180deg); + margin-left: -22px; + margin-top: 2px; } + +.tablesorter-default thead .headerSortDown .tablesorter-header-inner:after, +.tablesorter-default thead .tablesorter-headerDesc .tablesorter-header-inner:after, +.tablesorter-default thead .tablesorter-headerSortDown .tablesorter-header-inner:after { + font-family: 'icoPrimary' !important; + speak: none; + font-style: normal; + font-size: 24px; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 14px; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -moz-user-select: none; + -ms-user-select: none; + -webkit-user-select: none; + user-select: none; + content: "\ea3c"; + /* position: relative;*/ + position: absolute; + text-decoration: inherit; + display: inline-block; + margin-left: -22px; + margin-top: 2px; } + +.tablesorter-search-highlight { + font-weight: 700; } + +.tablesorter-headerRow th:focus { + outline: thin dotted #666; + outline-offset: -1px; } + +.data-row-opened td { + border-left: 1px solid transparent; + border-bottom: 1px solid transparent; } + +.expandable-table td:first-child, +.expandable-table th:first-child { + min-width: 130px; } + +.b2b-icon-add-maximize { + font-size: 22px; } + +.b2b-column-checkbox { + position: relative; + left: 32px; + top: -13px; } + +.b2b-expand-row { + background-color: white !important; } + +.b2b-expand-tables .b2b-td-noTopBorder { + border-top: 0px; } + +.b2b-expand-tables .b2b-td-noLeftBorder { + border-left: 0px; } + +.b2b-leading-dots:before { + float: left; + width: 0; + white-space: nowrap; + content: ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . " ". . . . . . . . . . . . . . . . . . . . "; } + +.b2b-leading-dots { + overflow: hidden; } + .b2b-leading-dots span { + background: #FFFFFF; } + .b2b-leading-dots span:first-child { + padding-right: 10px; } + .b2b-leading-dots span + span { + padding-left: 10px; } + +.b2b-table-message { + font-family: "Omnes-ATT-W02"; } + .b2b-table-message .b2b-magnify-glass { + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2036%2036%22%20enable-background%3D%22new%200%200%2036%2036%22%3E%3Cpath%20d%3D%22M27.847%208.26c-1.805-1.803-4.202-2.795-6.751-2.795-2.548%200-4.945.993-6.749%202.796-1.803%201.803-2.796%204.2-2.796%206.75%200%201.879.543%203.681%201.576%205.242l-7.059%207.059c-.357.356-.554.831-.554%201.336-.001.505.196.98.554%201.337.357.356.832.552%201.336.552.503%200%20.977-.196%201.336-.553l7.047-7.048c1.576%201.062%203.402%201.622%205.309%201.622%202.55%200%204.948-.993%206.751-2.796%201.803-1.804%202.796-4.201%202.796-6.751%200-2.549-.993-4.947-2.796-6.751zm-6.761.96c3.186%200%205.778%202.592%205.778%205.778%200%203.186-2.592%205.778-5.778%205.778-3.186%200-5.778-2.592-5.778-5.778%200-3.185%202.592-5.778%205.778-5.778z%22%20fill%3D%22%23767676%22%2F%3E%3C%2Fsvg%3E"); + background-repeat: no-repeat; + background-position: center; + height: 50px; } + .b2b-table-message .b2b-alert { + font-size: 50px; } + .b2b-table-message .b2b-loading-dots { + font-size: 50px; + margin-bottom: 20px; } + .b2b-table-message .b2b-message { + text-align: center; + padding-bottom: 45px; + padding-top: 40px; + border-style: solid; + border-width: 1px; + border-top: none; + padding-bottom: 45px; + border-color: #d2d2d2; + width: 100%; + min-height: 220px; } + .b2b-table-message .b2b-error-title { + font-family: "Omnes-ATT-W02"; + color: #444444; + line-height: 26px; + margin-top: 10px; } + .b2b-table-message .b2b-message-title { + color: #444; + font-family: "Omnes-ATT-W02"; } + +.b2b-table-scrollbar { + border: 1px solid; + width: 651px; + position: relative; } + .b2b-table-scrollbar .b2b-table-inner-container { + width: 650px; + padding-left: 150px; + overflow-x: scroll; } + .b2b-table-scrollbar th:first-child { + background-color: #FFFFFF; } + .b2b-table-scrollbar td:first-child { + background-color: #FFFFFF; + border-top: 1px solid #cccccc; + border-right: 1px solid #cccccc; + margin-top: -0.5px; } + .b2b-table-scrollbar tr { + th: nth-child(2), td; } + .b2b-table-scrollbar tr :nth-child(2) { + border-left: none; } + .b2b-table-scrollbar tr:last-child > td:first-child { + border-bottom: 1px solid #cccccc; } + +.b2b-scrollbar-arrow-left { + float: left; + margin: 10px; } + +.b2b-scrollbar-arrow-right { + float: right; + clear: right; + margin: 10px; } + .b2b-scrollbar-arrow-right.btn-arrow .btn { + margin-right: 0; } + +.b2b-table-scrollbar ::-webkit-scrollbar { + height: 10px; } + +.b2b-table-scrollbar ::-webkit-scrollbar-thumb { + background: #666666; + border-radius: 5px; } + +.tabs { + margin-left: 0; + margin-bottom: 20px; + list-style: none; } + +.tabs > li > a { + display: block; } + +.tabs > li > a:hover, +.tabs > li > a:focus { + text-decoration: none; + background-color: #d2d2d2; } + +.tabs > .pull-right { + float: right; } + +.tabs:before, +.tabs:after { + display: table; + content: ""; + line-height: 0; } + +.tabs:after { + clear: both; } + +.tabs > li { + float: left; } + +.tabs > li > a { + padding-right: 20px; + padding-left: 20px; + margin-right: 3px; + line-height: 16px; } + +.tabs { + margin: 0; } + +.tabs > li { + margin-bottom: -1px; } + +.tabs > li:first-child { + margin-left: 20px; } + +.tabs > li > a { + padding: 12px 20px; + border: 1px solid #d2d2d2; + border-radius: 6px 6px 0 0; + background-color: #f2f2f2; + color: #5a5a5a; + border-color: #d2d2d2; } + +.tabs > li > a { + margin-right: 6px; } + +.tabs > li > a, +.tabs > li > a:hover, +.tabs > li > a:focus { + background-image: none; + background-color: #ffffff; + color: #5a5a5a; + border-color: #d2d2d2; + border-bottom: 1px solid transparent; + cursor: pointer; } + +.tabs.tabs-justified, +.tabs.promo-tabs { + width: 100%; + border-bottom: 0; + margin-bottom: -1px; } + +.tabs.tabs-justified > li, +.tabs.promo-tabs > li { + display: table-cell; + float: none; + width: 1%; + border-left: 1px solid #d2d2d2; } + +.tabs.tabs-justified > li.active, +.tabs.promo-tabs > li.active { + position: relative; + z-index: 1000; } + +.tabs.tabs-justified > li > a { + padding-right: 5px; + padding-left: 5px; } + +.tabs.tabs-justified > li > a, +.tabs.promo-tabs > li > a { + text-align: center; } + +.tabs.promo-tabs > li > a { + padding: 0; + margin: 0; + border-radius: 0; + border: none; + color: #0568ae; + font-size: 1.2rem; + text-align: center; + padding: 6px 10px 10px; + border-top: 4px solid #e6e6e6; + filter: none; + border-bottom: 1px solid #d2d2d2; + background-color: #f9f9f9; } + +.tabs > li:last-child > a { + margin-right: 0; } + +.tabs.promo-tabs > li.active > a { + color: #333333; + border-top: 4px solid #ea7400; + border-bottom-color: white; + background-color: #fff !important; + filter: none; + cursor: default; } + +.tabs.promo-tabs > li:first-child { + border-left: none; } + +.tabs.promo-tabs > li > a img { + max-width: inherit; + max-height: 39px; + margin: 0 auto 5px auto; + display: block; } + +.tabbable:before, +.tabbable:after { + display: table; + content: ""; + line-height: 0; } + +.tabbable:after { + clear: both; } + +.tab-content { + overflow: auto; + border: 1px solid #e6e6e6; } + +.tabs.promo-tabs + .tab-content { + border: none; + border-bottom: 1px solid #e6e6e6; } + +.tab-content > .tab-pane { + padding: 10px 15px; } + +.tab-content.noborder { + border: none; } + +.tab-content.noborder > .tab-pane { + padding: 0; } + +.tab-content > .tab-pane { + display: none; } + +.tab-content > .active { + display: block; } + +.tabs.promo-tabs > li > a { + font-size: 2.0rem; + height: 70px; + padding: 20px 20px 24px; + background-color: #FFFFFF; + border-top: 5px solid #FFFFFF; + white-space: nowrap; } + +.tabs.promo-tabs > li.active > a { + border-top: 5px solid #0574ac; } + +.tabs.promo-tabs > li > a:hover { + color: #333333; } + +.tabs.promo-tabs > li { + width: auto; } + +.tabs > li[disabled="disabled"] > a:hover { + cursor: not-allowed; } + +.b2b-tags { + background-color: #f2f2f2; + -webkit-transition: all .3s ease-out; + -moz-transition: all .3s ease-out; + transition: all .3s ease-out; + margin: 3px 5px 3px 0; + padding: 2px 15px; + border-radius: 6px; + border: 1px solid #c9c9c9; + display: inline-block; } + .b2b-tags .tags__item { + font-size: 14px; + vertical-align: baseline; + zoom: 1; + color: #333; } + .b2b-tags .tags__item i { + color: #0574ac; + font-size: 14px; + font-weight: bold; + margin-left: 10px; } + .b2b-tags .tags__item i:hover { + cursor: pointer; } + .b2b-tags .tags__item i:focus { + outline: thin dotted #666; } + .b2b-tags .tags__item:last-child { + margin-right: 0; } + .b2b-tags .tags__item:hover { + text-decoration: none; } + .b2b-tags .tags__item:focus { + outline: 1px dotted #666; } + +.tooltip-size-control { + display: block; } + +.tooltip { + display: inline-block; + height: 20px; + vertical-align: middle; + margin: 1px 0 0 7px; } + +p .tooltip { + margin: -3px 7px 0 0; } + +label .tooltip { + margin: 1px 0 0 7px; } + +.tooltip .icon-tooltip { + background: none; + border: none; + display: inline-block; + font-size: 20px; + height: 20px; + margin: 0; + position: relative; + width: 20px; } + +.tooltip .icon-tooltip:before { + top: 0; } + +.tooltip .icon-tooltip:focus { + text-decoration: none; + outline: 1px dotted black; } + +.tooltip.active .icon-tooltip:focus { + outline: none; } + +.tooltip .arrow { + display: none; + border-color: transparent; + border-style: solid; + background-color: #0568ae; + height: 20px; + width: 20px; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + opacity: 0; + transform: rotate(45deg); + z-index: 20; } + +.tooltip.active .icon-tooltip[data-placement="top"] .arrow { + display: block; + bottom: 32px; + top: auto; + border-width: 0 1px 1px 0; } + +.tooltip.active .icon-tooltip[data-placement="bottom"] .arrow { + border-width: 1px 0 0 1px; + display: block; + bottom: -33px; + top: auto; } + +.tooltip.active .arrow { + opacity: 1; } + +.tooltip .closingtooltip { + display: block; } + +.tooltip.active .closingtooltip { + display: none; } + +.tooltip-wrapper { + position: absolute; + margin-top: 20px; + left: 15px; + right: 15px; + display: none; + opacity: 0; + z-index: 1010; + text-align: left; } + +.helpertext { + background-color: #0568ae; + border: 1px solid transparent; + border-radius: 6px; + color: #fff; + display: none; + margin: 0; + padding: 25px; + position: relative; + text-align: left; + width: 100%; + top: 0; + z-index: 1009; } + +.tooltip .helpertext { + position: absolute; } + +.tooltip.active .icon-tooltip[data-placement="bottom"] + .tooltip-wrapper .helpertext { + bottom: inherit; + top: 19px; } + +.tooltip.active .icon-tooltip[data-placement="top"] + .tooltip-wrapper .helpertext { + top: inherit; + bottom: 38px; } + +.tooltip.active .tooltip-wrapper { + opacity: 1; + display: block; + margin-top: 0; } + +.tooltip.active .tooltip-wrapper .helpertext { + display: block; } + +.tooltip-onclick .btn.icon-tooltip { + border: medium none; + box-shadow: none; + color: #0568ae; + font-size: 20px; + height: 34px; + line-height: 36px; + margin: 0; + min-width: 50px; + padding: 0; + position: absolute; + right: 0; + top: 0; } + +.isIE .btn.icon-tooltip:focus:after { + top: 9px; + left: 15px; } + +.tooltip-onclick .icon-tooltip:before { + display: inline; + position: relative; } + +.tooltip-onclick textarea + .reset-field + .icon-tooltip { + top: 4px; + right: 5px; + min-width: 40px; } + +.tooltip-onclick.active .helpertext:before, +.tooltip-onfocus.active .helpertext:before { + background-color: #0568ae; + border-color: transparent; + border-style: solid; + border-width: 1px 1px 0 0; + content: ""; + display: block; + height: 15px; + left: 17px; + margin: 0; + position: absolute; + top: -7px; + transform: rotate(-45deg); + width: 15px; } + +.tooltip-onclick.active .helpertext { + display: block; + opacity: 1; + margin: 14px 0 0; } + +.tooltip-onclick.active .helpertext:before { + left: inherit; + right: 18px; } + +.tooltip-onclick .reset-field { + right: 37px; } + +.tooltip-onclick .reset-field:before { + position: relative; + top: -1px; } + +.tooltip-onfocus.active .helpertext { + display: block; + margin: 14px 0 10px 0; } + +.popover-title { + display: block; + font-size: 14px; + font-family: "Omnes-ATT-W02-Medium"; + font-weight: bold; + margin-bottom: 8px; + white-space: normal; } + +.popover-content { + display: block; + font-size: 12px; + font-family: "Omnes-ATT-W02"; + line-height: 1.5rem; + white-space: normal; } + +.popover-content span, +.popover-content p { + line-height: 1.5rem; } + +.popover-content p:last-child { + margin-bottom: 0; } + +.tooltip .tooltip-element { + position: relative; } + +.tooltip .icon-tooltip:hover { + text-decoration: none; } + +.tooltip.active .tooltip-element[data-placement="top"] .arrow { + display: block; + bottom: 32px; + top: auto; } + +.tooltip.active .tooltip-element[data-placement="bottom"] .arrow { + display: block; + border-color: transparent transparent #0574ac; + bottom: -33px; + top: auto; } + +.tooltip.active .tooltip-element[data-placement="bottom"] + .tooltip-wrapper .helpertext { + bottom: inherit; + top: 19px; } + +.tooltip.active .tooltip-element[data-placement="top"] + .tooltip-wrapper .helpertext { + top: inherit; + bottom: 38px; } + +.b2b-tree { + padding: 0 10px 0 10px; + width: 320px; } + .b2b-tree ul { + list-style: none; + list-style-type: none; } + .b2b-tree a { + display: block; + padding: 0 0 5px 30px; + line-height: 22px; + margin-left: -10px; + font-size: 1.4rem; + outline-offset: -1px; } + .b2b-tree li:focus { + outline: none; } + .b2b-tree li:focus > a { + outline: thin dotted #666; + outline-offset: -1px; } + .b2b-tree ul li { + border-left: 1px solid #ccc; } + .b2b-tree ul li.bg > a { + color: #333; + background-image: url("../style/images/treebg.png"); + margin-left: 15px; + padding-left: 5px; } + .b2b-tree ul li .b2b-tree-tooltip { + display: none; + position: absolute; + top: -25px; + left: 100%; + white-space: nowrap; + margin-left: 10px; + z-index: 1010; + font-family: "Omnes-ATT-W02"; + font-size: 12px; } + .b2b-tree ul li .b2b-tree-tooltip-content { + background-color: #0568ae; + margin-left: 9px; + border-radius: 6px; + color: #fff; + padding: 25px; } + .b2b-tree ul li .b2b-tree-arrow-left { + width: 0; + height: 0; + border-top: 10px solid transparent; + border-bottom: 10px solid transparent; + border-right: 10px solid #0568ae; + position: absolute; + top: 25px; } + .b2b-tree ul li.activeTooltip > a .b2b-tree-tooltip { + display: block; } + .b2b-tree ul ul { + padding: 0 0 0 20px; } + .b2b-tree ul > li { + position: relative; + line-height: 18px; } + .b2b-tree a > span.b2b-tree-node-icon { + background-color: #FFF; + display: inline; + margin: 0; + padding: 0; + position: absolute; + left: -11px; + top: 0; + line-height: 14px; + width: 11px; } + .b2b-tree a > span.b2b-tree-node-icon > i { + font-size: 20px; } + .b2b-tree a:only-child { + color: #0574ac; } + .b2b-tree a:only-child > span.b2b-tree-node-icon { + left: -11px; + border-radius: 50%; + line-height: 7px; + top: 0; } + .b2b-tree a:only-child > span.b2b-tree-node-icon > i { + background-color: inherit; + background: #fff; } + .b2b-tree a > span.b2b-tree-node-icon > i.icon-circle { + background-color: inherit; + background: #fff; + font-size: 10px; } + .b2b-tree a.b2b-locked-node:after { + content: "\ec58"; + float: right; + font-family: 'icoSecurityalerts' !important; } + .b2b-tree a:hover .b2b-locked-node:after { + text-decoration: none; } + .b2b-tree ul li:first-child > a:only-child > span.b2b-tree-node-icon { + left: -11px; + border-radius: 50%; + line-height: 12px; } + .b2b-tree ul li:last-child > a:only-child > span.b2b-tree-node-icon { + height: 27px; + background-color: #fff; } + .b2b-tree li a + ul { + height: 0; + overflow: hidden; } + .b2b-tree li a.active + ul { + height: auto; + overflow: visible; } + .b2b-tree li a.grp { + font-family: "Omnes-ATT-W02-Italic"; } + .b2b-tree li a.grp.active { + color: #333; } + .b2b-tree span.end { + left: -6px !important; + top: 5px !important; } + .b2b-tree span.first-link { + width: 3px !important; + height: 15px !important; + top: 0px !important; + left: -2px !important; + background: #fff; } + +.b2b-tree-checkbox { + padding: 0 10px 0 10px; + width: 320px; } + .b2b-tree-checkbox ul { + list-style: none; + list-style-type: none; } + .b2b-tree-checkbox a { + display: block; + padding: 0 0 5px 30px; + line-height: 22px; + margin-left: -10px; + font-size: 14px; + outline-offset: -1px; } + .b2b-tree-checkbox li:focus { + outline: none; } + .b2b-tree-checkbox li:focus > a { + outline: thin dotted #666; + outline-offset: -1px; } + .b2b-tree-checkbox ul li { + border-left: 1px solid #ccc; } + .b2b-tree-checkbox ul ul { + padding: 0 0 0 20px; } + .b2b-tree-checkbox ul > li { + position: relative; + line-height: 18px; } + .b2b-tree-checkbox a > span.nodeIcon { + background-color: #FFF; + display: inline; + margin: 0; + padding: 0; + position: absolute; + left: -11px; + top: 0; + line-height: 14px; + width: 11px; } + .b2b-tree-checkbox a > span.nodeIcon > i { + font-size: 20px; } + .b2b-tree-checkbox a > span.nodeIcon.end { + margin-top: 10px; } + .b2b-tree-checkbox a:only-child { + color: #0574ac; } + .b2b-tree-checkbox a:only-child > span.nodeIcon { + left: -11px; + border-radius: 50%; + line-height: 7px; + top: 0; } + .b2b-tree-checkbox a:only-child > span.nodeIcon > i { + background-color: inherit; + background: #fff; } + .b2b-tree-checkbox a > span.nodeIcon > i.icon-circle { + background-color: inherit; + background: #fff; + font-size: 10px; } + .b2b-tree-checkbox ul li:first-child > a:only-child > span { + left: -11px; + border-radius: 50%; + line-height: 12px; + top: 0px; } + .b2b-tree-checkbox ul li:first-child > a:only-child > span.end { + margin-top: 0px; } + .b2b-tree-checkbox ul li:first-child > a:only-child > span i.icon-circle { + top: 8px; } + .b2b-tree-checkbox ul li:last-child > a:only-child > span { + height: 34px; + background-color: #fff; } + .b2b-tree-checkbox li a + ul { + height: 0; + overflow: hidden; } + .b2b-tree-checkbox li a.active + ul { + height: auto; } + .b2b-tree-checkbox li a.grp { + font-family: "Omnes-ATT-W02-Italic"; } + .b2b-tree-checkbox span.end { + left: -6px !important; } + .b2b-tree-checkbox .checkbox { + margin-bottom: 0px; + margin-top: 2px; + font-size: 14px; } + .b2b-tree-checkbox .checkbox input:indeterminate + .skin:after { + content: "\2014"; + padding-left: 2px; + font-family: inherit !important; + line-height: inherit !important; } + .b2b-tree-checkbox span.first-link { + width: 3px !important; + height: 15px !important; + top: 0px !important; + left: -2px !important; + background: #fff; } + +.b2b-widget-window { + width: 147px; + right: 5px; + top: 60px; + position: absolute; + border: 1px solid #ccc; + background-color: #fff; + border-radius: 8px; + z-index: 1000; } + .b2b-widget-window li { + margin: 15px; } + +.b2b-widget-container { + background-color: #fff; + border-radius: 8px; + border: 1px solid #ccc; + position: relative; } + .b2b-widget-container .b2b-widget-header { + font-family: "Omnes-ATT-W02"; + color: #333; + height: 55px; + padding-left: 15px; + padding-top: 19px; } + .b2b-widget-container .b2b-widget-header .header { + font-size: 18px; } + .b2b-widget-container .b2b-widget-header-icons { + font-size: 16px; + color: #0574ac; } + +.b2b-widget-header-icons button { + border: none; + background: transparent; + color: #0574ac; } + .b2b-widget-header-icons button:focus { + outline-style: solid; + outline-width: 1px; + outline-color: #0574ac; } + .b2b-widget-header-icons button:first-child { + margin-right: 0px; } + +.b2b-widget-container .b2b-widget-content { + height: 325px; + margin: 0; + padding: 20px; + position: relative; + border-top: 1px solid #ccc; } + +.b2b-widget-content .form-row:first-child { + margin-top: 0; } + +.b2b-widget-header-icons button.icon-controls-gear:focus, .b2b-widget-header-icons button.icon-close:focus { + outline: thin dotted #666; } + +.b2b-widget-header .icon-close:before { + content: '-'; + display: inline-block; + margin: 0; + padding: 0; + outline: none; } + +.b2b-widget-window .arrow_box { + background: #fff; + border: 1px solid #ccc; } + +.b2b-widget-window.arrow_box:after, .b2b-widget-window.arrow_box:before { + bottom: 100%; + left: 75%; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none; } + +.b2b-widget-window.arrow_box:after { + border-color: rgba(255, 255, 255, 0); + border-bottom-color: #fff; + border-width: 10px; + margin-left: 1px; } + +.b2b-widget-window.arrow_box:before { + border-color: rgba(204, 204, 204, 0); + border-bottom-color: #ccc; + border-width: 11px; + margin-left: 0px; } + +/************************** Overrides for Filters ***************************/ +.filter-container .filter-header h2 { + line-height: 1 !important; + margin: 0 !important; } + +.filter-container .icon-spinner:before { + content: none; } + +.filter-container .fixed-230-subnav { + margin: 10px !important; + width: inherit !important; } + +.filter-container .unlinked:focus { + outline: thin dotted #666 !important; } + +.filter-container .unlinked.active { + color: inherit !important; } + +.filter-container .fixed-230-subnav a > i { + background: none; } + +.filter-container .fixed-230-subnav ul { + margin: 0 0 10px 10px; } + +/************************** Overrides for Filters ***************************/ +.row .filter-container { + background-color: #fff; } + +.filter-header { + overflow: hidden; + padding: 20px 0; + position: relative; } + +.filter-header h2 { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 2.4rem; + margin-bottom: 0; } + +.filter-selected { + border-top: 1px solid #ccc; + padding-top: 20px; } + +.filter-selected > span { + font-size: 1.3rem; + text-transform: uppercase; } + +.filter-selected > a.clear-all-filters { + float: right; + font-size: 1.4rem; } + +.filter-selected > span, +.filter-selected > a.clear-all-filters { + font-family: Omnes-ATT-W02-Medium; } + +.filter-selected-group { + padding-top: 15px; } + +.filter-selected-badge { + background-color: #f2f2f2; + border-radius: 15px; + display: inline-block; + font-size: 1.4rem; + margin-bottom: 10px; + padding: 0 0 0 12px; } + +.filter-selected-badge .icon-controls-optionsoff { + background: rgba(0, 0, 0, 0) none repeat scroll 0 0; + border: medium none; + font-size: 2.5em; + margin: 0; + padding: 0; } + +.filters .fixed-230-subnav > ng-transclude > div:first-child { + border-top: 1px solid #ccc; } + +.filters .fixed-230-subnav > ng-transclude > div { + border-bottom: 1px solid #ccc; } + +.filter-results { + align-items: center; + border-bottom: 1px solid #ccc; + display: flex; + flex-wrap: wrap; + height: 50px; + -webkit-justify-content: space-between; + -ms-flex-pack: justify; + justify-content: space-between; } + +.filter-results-sortby > span { + text-transform: uppercase; } + +.filter-results-view .icon-content-gridguide { + font-size: 2em; + margin-right: 0; } + +.filter-container .fixed-230-subnav > ng-transclude > div > a { + font-size: 1.8rem; + margin: 0; + padding: 15px 20px 15px 0; + color: #0574ac !important; + cursor: pointer !important; + font-family: "Omnes-ATT-W02" !important; + outline-offset: inherit !important; + position: relative; + height: auto; + width: auto; } + +.filter-container .fixed-230-subnav a > i { + right: 0; + top: 15px; } + +.filter-container .fixed-230-subnav .icon-collapsed:before, .filter-container .fixed-230-subnav .icon-expanded:before { + float: right; } + +.filter-container .fixed-230-subnav ul.collapse { + position: inherit; + transition: height 0.5s ease; + height: 0; + overflow: hidden; } + +.filter-container .checkbox .icon-spinner { + height: 24px; + position: absolute; + width: 24px; } + +.fixed-230-subnav.affix { + margin: -28px 0 0; } + +#nav-menu .b2b-menu, +#nav-menu .fixed-230-subnav { + margin: 0; } + +.b2b-menu > li, +.fixed-230-subnav > div { + border-bottom: 1px solid #ccc; + line-height: 4.0rem; } + +.b2b-menu > li:first-child, +.fixed-230-subnav > li:first-child { + border-top: 1px solid #ccc; } + +.b2b-menu div > a, +.fixed-230-subnav div > a { + color: #0574ac; + cursor: pointer; + display: block; + font-family: "Omnes-ATT-W02"; + font-size: 1.4rem; + margin: 0; + outline-offset: -1px; + padding: 0 10px; + position: relative; } + +.fixed-230-subnav div > a.live { + font-family: "Omnes-ATT-W02-Medium"; + color: #666; } + +.fixed-230-subnav > ng-transclude > div li > a { + display: block; + font-size: 1.4rem; + line-height: 20px; } + +.fixed-230-subnav > ng-transclude > div li > a.active { + font-family: "Omnes-ATT-W02-Medium"; + text-decoration: none; + color: #666; } + +#nav-menu .fixed-230-subnav a > i { + top: 10px; } + +.fixed-230-subnav > li > a.active > i:after { + display: none; } + +.b2b-menu ul, +.fixed-230-subnav ul { + margin: 0 0 10px 0; } + +.b2b-menu ul div a, +.fixed-230-subnav ul div a { + padding: 0 10px; } + +.unlinked { + outline: medium none !important; + text-decoration: none !important; } + +@media (max-width: 1024px) { + .filter-container .fixed-230-subnav { + margin: 0 20px; + width: auto; } + .filter-container .fixed-230-subnav > li { + margin: 0; } + .row .filter-container { + display: none; + height: 100%; + left: 0; + position: fixed; + overflow: auto; + top: 0; + transition: all 0.5s ease 0s; + width: 285px; + z-index: 9999; } + .filter-header { + padding-left: 20px; } + .filter-selected { + margin: 0 20px 10px; } } + +.b2b-pane-selector-wrapper { + width: 100%; + display: block; + border-top: solid 1px #ccc; + border-bottom: solid 1px #ccc; } + .b2b-pane-selector-wrapper .side-nav { + width: 20% !important; + display: inline-block; + float: left; } + .b2b-pane-selector-wrapper .pane-container { + width: 80%; + vertical-align: top; + margin: 0; + padding-top: 30px; + border-left: solid 1px #ccc; + font-family: "Omnes-ATT-W02"; + display: none; } + .b2b-pane-selector-wrapper .pane-container.active { + display: inline-block; } + .b2b-pane-selector-wrapper .pane-container .pane-container-top { + padding-left: 15px; } + .b2b-pane-selector-wrapper .pane-container .panes { + display: -webkit-flex; + display: flex; + border-top: solid 1px #ccc; + margin-top: 30px; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block { + height: inherit; + overflow-y: auto; + border-right: solid 1px #ccc; + position: relative; + flex: 1; + -webkit-flex: 1; + /* Safari 6.1+ */ + -ms-flex: 1; + /* IE 10 */ } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block:focus { + outline: dotted 1px #333333; } + .b2b-pane-selector-wrapper .pane-container .search-block { + position: relative; + float: right; } + .b2b-pane-selector-wrapper .pane-container .search-block input[type="search"]:focus { + padding-right: 40px; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row p { + margin-top: 15px; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block div { + border-bottom: solid 1px #ccc; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row { + display: block; + padding: 19px 14px 19px 14px; + margin-top: 0px; + border: dotted 1px transparent; + border-bottom: solid 1px #ccc; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row:focus { + border: dotted 1px #333333 !important; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row:last-child { + border-bottom: none; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block > .no-content { + text-align: center; + border-bottom: none; + display: block; + position: absolute; + top: 45%; + left: 0; + right: 0; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block div:last-child { + border-bottom: none; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row span.margin-chk { + margin: 15px 15px 0px 15px; + float: left; } + .b2b-pane-selector-wrapper .pane-container .panes div.pane-block .form-row .checkbox-selectall { + margin: 0px 0 0 24px !important; } + .b2b-pane-selector-wrapper .side-nav li { + font-family: "Omnes-ATT-W02-Medium"; + border: none; + border-top: solid 1px #ccc; + display: block !important; + width: auto !important; + margin-left: 0px !important; } + .b2b-pane-selector-wrapper .side-nav li.active { + background-color: #f6f6f6; + position: inherit !important; } + .b2b-pane-selector-wrapper .side-nav li.active > a { + font-size: 16px; + color: #333; + text-decoration: none; + border: none; + background-color: transparent; + padding: 20px 15px; + display: block; + height: auto; + border-left: 4px solid #0574ac; } + .b2b-pane-selector-wrapper .side-nav li > a { + font-size: 16px; + color: #333; + text-decoration: none; + border: none; + background-color: transparent; + padding: 20px 15px; + display: block; + height: auto; + text-align: left; } + .b2b-pane-selector-wrapper .side-nav li > a:focus { + border-right: dotted 1px #333333; } + .b2b-pane-selector-wrapper .side-nav li:first-child { + border-top: none; + margin-left: none !important; } + +.btn-circular { + font-family: "font-regular", "Omnes-ATT-W02"; + font-size: 1.6rem; + font-weight: normal; + border: none; + background-color: transparent; + padding: 5px 0 0; + top: -3px; + color: #191919; + position: relative; } + +.btn-circular::-moz-focus-inner { + padding: 0; + border: 0; } + +.btn-circular:hover, +.btn-circular:focus, +.btn-circular:active { + text-decoration: underline; } + +.btn-circular:hover .btn, +.btn-circular:focus .btn, +.btn-circular:active .btn { + border: 1px solid transparent; + text-decoration: none; } + +.btn-circular:hover .btn.btn-primary-promo, +.btn-circular:focus .btn.btn-primary-promo, +.btn-circular:active .btn.btn-primary-promo { + background: #c96100; } + +.btn-circular:hover .btn.btn-primary-functional, +.btn-circular:focus .btn.btn-primary-functional, +.btn-circular:active .btn.btn-primary-functional { + background: #0563a6; } + +.btn-circular:hover .btn.btn-secondary, +.btn-circular:focus .btn.btn-secondary, +.btn-circular:active .btn.btn-secondary { + background: #f0f0f0; } + +.btn-circular:hover .btn.btn-primary-special, +.btn-circular:focus .btn.btn-primary-special, +.btn-circular:active .btn.btn-primary-special { + background: #007339; } + +.btn-circular:focus { + outline: 1px dotted #666; } + +.btn-circular .btn { + border: 1px solid transparent; + border-radius: 100%; + display: inline-block; + height: 36px; + margin-bottom: 0; + margin-right: 7px; + max-width: 36px; + min-width: 20px; + padding: 0; + margin-top: -4px; + vertical-align: middle; + width: 36px; } + +.btn-circular .btn > [class*="icon-"] { + bottom: 0; + color: #fff; + display: block; + height: 36px; + left: -1px; + line-height: 0; + margin: 0; + position: relative; + right: 0; + text-indent: 0; + top: -1px; + width: 36px; } + +.btn-circular .btn > [class*="icon-"]:before { + font-size: 1.6rem; + height: 100%; + left: 0; + letter-spacing: 0; + line-height: 36px; + position: relative; + top: 0; + width: 100%; } + +.btn-circular .btn > .icon-right { + -webkit-margin-start: 1px; } + +.btn-circular.disabled:hover .btn, +.btn-circular[disabled]:hover .btn, +.btn-circular.disabled:focus .btn, +.btn-circular[disabled]:focus .btn, +.btn-circular.disabled:active .btn, +.btn-circular[disabled]:active .btn { + background: #d2d2d2; } + +.btn-circular .btn.btn-secondary [class*="icon-"] { + color: #0568ae; } + +.btn-circular:disabled, +.btn-circular:disabled [class*="icon-"], +.btn-circular.disabled, +.btn-circular.disabled [class*="icon-"] { + color: #959595 !important; + cursor: not-allowed !important; + text-decoration: none !important; } + +.btn-circular .btn.btn-small { + height: 20px; + max-width: 20px; + min-width: 20px; + width: 20px; } + +.btn-circular .btn.btn-small > .icon-left { + -moz-padding-start: 1px; } + +.btn-circular .btn.btn-small [class*="icon-"] { + height: 20px; + width: 20px; } + +.btn-circular .btn.btn-small [class*="icon-"]:before { + font-size: 10px; + height: 20px; + line-height: 20px; + top: 0; + width: 20px; } + +.btn-circular .btn.btn-small > .icon-right { + -webkit-margin-start: 0; } + +.btn-circular .btn.btn-small .icon-left:before, +.btn-circular .btn.btn-small [class*="icon-"]:before { + left: 0; } + +.btn-circular .btn.btn-large [class*="icon-"]:before { + height: 48px; + width: 48px; + line-height: 48px; } + +.btn-circular .btn.btn-large [class*="icon-"]:before { + font-size: 112%; } + +.btn-circular .btn-large, +.btn-circular .btn-large [class*="icon-"] { + height: 48px; + width: 48px; + max-width: 48px; } + +.btn-circular .btn.btn-secondary [class*="icon-"] { + margin-top: 0px; + margin-bottom: 0px; } + +.input-append .field-group + .btn-circular { + top: 0; + padding: 0; } + +.input-append .field-group + .btn-circular .btn { + margin-left: 15px; + margin-right: 0; + margin-top: 0; } + +.filmstrip button.btn-circular .btn.btn-secondary { + border-color: #5a5a5a; } + +.filmstrip button.btn-circular:hover .btn.btn-secondary, +.filmstrip button.btn-circular:active .btn.btn-secondary, +.filmstrip button.btn-circular:focus .btn.btn-secondary { + background-color: initial; + border-color: #0568ae; } + +.filmstrip button.btn-circular[disabled] .btn.btn-secondary { + border-color: #d2d2d2; } + +.filmstrip button.btn-circular[disabled] [class*="icon-"] { + color: #d2d2d2 !important; } + +.bg-att-digital-black .btn-circular, +.promo-overlay .btn-circular { + color: #fff; } + +.bg-att-digital-black .btn-circular .btn, +.promo-overlay .btn-circular .btn { + border: 1px solid #fff; } + +.bg-att-digital-black .btn-circular .btn [class*="icon-"], +.promo-overlay .btn-circular .btn [class*="icon-"] { + color: #fff; } + +.bg-att-digital-black .btn-circular .btn.btn-small, +.promo-overlay .btn-circular .btn.btn-small { + top: 0; } + +.btn-circular.left-arrow .btn, +.btn-circular.right-arrow .btn { + background: #fff; + box-shadow: none; + margin: 0; } + +.btn-circular.left-arrow:hover .btn, +.btn-circular.left-arrow:focus .btn, +.btn-circular.right-arrow:hover .btn, +.btn-circular.right-arrow:focus .btn { + border-color: #0568ae; } + +.btn-circular.left-arrow:disabled .btn, +.btn-circular.right-arrow:disabled .btn { + border-color: #cdcdcd; } + +.filmstrip { + font-size: 12px; + font-family: "font-regular", "Omnes-ATT-W02", Arial; + position: relative; + overflow: hidden; + border: 0; + opacity: 1; + overflow: inherit; + display: -ms-flexbox !important; + display: flex !important; + -ms-flex-flow: row wrap; + flex-flow: row wrap; + height: inherit; + transition: height .3s linear 0; } + +.filmstrip .filmstrip-wrapper { + position: relative; + display: -ms-inline-flexbox; + display: inline-flex; + -ms-flex-positive: 1; + flex-grow: 1; + -ms-flex-negative: 1; + flex-shrink: 1; + -ms-flex-preferred-size: 0px; + flex-basis: 0px; + max-width: 100%; + overflow: hidden; } + +.filmstrip .left-arrow.hide + .filmstrip-wrapper, +.filmstrip h3 + .filmstrip-wrapper { + -ms-flex: 1 100%; + flex: 1 100%; } + +.filmstrip * { + box-sizing: border-box; } + +.filmstrip .filmstrip-wrapper:focus, +.filmstrip .contents:focus { + outline: 1px dotted #191919; + outline-offset: -1px; } + +.filmstrip a { + text-decoration: none; } + +.filmstrip a:hover .item-label, +.filmstrip a:focus .item-label { + text-decoration: underline; } + +.filmstrip h3.header { + -ms-flex-pack: center; + justify-content: center; + font-size: 24px; + text-align: center; + font-weight: 500; + color: #191919; + white-space: nowrap; + -ms-flex: 1 100%; + flex: 1 100%; } + +.filmstrip .item-label { + color: #0568ae; + font-size: 12px; + line-height: 14px; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + text-overflow: ellipsis; + white-space: normal; } + +.filmstrip.service-list .item, +.filmstrip.prod-list .item { + width: 110px; } + +.filmstrip.service-list .item.view-more > a, +.filmstrip.prod-list .item.view-more > a, +.filmstrip.service-list .item.cat-link > a, +.filmstrip.prod-list .item.cat-link > a { + height: 170px; } + +.filmstrip.service-list .item img.item-image, +.filmstrip.prod-list .item img.item-image { + max-width: 110px; + max-height: 82px; + margin: 0 auto 20px; + display: block; } + +.filmstrip.service-list .item-label, +.filmstrip.prod-list .item-label { + max-height: 28px; } + +.filmstrip.service-list .starrating-wrap, +.filmstrip.prod-list .starrating-wrap { + margin-top: 3px; } + +.filmstrip.service-list .starrating > li, +.filmstrip.prod-list .starrating > li { + margin-right: 3px; } + +.filmstrip.service-list .star-total-reviews, +.filmstrip.prod-list .star-total-reviews { + font-size: 11px; + color: #191919; } + +.filmstrip.service-list .item-price, +.filmstrip.prod-list .item-price { + font-weight: 600; + color: #191919; + font-size: 14px; } + +.filmstrip.service-list .right-arrow, +.filmstrip.prod-list .right-arrow, +.filmstrip.service-list .left-arrow, +.filmstrip.prod-list .left-arrow { + height: 175px; } + +.filmstrip.video-list .item.view-more > a, +.filmstrip.video-list .item.cat-link > a { + height: 204px; } + +.filmstrip.video-list-micro, +.filmstrip.video-list { + font-size: 12px; + color: #0568ae; } + +.filmstrip.video-list-micro .item, +.filmstrip.video-list .item { + width: 176px; + margin-top: 0; + vertical-align: top; } + +.filmstrip.video-list-micro .item:hover .video-duration, +.filmstrip.video-list .item:hover .video-duration, +.filmstrip.video-list-micro .item:focus .video-duration, +.filmstrip.video-list .item:focus .video-duration { + height: 0px; } + +.filmstrip.video-list-micro .item:hover .video-duration:after, +.filmstrip.video-list .item:hover .video-duration:after, +.filmstrip.video-list-micro .item:focus .video-duration:after, +.filmstrip.video-list .item:focus .video-duration:after { + opacity: .55; } + +.filmstrip.video-list-micro .item-image, +.filmstrip.video-list .item-image { + border-radius: 8px; + overflow: hidden; + position: relative; + margin-bottom: 20px; } + +.filmstrip.video-list-micro .item-image .video-duration, +.filmstrip.video-list .item-image .video-duration { + text-align: right; + background: rgba(0, 0, 0, 0.55); + width: 100%; + position: absolute; + right: 0; + padding-right: 10px; + bottom: 0; + height: 20px; + color: #ffffff; + line-height: 22px; + transition: height 300ms ease-in-out; + border-radius: 0 0 8px 8px; } + +.filmstrip.video-list-micro .item-image .video-duration:after, +.filmstrip.video-list .item-image .video-duration:after { + content: ''; + width: 100%; + height: 132px; + position: absolute; + left: 0; + bottom: 0; + border-radius: 8px; + background: black; + opacity: 0; + transition: opacity 300ms ease-in-out; } + +.filmstrip.video-list-micro .item-label, +.filmstrip.video-list .item-label { + max-height: 42px; + width: 100%; + text-align: center; + -webkit-line-clamp: 3; + margin-bottom: 10px; } + +.filmstrip.video-list-micro .icon-video-play, +.filmstrip.video-list .icon-video-play { + top: 50%; + left: 50%; + display: inline-block; + position: absolute; + width: 50px; + height: 50px; + z-index: 1; + transform: translate3d(-50%, -50%, 0); } + +.filmstrip.video-list-micro .icon-video-play:before, +.filmstrip.video-list .icon-video-play:before { + display: inline-block; + content: ''; + width: inherit; + height: inherit; + background-image: url("../style/images/icon-video-play.png"); + background-size: cover; } + +.filmstrip.video-list-micro .left-arrow, +.filmstrip.video-list .left-arrow, +.filmstrip.video-list-micro .right-arrow, +.filmstrip.video-list .right-arrow { + height: 132px; } + +.filmstrip.video-list-micro .item { + width: 110px; } + +.filmstrip.video-list-micro .item.view-more > a, +.filmstrip.video-list-micro .item.cat-link > a { + height: 154px; } + +.filmstrip.video-list-micro .item .video-duration:after { + height: 82px; } + +.filmstrip.video-list-micro .icon-video-play { + width: 30px; + height: 30px; } + +.filmstrip.video-list-micro .icon-video-play:before { + width: inherit; + height: inherit; + background-image: url("../style/images/icon-video-play.png"); + background-repeat: no-repeat; + background-size: cover; } + +.filmstrip.video-list-micro .right-arrow, +.filmstrip.video-list-micro .left-arrow { + height: 82px; } + +.filmstrip.icons-list .item { + width: 110px; + text-align: center; } + +.filmstrip.icons-list .item.view-more > a, +.filmstrip.icons-list .item.cat-link > a { + height: 98px; } + +.filmstrip.icons-list .item-image { + margin: 0 auto; + fill: #0568ae; + margin-bottom: 20px; } + +.filmstrip.icons-list .item-image image { + height: 100%; + width: 100%; + max-height: 100%; + max-width: 100%; } + +.filmstrip.icons-list .left-arrow, +.filmstrip.icons-list .right-arrow { + height: 98px; } + +.filmstrip .contents { + overflow-x: auto; + overflow-y: hidden; + white-space: nowrap; + -ms-flex: 1 auto; + flex: 1 auto; + -ms-flex-preferred-size: 100%; + flex-basis: 100%; + -moz-user-select: none; + -ms-user-select: none; + -webkit-user-select: none; + user-select: none; } + +.filmstrip .contents::-webkit-scrollbar { + width: 10px; + height: 0px; } + +.filmstrip .contents.no-animate > .item, +.filmstrip .contents.items-in > .item { + transition: all 500ms linear; + opacity: 1; + left: 0; } + +.filmstrip .contents.snapping { + -webkit-overflow-scrolling: auto; } + +.filmstrip .item { + display: inline-block; + position: relative; + vertical-align: top; + padding-bottom: 0px; + margin-left: 0px; + opacity: 0; + left: 70px; + min-width: initial; } + +.filmstrip .item:first-child { + margin-left: 0px; } + +.filmstrip .item:focus { + outline: 1px dotted #000000; + outline-offset: -1px; } + +.filmstrip .item.view-more span, +.filmstrip .item.cat-link span { + white-space: pre-wrap; } + +.filmstrip .item.view-more:focus span, +.filmstrip .item.cat-link:focus span, +.filmstrip .item.view-more:hover span, +.filmstrip .item.cat-link:hover span { + text-decoration: underline; } + +.filmstrip .item.cat-link .btn-circular { + margin-bottom: 7px; } + +.filmstrip .item:focus .item-label, +.filmstrip .item:hover .item-label { + text-decoration: underline; } + +.filmstrip .item a { + display: block; } + +.filmstrip .item .btn-arrow { + margin-bottom: 12px; } + +.filmstrip .item .valign-middle { + top: 50%; + transform: translate3d(0, -50%, 0); + position: relative; } + +@media (min-width: 1025px) { + .filmstrip { + position: relative; } + .filmstrip .item { + margin-right: 20px; + /*collapse items in mobile view*/ } + .filmstrip .item:focus { + outline: 1px dotted #000000; } + .filmstrip .item.view-more, + .filmstrip .item.cat-link { + display: none; } + .filmstrip .left-arrow { + margin-right: 20px; } + .filmstrip .right-arrow { + margin-left: 20px; } } + +@media (max-width: 1024px) { + .filmstrip .item.view-more ~ li { + display: none !important; } + .filmstrip .item.view-more span { + line-height: 17px; + font-size: 14px; } + .filmstrip .item.view-more span:before { + content: ''; + display: block; + position: relative; + width: 36px; + height: 36px; + margin: 0 auto; + background: url("../style/images/moreapplications.svg"); + background-repeat: no-repeat; + background-size: contain; } + .filmstrip .item.cat-link > a { + outline-offset: -8px; } + .filmstrip .item.cat-link span { + line-height: 17px; + font-size: 14px; } + .filmstrip .item.view-more, + .filmstrip .item.cat-link { + border-left: 1px solid #ccc; + margin-right: 0px; } + .filmstrip .item.view-more > a, + .filmstrip .item.cat-link > a { + width: inherit; } + .filmstrip .item.view-more > a > span, + .filmstrip .item.cat-link > a > span { + top: 50%; + display: inline-block; + position: relative; + transform: translate3d(0, -50%, 0); + transform-origin: 50%; + text-align: center; + width: inherit; } } + +@media (min-width: 768px) { + .filmstrip h3.header { + margin-bottom: 50px; } + .filmstrip.prod-list, + .filmstrip.service-list { + height: 100%; + max-height: 260px; } + .filmstrip.prod-list .filmstrip-wrapper, + .filmstrip.service-list .filmstrip-wrapper { + height: 180px; } + .filmstrip.prod-list .contents, + .filmstrip.service-list .contents { + height: 210px; } + .filmstrip.prod-list .item, + .filmstrip.service-list .item { + height: 175px; } + .filmstrip.video-list { + height: 285px; } + .filmstrip.video-list .filmstrip-wrapper { + height: 200px; } + .filmstrip.video-list .contents { + height: 230px; } + .filmstrip.video-list .item { + height: 200px; } + .filmstrip.video-list-micro { + height: 230px; } + .filmstrip.video-list-micro .filmstrip-wrapper { + height: 145px; } + .filmstrip.video-list-micro .contents { + height: 175px; } + .filmstrip.video-list-micro .item { + height: 150px; } + .filmstrip.icons-list { + height: 185px; } + .filmstrip.icons-list .filmstrip-wrapper { + height: 100px; } + .filmstrip.icons-list .contents { + height: 130px; } + .filmstrip.icons-list .item { + height: 105px; } + .filmstrip.icons-list .item .item-image { + height: 50px; + width: 50px; } + .filmstrip.icons-list .item-image > [class*="icon-"] { + font-size: 6rem; } } + +@media (min-width: 768px) and (max-width: 1024px) { + .filmstrip .left-arrow.hidden-tablet + .filmstrip-wrapper { + -ms-flex-preferred-size: 100%; + flex-basis: 100%; + width: 100%; } + .filmstrip .item { + margin-right: 30px; } } + +@media (max-width: 767px) { + .filmstrip .left-arrow.hidden-phone + .filmstrip-wrapper { + -ms-flex-preferred-size: 100%; + flex-basis: 100%; + width: 100%; } + .filmstrip h3.header { + margin-bottom: 25px; + -ms-flex-pack: start; + justify-content: flex-start; } + .filmstrip .item { + margin-right: 10px; } + .filmstrip.prod-list, + .filmstrip.service-list { + height: 230px; } + .filmstrip.prod-list .filmstrip-wrapper, + .filmstrip.service-list .filmstrip-wrapper { + height: 175px; } + .filmstrip.prod-list .contents, + .filmstrip.service-list .contents { + height: 200px; } + .filmstrip.prod-list .item, + .filmstrip.service-list .item { + height: 175px; } + .filmstrip.video-list { + height: 260px; } + .filmstrip.video-list .filmstrip-wrapper { + height: 200px; } + .filmstrip.video-list .contents { + height: 230px; } + .filmstrip.video-list .item { + height: 205px; } + .filmstrip.video-list-micro { + height: 205px; } + .filmstrip.video-list-micro .filmstrip-wrapper { + height: 145px; } + .filmstrip.video-list-micro .contents { + height: 175px; } + .filmstrip.video-list-micro .item { + height: 155px; } + .filmstrip.icons-list { + height: 160px; } + .filmstrip.icons-list .filmstrip-wrapper { + height: 100px; } + .filmstrip.icons-list .contents { + height: 130px; } + .filmstrip.icons-list .item { + height: 105px; } + .filmstrip.icons-list .item .item-image { + width: 40px; + height: 40px; } + .filmstrip.icons-list .item .item-image > [class*="icon-"] { + font-size: 5rem; } + .filmstrip .view-more span:before { + margin-bottom: 8px !important; } } + +.isMobile .filmstrip .filmstrip-wrapper { + -ms-flex-preferred-size: 100%; + flex-basis: 100%; } + +.isMobile .filmstrip .left-arrow, +.isMobile .filmstrip .right-arrow { + display: none; } + +.filmstrip .final-rating { + color: #191919; + font-size: 11px; } + +@keyframes progress-bar-stripes { + from { + background-position: 0 0; } + to { + background-position: 80px 0; } } + +.b2b-progress { + background-color: #d2d2d2; + border-radius: 4px; + height: 14px; + margin-bottom: 2rem; + min-width: 250px; + outline: 1px solid transparent; + overflow: hidden; + padding: 0; + position: relative; } + +.b2b-progress .b2b-progress-bars { + background-color: #666; + border-radius: 4px; + display: -ms-flexbox; + display: flex; + height: 0; + width: 0; + border-width: 7px 0; + border-style: solid; + border-color: #666; } + +.b2b-progress-arrow { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: end; + justify-content: flex-end; } + +.b2b-progress-success .b2b-progress-bars, +.b2b-progress .b2b-progress-bars-success { + border-color: #007a3e; } + +.b2b-progress-warning .b2b-progress-bars, +.b2b-progress .b2b-progress-bars-warning { + border-color: #ea7400; } + +.b2b-progress-danger .b2b-progress-bars, +.b2b-progress .b2b-progress-bars-danger { + border-color: #cf2a2a; } + +.b2b-progress.increment { + display: -ms-flexbox; + display: flex; } + +.b2b-progress.increment .b2b-progress-bars:first-child:not(:last-child) { + border-right: none; + border-radius: 4px 0 0 4px; } + +.b2b-progress.increment .b2b-progress-bars:last-child:not(:first-child) { + border-left: none; + border-radius: 0 4px 4px 0; } + +.b2b-progress.increment .b2b-progress-bars + .b2b-progress-bars:not(:last-child) { + border-left: none; + border-right: none; + border-radius: 0; } + +.b2b-progress.increment .b2b-progress-bars:not(:first-child) { + margin-left: 1px; } + +.b2b-usage-bars { + display: table; + float: none; + width: 100%; + margin-bottom: 1px; + margin-bottom: .6rem; + line-height: 1; } + +.b2b-usage-bars > .b2b-usage-text { + display: table-cell; + width: 1%; } + +.b2b-usage-bars .b2b-usage-text { + font-size: 1.6rem; + font-family: "font-medium", "Omnes-ATT-W02-Medium"; } + +.b2b-usage-bars .b2b-usage-text:first-child { + white-space: nowrap; } + +.b2b-usage-bars .b2b-usage-text.text-right { + vertical-align: top; + font-size: 1.6rem; + width: auto !important; } + +.b2b-usage-bars .b2b-usage-text.text-description { + font-size: 1.4rem; + font-family: "font-regular", "Omnes-ATT-W02"; } + +.b2b-usage-bars.billing-cycle { + line-height: 1.3; + margin-bottom: .3rem; } + +.b2b-usage-bars.billing-cycle .b2b-usage-text { + font-size: 1.6rem; } + +.b2b-usage-bars.billing-cycle .b2b-usage-text.text-right { + vertical-align: bottom; } + +.b2b-progress.autocolor [data-percentage="1"], +.b2b-progress.autocolor [data-percentage="2"], +.b2b-progress.autocolor [data-percentage="3"], +.b2b-progress.autocolor [data-percentage="4"], +.b2b-progress.autocolor [data-percentage="5"], +.b2b-progress.autocolor [data-percentage="6"], +.b2b-progress.autocolor [data-percentage="7"], +.b2b-progress.autocolor [data-percentage="8"], +.b2b-progress.autocolor [data-percentage="9"], +.b2b-progress.autocolor [data-percentage="10"] +.b2b-progress.autocolor [data-percentage^="2"], +.b2b-progress.autocolor [data-percentage^="3"], +.b2b-progress.autocolor [data-percentage^="4"], +.b2b-progress.autocolor [data-percentage^="5"], +.b2b-progress.autocolor [data-percentage="60"], +.b2b-progress.autocolor [data-percentage="61"], +.b2b-progress.autocolor [data-percentage="62"], +.b2b-progress.autocolor [data-percentage="63"], +.b2b-progress.autocolor [data-percentage="64"] { + border-color: #007a3e; } + +.b2b-progress.autocolor [data-percentage="65"], +.b2b-progress.autocolor [data-percentage="66"], +.b2b-progress.autocolor [data-percentage="67"], +.b2b-progress.autocolor [data-percentage="68"], +.b2b-progress.autocolor [data-percentage="69"], +.b2b-progress.autocolor [data-percentage^="7"], +.b2b-progress.autocolor [data-percentage^="8"] { + border-color: #ea7400; } + +.b2b-progress.autocolor [data-percentage^="9"], +.b2b-progress.autocolor [data-percentage="100"] { + border-color: #cf2a2a; } +/********************* Utility CSS Starts **********************/ +.offscreen-text { + position: absolute; + left: -10000px; + top: auto; + width: 1px; + height: 1px; + overflow: hidden; } + +/********************* Utility CSS Ends **********************/ +/* Fix for alignment issue on Cancel link inside modal */ +.modal-footer > .cta-button-group { + line-height: 40px; } + +/* .att-dark-green { // Not used + color: #007a3e; +} */ +.colors-off-msg { + display: none; } + +button .colors-off-msg { + position: relative; } + +.ds2-no-colors .colors-off-msg { + display: block; } + +.ds2-no-colors [data-colordatatext] button .colors-off-msg { + font-size: 1.1rem; + line-height: normal; + padding: 5px 0; + position: absolute; + top: 0; + white-space: normal; + width: 60px; } + +/* Not used +.make-all-white * { + color: #fff; +} +.make-all-white a { + text-decoration: underline; +} */ +.loader > span { + display: block; + padding-top: 20px; } + +.modal > .loader { + left: 50%; + margin-left: -25px; + margin-top: -25px; + position: absolute; + top: 50%; } + +#pageLevelLoader.modal { + background-color: transparent; + border: none; + box-shadow: none; + top: 40%; } + +.modal.fade .loader { + display: none; } + +.modal.fade.in .loader { + display: block; } + +.btn.disabled[data-loading-text] { + padding: 0 19px 0 18px; + line-height: 46px; } + +.btn.disabled[data-loading-text] img { + position: relative; + top: 2px; } + +/* Seems to already be in docs.css +.fixed-230.leftnav { + position: relative; +} +.fixed-230-subnav { + margin: 10px; +} +.fixed-230-subnav > li:first-child { + border-top: none; +} +.fixed-230-subnav > li { + border-bottom: 1px solid #d2d2d2; +} +.fixed-230-subnav > li > a { + display: block; + font-size: 1.4rem; + line-height: normal; + margin: 0 -9px; + padding: 11px 35px 12px 9px; + outline-offset: 0; + position: relative; +} +.fixed-230-subnav > li > a.live { + color: #333333; + font-family: "Omnes-ATT-W02-Medium"; +} +.fixed-230-subnav a > i { + right: 10px; + margin: 0; + position: absolute; + top: 10px; +} +.fixed-230-subnav a > i:after { + display: none; +} +.fixed-230-subnav > li li > a { + display: block; + font-size: 1.4rem; + line-height: 18px; +} +.fixed-230-subnav > li li > a.active { + color: #333333; + font-family: "Omnes-ATT-W02-Medium"; + text-decoration: none; +} +.fixed-230-subnav ul { + margin: 0 0 10px; +} */ +.unlinked { + color: #0568ae !important; + font-family: "Omnes-ATT-W02" !important; } + +.unlinked.active { + color: inherit !important; } + +/* @media (max-width: 767px) { + .row.has-leftnav { + flex-wrap: wrap; + } + .row.has-leftnav .fluid-space { + padding-right: 0; + } + .row .fixed-230 { + background-color: #fff; + width: auto; + } + .row .leftnav { + background-color: #fff !important; + display: block !important; + } + .fixed-230-subnav { + margin: 10px 0 0; + width: 100%; + } + .fixed-230-subnav > li { + margin-left: -15px; + margin-right: -15px; + } + .fixed-230-subnav > li:first-child { + border-top: 1px solid #d2d2d2; + } + .fixed-230-subnav > li > a { + margin: 0; + } + .fixed-230-subnav a:hover, + .fixed-230-subnav a:focus { + text-decoration: none !important; + } + .fixed-230-subnav > li li > a { + padding: 5px 10px; + } + .fixed-230-subnav > li li > a.active { + color: inherit; + font-family: "Omnes-ATT-W02-Medium"; + } +} */ +@keyframes DOMinsertion { + from { + outline-color: transparent; } + to { + outline-color: transparent; } } + +@-moz-keyframes DOMinsertion { + from { + outline-color: transparent; } + to { + outline-color: transparent; } } + +@-webkit-keyframes DOMinsertion { + from { + outline-color: transparent; } + to { + outline-color: transparent; } } + +@-ms-keyframes DOMinsertion { + from { + outline-color: transparent; } + to { + outline-color: transparent; } } + +@-o-keyframes DOMinsertion { + from { + outline-color: transparent; } + to { + outline-color: transparent; } } + +.ajaxed, +.modal.fade.in .modal-header, +.modal.fade.in .modal-body, +.modal.fade.in .modal-footer { + animation-duration: 0.01s; + -o-animation-duration: 0.01s; + -ms-animation-duration: 0.01s; + -moz-animation-duration: 0.01s; + -webkit-animation-duration: 0.01s; + animation-name: DOMinsertion; + -o-animation-name: DOMinsertion; + -ms-animation-name: DOMinsertion; + -moz-animation-name: DOMinsertion; + -webkit-animation-name: DOMinsertion; } + +.dda-css-override ul.nav-tabs { + margin-bottom: 0; } + +.dda-css-override div.tab-content { + margin-top: 0; + border-top: none; } + +.dda-css-override .tab-content .prettyprint, .dda-css-override .usage .prettyprint { + max-height: 500px; + overflow-y: auto; } + +.formsWithinProcessButton { + margin-right: 0px; } + +.heading-sub-section-form { + font-size: 2.4rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; + margin-top: 10px; } + +.heading-small-form { + font-size: 1.6rem; + font-family: "Omnes-ATT-W02"; + margin-top: 0px; } + +.icon-form-sizeL { + font-size: 50px; } + +.icon-form-size { + font-size: 30px; } + +.spanformfix { + margin-right: 15px !important; } + +@media (max-width: 767px) { + .heading-sub-section-form { + font-size: 1.8rem; + font-family: "Omnes-ATT-W02"; + margin-bottom: 20px; + padding-top: 10px; + margin-top: 30px; } + .heading-small-form { + font-size: 1.4rem; + font-family: "Omnes-ATT-W02"; + margin-top: 0px; } } + +@media (max-width: 479px) { + .icon-form-resizeL { + display: none; } + .icon-form-resize { + display: none; } + .heading-center-form { + margin-left: 20px; } } + +@media (min-width: 480px) { + .icon-form-resizeL { + display: none; } + .icon-form-resize { + display: inherit; } + .icon-center-min { + margin-top: 30px; } } + +@media (min-width: 768px) { + .icon-form-resizeL { + display: inherit; + margin-top: 30px; } + .icon-form-resize { + display: none; } + .center-form-align { + margin-top: 35px; } } + +@media (min-width: 1024px) { + .icon-form-resizeL { + display: inherit; + margin-top: 0px; } + .icon-form-resize { + display: none; } + .center-form-align { + margin-top: 5px; } } + +.data-row.has-button td.col-1 { + padding: 0; } + +.tab-content > .tab-pane { + display: none; } + +.tab-content > .active { + display: block; } + +.icon-circle:before { + background-image: url("data:image/svg+xml,%3Csvg%20baseProfile%3D%22tiny%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2036%2036%22%3E%3Ccircle%20fill%3D%22transparent%22%20stroke%3D%22%23666%22%20stroke-miterlimit%3D%2210%22%20cx%3D%2218%22%20cy%3D%2218%22%20r%3D%2216%22%2F%3E%3C%2Fsvg%3E"); + content: ""; + position: absolute; + top: 0; + z-index: 1; } + +.b2b-drag-handle { + cursor: move; + font-size: 36px; } + +a.b2b-drag-handle:hover, a.b2b-drag-handle:focus { + outline: 1px solid #0568ae; + text-decoration: none !important; } + +.b2b-drag-over { + border-bottom: 4px solid #0568ae; } + +.b2b-drag-element { + background-color: #e8e8e8; } + +.hide-drag-icon { + display: none; } +/* Flyout inputs color is not aligned */ +textarea, input { + color: #333; } + +.isIE .btn-primary.btn:focus::after, +.isIE .btn-specialty.btn:focus::after, +.isIE .btn-alt.btn:focus::after { + border: 1px dashed #fff !important; } +.b2b-config-section-container { + height: auto; + min-height: 330px; + width: 815px; + background-color: #fff; + border: 1px solid #ccc; + display: inline-table; + border-radius: 6px; } + +.b2b-config-section-first-div { + border-right: 1px solid #ccc; + height: auto; + min-height: 330px; } + +.b2b-config-section-icon-font { + font-size: 50px; + height: 31px; + line-height: 31px; } + +.b2b-config-section-padding { + padding: 20px 20px 15px 15px; + height: auto; } + +.b2b-config-sec-flyout { + position: relative; + left: 10px; + float: right; + color: #0574ac; + font-size: 16px; + font-family: "Omnes-ATT-W02"; } + +.b2b-config-sec-divider { + border-bottom: 1px solid #ccc; } + +.b2b-confi-sec-span-border { + border-right: 1px solid; + height: auto; } + +.b2b-config-sec-speed-div { + text-align: center; + margin-top: 20px; } + +.b2b-config-sec-label-font { + font-size: 16px; } + +.b2b-config-sec-expander-main { + padding: 0 5px 0px 15px; } + +.b2b-config-sec-expander-body .b2b-config-vlan-padding { + padding: 5px 15px 10px 0px; } + +.b2b-conif-sec-row-height { + height: 110px; } + +.b2b-config-sec-expander-body { + font-size: 14px; } + .b2b-config-sec-expander-body .b2b-config-vlan-data { + font-family: "Omnes-ATT-W02-Medium"; + padding-left: 15px; } + +.b2b-config-sec-expander-body-first-div { + border-top: 1px solid #ccc; } + +.b2b-config-sec-expander-body .tooltip { + position: static; + opacity: 1; } + +.b2b-config-section-container .row > [class*="span"] { + margin-right: 0px; } + +.b2b-config-vlan-icons { + font-size: 20px; + float: right; + margin-right: 0px; } + +.b2b-config-section-container .span6 { + width: 50%; } + +.b2b-config-sec-data-link-style { + position: relative; + left: 95%; + top: 30px; + border-radius: 50%; + width: 23px; + height: 23px; + background: #fff; + border: 1px solid #ccc; + color: #666666; } + +.b2b-config-sec-text-align { + text-align: center; + margin-top: 15px; + margin-bottom: 35px; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 14px; + color: #333333; } + +.b2b-config-port-text-align { + text-align: center; + margin-top: 15px; + margin-bottom: 8px; + font-family: "Omnes-ATT-W02-Medium"; + font-size: 14px; + color: #333333; } + +.b2b-config-port-text-label { + margin-top: 6px; + margin-bottom: 8px; + font-size: 14px; + text-align: center; } + +.b2b-confi-sec-last-div p { + font-size: 14px; + padding: 10px 15px 0 15px; } + +.b2b-confi-sec-router-label { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 16px; + color: #333333; + float: left; + width: 100%; + margin-bottom: 7px; } + +.b2b-config-vlan-label { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 14px; + color: #333333; + margin-top: 1px; + margin-bottom: 9px; } + +.b2b-config-vlan-info { + font-family: "Omnes-ATT-W02"; + font-size: 14px; + color: #333333; + margin-bottom: 1px; } + .b2b-config-vlan-info .icon-misc-pen { + margin-left: 8px; } + +.b2b-confi-sec-model-label { + font-family: "Omnes-ATT-W02"; + font-size: 14px; + color: #333333; } + +.b2b-confi-sec-router-info { + float: left; + width: 62%; } + +.b2b-config-sec-speed-sec { + border-right: 1px solid #ccc; } + +.b2b-config-sec-speed-label { + font-family: "Omnes-ATT-W02"; + font-size: 20px; + color: #333333; + text-align: center; } + .b2b-config-sec-speed-label i { + margin-left: 15px; } + +.b2b-config-sec-yellow-flag-div { + width: 1.6%; + background-color: #ffb81c; } + +.b2b-config-sec-expander-icons { + margin-top: 6px; } + .b2b-config-sec-expander-icons .icon-misc-trash { + margin-right: 10px; } + +.b2b-config-sec-yellow-flag .b2b-config-sec-expander-icons { + left: 40px; } + +.b2b-config-sec-expander-body-icons .icon-misc-pen { + position: relative; + left: 9px; } +.b2b-directory-listing .center { + display: block; + margin: 2em auto; } + +.b2b-directory-listing .listBox { + height: 310px; + width: 450px; + padding-left: 1px; + padding-right: 1px; + font-family: "Omnes-ATT-W02"; } + +.b2b-directory-listing .listBox:focus { + outline: thin dotted #666; } + +.b2b-directory-listing .b2b-directory-listing-no-results { + font-weight: bold; } + +.b2b-directory-listing .b2b-directory-listing-list { + font-family: "Omnes-ATT-W02"; + color: #5a5a5a; + overflow-x: hidden; + position: relative; + height: 300px; + border: 1px solid #333; + border-radius: 6px; + margin-bottom: 10px; } + +.b2b-directory-listing .b2b-directory-listing-item { + margin: 1px; + border: 1px solid transparent; + outline: none; + text-align: left; + overflow: hidden; + cursor: pointer; + padding-top: 13px; + padding-bottom: 7px; + padding-left: 15px; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + word-wrap: break-word; } + .b2b-directory-listing .b2b-directory-listing-item:focus { + border: 1px #3399FF solid; } + +.b2b-directory-listing .b2b-directory-listing-item-selected { + color: #fff; + background-color: #3399FF; } + +.b2b-directory-listing input[type="text"] { + padding-right: 30px; } + .b2b-directory-listing input[type="text"]:focus, .b2b-directory-listing input[type="text"]:hover { + padding-right: 30px; } + +.b2b-directory-listing .row .btns { + margin-right: 90px; + margin-left: -115px; + margin-top: 100px; } + +.b2b-directory-listing .btn-remove { + margin-right: auto !important; + margin-bottom: 15px; } + .b2b-directory-listing .btn-remove i { + margin-right: 0; + color: #fff; + top: -1px; } + +.b2b-directory-listing .btn-remove-all { + margin-top: 0; + margin-bottom: 61px !important; + /* need to be removed */ + margin-right: auto !important; } + .b2b-directory-listing .btn-remove-all i { + margin-right: 0; + color: #fff; + top: -1px; } + +.b2b-directory-listing .btn-add { + margin-bottom: 15px !important; } + .b2b-directory-listing .btn-add i { + margin-right: 0; + color: #fff; + top: -1px; } + +.b2b-directory-listing .btn-add-all { + margin-top: 0; + margin-bottom: 61px !important; } + .b2b-directory-listing .btn-add-all i { + margin-right: 0; + color: #fff; + top: -1px; } + +.b2b-directory-listing .btn-search[class*="btn"] { + right: 0.09rem; } + +.b2b-directory-listing .btn { + width: 130px; } + +.b2b-directory-listing-disabled { + cursor: not-allowed; } + +.b2b-directory-listing-label-heading { + margin-top: 24px; + padding-bottom: 5px; } + +.b2b-dl-list-box option { + padding-top: 13px; + padding-bottom: 7px; + padding-left: 15px; } + +.b2b-dl-modal-button-div { + padding-top: 110px; + text-align: center; } +.b2b-tmpl-notification-card { + border-radius: 6px; + height: auto; + width: 420px; + background-color: #ffffff; + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + overflow: hidden; } + .b2b-tmpl-notification-card .b2b-tmpl-card-header { + padding-left: 30px; + font-family: "Omnes-ATT-W02"; + color: #333333; + font-size: 24px; + margin-top: 2px; + display: inline-block; + min-height: 60px; + position: relative; } + .b2b-tmpl-notification-card .b2b-tmpl-card-body { + padding: 0 30px 20px; + position: relative; } + .b2b-tmpl-notification-card .b2b-tmpl-card-header-title { + margin-top: 10px; } + .b2b-tmpl-notification-card .b2b-tmpl-card-corner-button { + box-shadow: 0 -50px 0 0 #f2f2f2 inset; + height: 69px; + position: absolute; + border-color: #f2f2f2 #f2f2f2 transparent transparent; + border-style: solid; + border-width: 35px; + height: 0; + right: -295px; + top: -4px; + width: 69px; + /*Old properties */ + box-shadow: none; + transform: none; } + .b2b-tmpl-notification-card .b2b-tmpl-card-corner-button .close { + height: 48px; + right: -40px; + top: -40px; + width: 48px; + position: relative; + /*Old properties */ + transform: none; } + .b2b-tmpl-notification-card .b2b-tmpl-card-corner-button .close:before { + color: #0568ae; + display: block; + font-size: 20px; + height: auto; + right: -4px; + top: 4px; + width: auto; + /*Old properties */ + left: auto; + height: auto; + bottom: auto; } + .b2b-tmpl-notification-card .b2b-tmpl-card-corner-button .close:focus { + outline: 1px dotted black; } + .b2b-tmpl-notification-card button.close { + -webkit-appearance: none; + moz-appearance: none; + appearance: none; } + .b2b-tmpl-notification-card .b2b-tmpl-card-icon-cirlce { + width: 30px; + height: 30px; + border-radius: 50%; } + .b2b-tmpl-notification-card .b2b-tmpl-card-outer-cirlce { + background: #f0f5f5; + border-radius: 50%; + height: 16px; + width: 16px; + vertical-align: middle; } + .b2b-tmpl-notification-card .b2b-tmpl-card-inner-cirlce { + background: #fff; + width: 22px; + height: 22px; + position: relative; + border-radius: 50%; + display: block; + left: 4px; + top: 4px; + border: 1px solid #767676; } + .b2b-tmpl-notification-card .b2b-tmpl-card-row { + padding-top: 10px; } + .b2b-tmpl-notification-card .b2b-tmpl-card-sub-header { + margin-top: 0px; } + .b2b-tmpl-notification-card .b2b-tmpl-favourite-view-item { + background-color: #fff; + margin-top: 25px; + border-top: 1px solid #ccc; } + .b2b-tmpl-notification-card .b2b-tmpl-favourite-view-item .cta-button-group { + line-height: 40px; + padding-top: 20px; } + .b2b-tmpl-notification-card .b2b-tmpl-card-edit-section .cta-button-group { + line-height: 40px; + padding-top: 15px; } + .b2b-tmpl-notification-card .b2b-tmpl-card-add-item-container { + padding-top: 30px; } + .b2b-tmpl-notification-card .b2b-tmpl-card-link-active { + pointer-events: none; + cursor: default; + color: #ccc; } + .b2b-tmpl-notification-card .b2b-tmpl-card-cursor:hover { + cursor: pointer; } +.b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-icon { + text-align: center; + margin-top: 91px; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-icon i { + font-size: 99px; + color: #1b7e28; } + +.b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-heading { + color: #333333; + text-align: center; + margin-top: 20px; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-heading h1 { + font-size: 38px; } + +.b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-sub-heading { + color: #333333; + text-align: center; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-sub-heading h5 { + font-size: 18px; } + +.b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-info { + padding-left: 18%; + font-size: 16px; + margin-top: 20px; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-info ul { + list-style-type: disc; + list-style-position: inside; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-info li { + padding-top: 5px; } + +.b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-link-section { + font-size: 15px; + color: #0574ac; + margin-top: 20px; + text-align: center; + margin-bottom: 55px; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-link-section .b2b-tmpl-order-confirmation-link { + margin-right: 8%; } + .b2b-tmpl-order-confirmation .b2b-tmpl-order-confirmation-link-section a { + cursor: pointer; } +.b2b-tmpl-profile-block-container { + min-height: 200px; + height: auto; + background-color: #fff; + border-radius: 8px; + border: 1px solid #ccc; + box-shadow: 0px 1px 1px 1px #ccc; + display: inline-table; + margin: 15px 15px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-title { + font-weight: bold; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-footer { + margin-bottom: 12px; + margin-top: 5px; + height: 35px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p { + word-wrap: break-word; + height: 61px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p:first-child { + margin-top: 10px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p:after { + content: ' '; + display: block; + border: 0.2px solid #ccc; + margin-top: 12px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details .radio { + margin-left: 15px; + height: 30px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p, .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details div { + padding: 2px 7px; + font-size: 14px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details .radio-label, .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details a { + font-size: 14px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p label, .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-details p span { + padding-left: 10px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-approval-icon { + color: #1b7e28; + float: right; + position: relative; + left: 10px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-approval-icon i { + color: #1b7e28; + float: right; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-link { + float: right; + position: relative; + left: -4px; } + .b2b-tmpl-profile-block-container a.link-profile { + position: relative; + left: -5px; + float: right; + margin-bottom: 16px; } + .b2b-tmpl-profile-block-container .b2b-tmpl-profile-block-radio { + position: relative; + top: -5px; } +.b2b-static-route-container { + padding-left: 32px; + display: inline-block; } + +.b2b-static-route-label-heading { + font-family: "Omnes-ATT-W02-Medium"; + font-size: 16px !important; + color: #333333; + font-style: normal; + text-align: left; } + +label.b2b-static-route-label-heading { + margin-bottom: 12px; + margin-top: 15px; + display: block; } + +#b2b-static-route-input { + margin: 5px 0 5px; } + +.b2b-static-route-list { + margin-bottom: 30px; + width: 216px; + float: left; + margin-right: 20px; + max-height: 540px; + overflow-y: auto; } + .b2b-static-route-list .status-text { + flex: 1; + display: flex; + align-items: center; + outline: 0; } + +.b2b-static-route-list-item { + border: 1px #cccccc solid; + font-family: "Omnes-ATT-W02"; + font-size: 14px; + display: flex; + cursor: pointer; } + .b2b-static-route-list-item > .status-bar { + padding: 20px 0 20px; + background-color: #ea7400; + border-radius: 0; + width: 10px; + display: inline-block; + margin-right: 20px; + height: 100%; + float: left; } + .b2b-static-route-list-item > .status-bar:after { + content: '.'; + visibility: hidden; } + .b2b-static-route-list-item > .status-bar-unedited { + padding: 20px 0 20px; + background-color: #ffb81c; + border-radius: 0; + width: 10px; + display: inline-block; + margin-right: 20px; + height: 100%; + float: left; + background-color: transparent; } + .b2b-static-route-list-item > .status-bar-unedited:after { + content: '.'; + visibility: hidden; } + +.b2b-static-route-list-item:focus { + outline: 1px dashed #00f; } + +.b2b-static-route-list-item--selected { + background: #f2f2f2; } + +.b2b-static-route-content { + display: inline-block; } diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/horse_shoe.jpg b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/horse_shoe.jpg new file mode 100644 index 0000000..a53eb4e Binary files /dev/null and b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/horse_shoe.jpg differ diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/icon-flyout.png b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/icon-flyout.png new file mode 100644 index 0000000..88e1033 Binary files /dev/null and b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/icon-flyout.png differ diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/treebg.png b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/treebg.png new file mode 100644 index 0000000..32ed1b7 Binary files /dev/null and b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/treebg.png differ diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/widget-thumbnail.png b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/widget-thumbnail.png new file mode 100644 index 0000000..5fbf93c Binary files /dev/null and b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/style/images/widget-thumbnail.png differ diff --git a/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/js/b2b-angular/b2b-library.js b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/js/b2b-angular/b2b-library.js new file mode 100644 index 0000000..269defa --- /dev/null +++ b/ccsdk-app-overlay/src/main/webapp/app/fusion/external/b2b/js/b2b-angular/b2b-library.js @@ -0,0 +1,25339 @@ +angular.module("b2b.att.tpls", ['b2bTemplate/audioPlayer/audioPlayer.html', 'b2bTemplate/audioRecorder/audioRecorder.html', 'b2bTemplate/backToTop/backToTop.html', 'b2bTemplate/boardstrip/b2bAddBoard.html', 'b2bTemplate/boardstrip/b2bBoard.html', 'b2bTemplate/boardstrip/b2bBoardstrip.html', 'b2bTemplate/calendar/datepicker-popup.html', 'b2bTemplate/calendar/datepicker.html', 'b2bTemplate/coachmark/coachmark.html', 'b2bTemplate/dropdowns/b2bDropdownDesktop.html', 'b2bTemplate/dropdowns/b2bDropdownGroupDesktop.html', 'b2bTemplate/dropdowns/b2bDropdownListDesktop.html', 'b2bTemplate/fileUpload/fileUpload.html', 'b2bTemplate/filmstrip/b2bFilmstrip.html', 'b2bTemplate/filmstrip/b2bFilmstripContent.html', 'b2bTemplate/flyout/flyout.html', 'b2bTemplate/flyout/flyoutContent.html', 'b2bTemplate/footer/footer_column_switch_tpl.html', 'b2bTemplate/horizontalTable/horizontalTable.html', 'b2bTemplate/hourPicker/b2bHourpicker.html', 'b2bTemplate/hourPicker/b2bHourpickerPanel.html', 'b2bTemplate/hourPicker/b2bHourpickerValue.html', 'b2bTemplate/leftNavigation/leftNavigation.html', 'b2bTemplate/listbox/listbox.html', 'b2bTemplate/modalsAndAlerts/b2b-backdrop.html', 'b2bTemplate/modalsAndAlerts/b2b-window.html', 'b2bTemplate/monthSelector/monthSelector-popup.html', 'b2bTemplate/monthSelector/monthSelector.html', 'b2bTemplate/monthSelector/monthSelectorLink.html', 'b2bTemplate/pagination/b2b-pagination.html', 'b2bTemplate/paneSelector/paneSelector.html', 'b2bTemplate/paneSelector/paneSelectorPane.html', 'b2bTemplate/profileCard/profileCard-addUser.html', 'b2bTemplate/profileCard/profileCard.html', 'b2bTemplate/reorderList/reorderList.html', 'b2bTemplate/searchField/searchField.html', 'b2bTemplate/seekBar/seekBar.html', 'b2bTemplate/slider/slider.html', 'b2bTemplate/spinButton/spinButton.html', 'b2bTemplate/statusTracker/statusTracker.html', 'b2bTemplate/stepTracker/stepTracker.html', 'b2bTemplate/switches/switches-spanish.html', 'b2bTemplate/switches/switches-v2.html', 'b2bTemplate/switches/switches.html', 'b2bTemplate/tableMessages/tableMessage.html', 'b2bTemplate/tableScrollbar/tableScrollbar.html', 'b2bTemplate/tables/b2bResponsiveRow.html', 'b2bTemplate/tables/b2bTable.html', 'b2bTemplate/tables/b2bTableBody.html', 'b2bTemplate/tables/b2bTableHeaderSortable.html', 'b2bTemplate/tables/b2bTableHeaderUnsortable.html', 'b2bTemplate/tabs/b2bTab.html', 'b2bTemplate/tabs/b2bTabset.html', 'b2bTemplate/treeNav/groupedTree.html', 'b2bTemplate/treeNav/treeMember.html', 'b2bTemplate/treeNav/ungroupedTree.html', 'b2bTemplate/treeNodeCheckbox/groupedTree.html', 'b2bTemplate/treeNodeCheckbox/treeMember.html', 'b2bTemplate/treeNodeCheckbox/ungroupedTree.html', 'b2bTemplate/usageBar/usageBar.html']);angular.module("b2b.att", ["b2b.att.tpls", 'b2b.att.addressInputTemplate','b2b.att.arrows','b2b.att.audioPlayer','b2b.att.audioRecorder','b2b.att.backToTop','b2b.att.badgesForAlerts','b2b.att.bellybandLinks','b2b.att.boardstrip','b2b.att.bootstrapGridTemplate','b2b.att.breadcrumbs','b2b.att.buttonGroups','b2b.att.buttons','b2b.att.calendar','b2b.att.cards','b2b.att.checkboxes','b2b.att.coachmark','b2b.att.configurationSection','b2b.att.directoryListingTemplate','b2b.att.dropdowns','b2b.att.fileUpload','b2b.att.filmstrip','b2b.att.filters','b2b.att.flyout','b2b.att.footer','b2b.att.header','b2b.att.headingsAndCopy','b2b.att.horizontalTable','b2b.att.hourPicker','b2b.att.inputTemplate','b2b.att.leftNavigation','b2b.att.links','b2b.att.listbox','b2b.att.loaderAnimation','b2b.att.messageWrapper','b2b.att.modalsAndAlerts','b2b.att.monthSelector','b2b.att.multiLevelNavigation','b2b.att.multipurposeExpander','b2b.att.notesMessagesAndErrors','b2b.att.notificationCardTemplate','b2b.att.orderConfirmationTemplate','b2b.att.pagination','b2b.att.paneSelector','b2b.att.phoneNumberInput','b2b.att.profileBlockTemplate','b2b.att.profileCard','b2b.att.radios','b2b.att.reorderList','b2b.att.searchField','b2b.att.seekBar','b2b.att.separators','b2b.att.slider','b2b.att.spinButton','b2b.att.staticRouteTemplate','b2b.att.statusTracker','b2b.att.stepTracker','b2b.att.switches','b2b.att.switchesv2','b2b.att.tableDragAndDrop','b2b.att.tableMessages','b2b.att.tableScrollbar','b2b.att.tables','b2b.att.tabs','b2b.att.tagBadges','b2b.att.textArea','b2b.att.timeInputField','b2b.att.tooltipsForForms','b2b.att.treeNav','b2b.att.treeNodeCheckbox','b2b.att.usageBar','b2b.att.utilities']);/** + * @ngdoc directive + * @name Template.att:Address Input + * + * @description + * + * + * @usage + + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.addressInputTemplate', ['ngMessages']); +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:arrows + * + * @description + * + * + * @usage + * Please refer demo.html tab in Example section below. + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.arrows', []); +/** + * @ngdoc directive + * @name Videos, audio & animation.att:Audio Player + * @scope + * @param {string} audioSrcUrl - MP3 audio source URL or Blob URL + * @description + * + * + * @usage + * +
+ * + * @example + *
+ + + + +
+ * + */ + +angular.module('b2b.att.audioPlayer', ['b2b.att.utilities', 'b2b.att.slider']) + .constant('AudioPlayerConfig', { + 'defaultVolume': 50, + 'timeShiftInSeconds': 5 + }) + .filter('trustedAudioUrl', ['$sce', function ($sce) { + return function (audioFileFullPath) { + return audioFileFullPath ? $sce.trustAsResourceUrl(audioFileFullPath) : 'undefined'; + }; + }]) + .directive('b2bAudio', ['$log', '$timeout', 'AudioPlayerConfig', '$compile', 'events', function ($log, $timeout, AudioPlayerConfig, $compile, events) { + return { + restrict: 'EA', + replace: true, + scope: { + audioSrcUrl: '=', + disabled: '=', + audioConfiguration: '=?' + }, + templateUrl: 'b2bTemplate/audioPlayer/audioPlayer.html', + controller: function ($scope) { + $scope.audio = {}; + if (!angular.isDefined($scope.audioConfiguration)) { + $scope.audioConfiguration = { + 'playLabel' : 'play', + 'pauseLabel' : 'pause' + } + } + if (!angular.isDefined($scope.audioSrcUrl)) { + $log.warn('b2b-audio : audio-src-url undefined'); + $scope.audioSrcUrl = undefined; + $scope.audio.mp3 = undefined; + } + + }, + link: function (scope, element, attr) { + var audioElement = angular.element(element[0].querySelector('audio'))[0]; + var audioSrcElement = angular.element(element[0].querySelector('audio source'))[0]; + scope.audio.audioElement = audioElement; + var infinityDuration = false; + element[0].removeAttribute("disabled"); + function setAttributes(element, attributes) { + Object.keys(attributes).forEach(function (name) { + element.setAttribute(name, attributes[name]); + }); + } + + $timeout(function () { + // TODO: Replace with DDA Tooltip + var seekBarKnob = element[0].querySelector('.slider-knob'); + var tooltipObject = { + 'tooltip': '{{timeFormatter(audio.currentTime)}}', + 'tooltip-placement': 'above', + 'tooltip-style': 'blue', + 'tooltip-trigger': 'mousedown', + 'tooltip-append-to-body': 'false', + 'tooltip-offset': '-10', + 'refer-by': 'seek-bar-tooltip' + }; + setAttributes(seekBarKnob, tooltipObject); + $compile(seekBarKnob)(scope); + }); + + if (angular.isDefined(scope.audioSrcUrl)) { + scope.audio.mp3 = scope.audioSrcUrl; + } + + scope.audio.currentTime = 0; + scope.audio.currentVolume = AudioPlayerConfig.defaultVolume; + scope.audio.timeShiftInSeconds = AudioPlayerConfig.timeShiftInSeconds; + scope.isPlayInProgress = false; + scope.isReady = false; + scope.isAudioDragging = false; + scope.audioError = false; + $timeout(function () { + audioElement.load(); + audioElement.volume = scope.audio.currentVolume / 100; + }); + + scope.$watch('audioSrcUrl', function (newVal, oldVal) { + if (newVal !== oldVal) { + if (!newVal) { + $log.warn('b2b-audio : audio-src-url undefined. Please provide a valid URL'); + } + + scope.audio.mp3 = newVal; + $timeout(function () { + audioElement.load(); + }); + } + }); + + scope.$watch('disabled', function (newVal, oldVal) { + if(newVal){ + if(scope.disabled){ + scope.pauseAudio(); + } + element.addClass("b2b-audio-disabled"); + angular.element(element[0].querySelector(".controls-wrapper")).attr({'tabindex':-1, 'aria-disabled':true}) + angular.element(element[0].querySelector(".audio-volume-control")).attr({'tabindex':-1, 'aria-disabled':true}) + }else{ + element.removeClass("b2b-audio-disabled"); + angular.element(element[0].querySelector(".controls-wrapper")).attr({'tabindex':0, 'aria-disabled':false}) + angular.element(element[0].querySelector(".audio-volume-control")).attr({'tabindex':0, 'aria-disabled':false}) + } + }); + + + scope.playAudio = function () { + if (scope.isReady) { + audioElement.play(); + } + }; + + audioElement.onplay = function () { + scope.isPlayInProgress = true; + scope.$digest(); + }; + + scope.pauseAudio = function () { + audioElement.pause(); + }; + + audioElement.onpause = function () { + scope.isPlayInProgress = false; + scope.$digest(); + }; + audioElement.onerror = function(){ + scope.audioError = true; + var fileName = scope.audio.mp3.split("/"); + scope.audioFileName = fileName[fileName.length-1]; + }; + audioSrcElement.onerror = function(){ + scope.audioError = true; + var fileName = scope.audio.mp3.split("/"); + scope.audioFileName = fileName[fileName.length-1]; + }; + scope.volumeControl = function() { + if(element[0].querySelector('.b2b-audio-popover .slider-knob')){ + $timeout(function () { + element[0].querySelector('.b2b-audio-popover .slider-knob').focus(); + },500); + } + } + scope.toggleAudio = function () { + if (audioElement.paused) { + scope.playAudio(); + } else { + scope.pauseAudio(); + } + }; + + scope.volumeUp = function (delta) { + if (!delta) { + delta = 0.1; + } else { + delta = delta / 100; + } + audioElement.muted = false; + if (audioElement.volume < 1) { + audioElement.volume = Math.min((Math.round((audioElement.volume + delta) * 100) / 100), 1); + } + scope.audio.currentVolume = audioElement.volume * 100; + return audioElement.volume; + }; + + scope.volumeDown = function (delta) { + if (!delta) { + delta = 0.1; + } else { + delta = delta / 100; + } + audioElement.muted = false; + if (audioElement.volume > 0) { + audioElement.volume = Math.max((Math.round((audioElement.volume - delta) * 100) / 100), 0); + } + scope.audio.currentVolume = audioElement.volume * 100; + return audioElement.volume; + }; + + var volumeHandler = function (e) { + events.preventDefault(e); + if ((e.wheelDelta && e.wheelDelta > 0) || (e.detail && e.detail < 0)) { + scope.volumeUp(); + } else { + scope.volumeDown(); + } + scope.$digest(); + }; + + + + scope.$watch('audio.currentVolume', function (newVal, oldVal) { + if (newVal !== oldVal) { + audioElement.volume = newVal / 100; + } + }); + + scope.setCurrentTime = function (timeInSec) { + audioElement.currentTime = timeInSec; + }; + + scope.setAudioPosition = function (val) { + if (scope.isReady) { + scope.setCurrentTime(val); + scope.isAudioDragging = false; + } + }; + + function getTimestampArray(timestamp) { + var d = Math.abs(timestamp) / 1000; // delta + var r = {}; // result + var s = { // structure + day: 86400, + hour: 3600, + minute: 60, + second: 1 + }; + + Object.keys(s).forEach(function (key) { + r[key] = Math.floor(d / s[key]); + d -= r[key] * s[key]; + }); + + return r; + }; + + scope.timeFormatter = function (timeInSec) { + var formattedTime = '00:00'; + + if (!timeInSec || timeInSec < 1) { + return formattedTime; + } + + if (typeof timeInSec === 'string') { + return timeInSec; + } + + var dateArray = getTimestampArray(timeInSec * 1000); + Object.keys(dateArray).forEach(function (key) { + if (dateArray[key] === 0) { + dateArray[key] = '00'; + } else if (dateArray[key] < 10) { + dateArray[key] = '0' + dateArray[key]; + } + }); + + formattedTime = dateArray['minute'] + ':' + dateArray['second']; + + if (dateArray['hour'] !== '00') { + formattedTime = dateArray['hour'] + ':' + formattedTime; + } + + if (dateArray['day'] !== '00') { + formattedTime = dateArray['day'] + ':' + formattedTime; + } + + return formattedTime; + }; + + audioElement.onloadedmetadata = function () { + /* Few of the audio files were returning the duration as Infinity, hence moving the current time by 180 sec and the resetting the current time to zero*/ + if(audioElement.duration === Infinity){ + infinityDuration = true; + audioElement.currentTime = 360; + }else{ + scope.audio.duration = audioElement.duration; + scope.$digest(); + } + }; + + audioElement.ontimeupdate = function () { + if(infinityDuration === true && audioElement.duration !== Infinity){ + audioElement.currentTime = 0; + infinityDuration = false; + scope.audio.duration = audioElement.duration; + scope.$digest(); + } + if (!scope.isAudioDragging) { + scope.audio.currentTime = audioElement.currentTime; + scope.$digest(); + } + }; + + audioElement.onended = function () { + scope.setCurrentTime(0); + scope.audio.currentTime = 0; + if (!audioElement.paused) { + scope.pauseAudio(); + } + scope.$digest(); + }; + + audioElement.oncanplay = function () { + scope.isReady = true; + scope.isPlayInProgress = !audioElement.paused; + scope.$digest(); + }; + + var onloadstart = function () { + scope.isReady = false; + scope.isPlayInProgress = !audioElement.paused; + scope.audio.currentTime = 0; + scope.audio.duration = 0; + scope.$digest(); + }; + audioElement.addEventListener("loadstart", onloadstart); + } + }; + }]); +/** + * @ngdoc directive + * @name Videos, audio & animation.att:Audio Recorder + * @scope + * @param {function} callback - A callback to handle the WAV blob + * @param {object} config - A config object with properties startRecordingMessage & whileRecordingMessage + * @description + * + * + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.audioRecorder', ['b2b.att.utilities']) + .constant('AudioRecorderConfig', { + 'startRecordingMessage': 'Click on REC icon to begin recording', + 'whileRecordingMessage': 'Recording...', + 'stopLabel': 'stop', + 'recordingLabel': 'record' + }) + .directive('b2bAudioRecorder', ['$interval', 'AudioRecorderConfig', 'b2bUserAgent', 'b2bRecorder', function($interval, AudioRecorderConfig, b2bUserAgent, b2bRecorder) { + return { + restrict: 'EA', + replace: true, + scope: { + callback: '&', + audioRecorderConfiguration: '=?' + }, + templateUrl: 'b2bTemplate/audioRecorder/audioRecorder.html', + controller: function($scope) { + + function hasGetUserMedia() { + return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || + navigator.mozGetUserMedia || navigator.msGetUserMedia); + } + + if (!hasGetUserMedia()) { + throw new Error('Your broswer does not support MediaRecorder API'); + } + + if (!(b2bUserAgent.isFF() || b2bUserAgent.isChrome())) { + throw new Error('b2bAudioRecorder does not support this browser!'); + } + + }, + link: function(scope, element) { + scope.elapsedTime = 0; + scope.isRecording = false; + scope.config = {}; + if (!angular.isDefined(scope.audioRecorderConfiguration)) { + scope.config.startRecordingMessage = AudioRecorderConfig.startRecordingMessage; + scope.config.whileRecordingMessage = AudioRecorderConfig.whileRecordingMessage; + scope.config.recordingLabel = AudioRecorderConfig.recordingLabel; + scope.config.stopLabel = AudioRecorderConfig.stopLabel; + }else{ + scope.config = scope.audioRecorderConfiguration; + } + + + var timer = undefined; // Interval promise + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; + var stream; + var audio = angular.element(element[0].querySelector('audio'))[0]; + var recorder = undefined; + var audioStream; + function startRecording() { + scope.isRecording = true; + navigator.mediaDevices.getUserMedia({ + audio: true + }).then(function(stream) { + //create the MediaStreamAudioSourceNode + audioStream = stream; + context = new AudioContext(); + source = context.createMediaStreamSource(stream); + recorder = new b2bRecorder(source); + recorder.record(); + + timer = $interval(function() { + scope.elapsedTime += 1; + }, 1000, 0); + }).catch(function(err) { + angular.noop(); + }); + + }; + + function stopRecording() { + scope.isRecording = false; + recorder.stop(); + var audio = {}; + recorder.exportWAV(function(s) { + audio.src = window.URL.createObjectURL(s); + context.close().then(function() { + if (timer) { + $interval.cancel(timer); + } + scope.elapsedTime = 0; + + recorder.clear(); + recorder = undefined; + }); + if (angular.isFunction(scope.callback)){ + scope.callback({'data': audio}); + } + }); + if (angular.isFunction(audioStream.stop)){ + audioStream.stop(); + } + var tracks = audioStream.getTracks(); + for(var i=0; i + * @param {integer} scrollSpeed - Scroll speed in seconds, default is 1 +* + * @usage + * +
+
+
+ * + * @example + *
+ + + + +
+ * + */ + +angular.module('b2b.att.backToTop', ['b2b.att.utilities','b2b.att.position']) + .directive('b2bBacktotopButton', [function () { + return { + restrict: 'EA', + replace: true, + templateUrl: 'b2bTemplate/backToTop/backToTop.html', + link: function (scope, elem, attr) { + elem.bind('click', function(evt) { + var scrollSpeed = parseInt(attr.scrollSpeed) || 1; + TweenLite.to(window, scrollSpeed, {scrollTo:{x: 0, y: 0}}); + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:badgesForAlerts + * + * @description + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.badgesForAlerts', []); +/** + * @ngdoc directive + * @name Misc.att:bellybandLinks + * + * @description + * + * + * @usage + * + + * @example + *
+ HTML + AngularJS + + + + +
+ * + */ +angular.module('b2b.att.bellybandLinks', []) + .directive('b2bBellybandAutosizeWhat', ['$window', function($window) { + return { + restrict: 'EA', + link: function(scope, ele, attr) { + var bellyBandGroupElement; + var sizeWhat = attr.bellybandAutosizeWhat; + var haveBellybandGgroupClass = ele.hasClass('b2b-bellyband-group'); + + if (haveBellybandGgroupClass) { + bellyBandGroupElement = ele[0]; + } + else { + bellyBandGroupElement = ele[0].querySelectorAll('.b2b-bellyband-group'); + } + + var bellyBandCssCalculation = function() { + angular.forEach(ele[0].querySelectorAll('.b2b-bellyband-link'), function(value, key) { + var newElement = angular.element(value); + if ($window.innerWidth <= '479') { + newElement.removeAttr('style'); + angular.element(bellyBandGroupElement).removeAttr('style'); + } + if ($window.innerWidth > '479' && $window.innerWidth < '768') { + + var lnkHeight = getComputedStyle(value, null).height.split("px"); + + lnkMar = getComputedStyle(value, null).marginBottom.split("px"); + + var bblink; + + if (ele[0].querySelectorAll('.b2b-bellyband-link').length === 2) { + bblink = ((parseInt(lnkHeight[0]) + parseInt(lnkMar[0])) * 1) + 'px'; + } + + else if ((ele[0].querySelectorAll('.b2b-bellyband-link').length === 3) || (ele[0].querySelectorAll('.b2b-bellyband-link').length === 4)){ + bblink = ((parseInt(lnkHeight[0]) + parseInt(lnkMar[0])) * 2) + 'px'; + } + + else if (ele[0].querySelectorAll('.b2b-bellyband-link').length >= 5) { + bblink = ((parseInt(lnkHeight[0]) + parseInt(lnkMar[0])) * 3) + 'px'; + } + + angular.element(bellyBandGroupElement).css({ + 'max-height': bblink + }); + + } else if ($window.innerWidth >= '768') { + + for(var i = 0;i + * + * @usage + * See demo section + * @example +
+ HTML + AngularJS + + + + +
+ */ +angular.module('b2b.att.boardstrip', ['b2b.att.utilities']) + .constant('BoardStripConfig', { + 'maxVisibleBoards': 4, + 'boardsToScroll': 1, + /* These parameters are non-configurable and remain unaltered, until there is a change in corresponding CSS */ + 'boardLength': 140, + 'boardMargin': 15 + }) + .directive('b2bBoard', [function () { + return { + restrict: 'AE', + replace: true, + transclude: true, + require: '^b2bBoardStrip', + scope: { + boardIndex: '=', + boardLabel: '=' + }, + templateUrl: 'b2bTemplate/boardstrip/b2bBoard.html', + link: function (scope, element, attrs, ctrls) { + + var parentCtrl = ctrls; + + scope.getCurrentIndex = function () { + return parentCtrl.getCurrentIndex(); + }; + scope.selectBoard = function (boardIndex) { + if (!isNaN(boardIndex)) { + parentCtrl.setCurrentIndex(boardIndex); + } + }; + } + }; + }]) + .directive('b2bBoardStrip', ['BoardStripConfig', '$timeout', function (BoardStripConfig, $timeout) { + return { + restrict: 'AE', + replace: true, + transclude: true, + require: ['?ngModel', 'b2bBoardStrip'], + scope: { + boardsMasterArray: '=', + onAddBoard: '&?' + }, + templateUrl: 'b2bTemplate/boardstrip/b2bBoardstrip.html', + controller: function ($scope) { + if (!angular.isDefined($scope.boardsMasterArray)) { + $scope.boardsMasterArray = []; + } + + this.rectifyMaxVisibleBoards = function () { + if (this.maxVisibleIndex >= $scope.boardsMasterArray.length) { + this.maxVisibleIndex = $scope.boardsMasterArray.length - 1; + } + + if (this.maxVisibleIndex < 0) { + this.maxVisibleIndex = 0; + } + }; + + this.resetBoardStrip = function () { + $scope.currentIndex = 0; + + this.maxVisibleIndex = BoardStripConfig.maxVisibleBoards - 1; + this.minVisibleIndex = 0; + + this.rectifyMaxVisibleBoards(); + }; + + this.getCurrentIndex = function () { + return $scope.currentIndex; + }; + this.setCurrentIndex = function (indx) { + $scope.currentIndex = indx; + }; + + this.getBoardsMasterArrayLength = function () { + return $scope.boardsMasterArray.length; + }; + + $scope.addBoardPressedFlag = false; + this.getAddBoardPressedFlag = function () { + return $scope.addBoardPressedFlag; + }; + this.setAddBoardPressedFlag = function (booleanValue) { + $scope.addBoardPressedFlag = booleanValue; + }; + + }, + link: function (scope, element, attrs, ctrls) { + + var ngModelCtrl = ctrls[0]; + var ctrl = ctrls[1]; + + var oldTimeout; + var animationTimeout = 1000; + + var getBoardViewportWidth = function (numberOfVisibleBoards) { + return numberOfVisibleBoards * (BoardStripConfig.boardLength + BoardStripConfig.boardMargin); + }; + if (element[0].querySelector(".board-viewport")) { + angular.element(element[0].querySelector(".board-viewport")).css({ + "width": getBoardViewportWidth(BoardStripConfig.maxVisibleBoards) + "px" + }); + } + + var getBoardstripContainerWidth = function (totalNumberOfBoards) { + return totalNumberOfBoards * (BoardStripConfig.boardLength + BoardStripConfig.boardMargin); + }; + if (element[0].querySelector(".boardstrip-container")) { + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "width": getBoardstripContainerWidth(ctrl.getBoardsMasterArrayLength()) + "px" + }); + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "left": "0px" + }); + } + + var calculateAndGetBoardstripContainerAdjustment = function () { + + var calculatedAdjustmentValue; + + if (ctrl.getBoardsMasterArrayLength() <= BoardStripConfig.maxVisibleBoards) { + calculatedAdjustmentValue = 0; + } else { + calculatedAdjustmentValue = (ctrl.minVisibleIndex * (BoardStripConfig.boardLength + BoardStripConfig.boardMargin)) * -1; + } + + return calculatedAdjustmentValue; + }; + + var animateBoardstripContainerAdjustment = function (elementToFocusAfterAnimation) { + var oldContainerAdjustment = angular.element(element[0].querySelector(".boardstrip-container"))[0].style.left; + var containerAdjustment = calculateAndGetBoardstripContainerAdjustment(); + if (oldContainerAdjustment !== containerAdjustment + 'px') { + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "left": containerAdjustment + "px" + }); + + $timeout.cancel(oldTimeout); + oldTimeout = $timeout(function () { + elementToFocusAfterAnimation.focus(); + }, animationTimeout); + } else { + elementToFocusAfterAnimation.focus(); + } + }; + + var updateBoardsTabIndex = function (boardArray, minViewIndex, maxViewIndex) { + for (var i = 0; i < boardArray.length; i++) { + angular.element(boardArray[i]).attr('tabindex', '-1'); + } + for (var j = minViewIndex; j <= maxViewIndex; j++) { + angular.element(boardArray[j]).attr('tabindex', '0'); + } + }; + + $timeout(function () { + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + + scope.$watchCollection('boardsMasterArray', function (newVal, oldVal) { + if (newVal !== oldVal) { + /* When a board is removed */ + if (newVal.length < oldVal.length) { + ctrl.resetBoardStrip(); + $timeout(function () { + + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + if (currentBoardArray.length !== 0) { + animateBoardstripContainerAdjustment(currentBoardArray[0]); + } else { + element[0].querySelector('div.boardstrip-item--add').focus(); + } + + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "width": getBoardstripContainerWidth(ctrl.getBoardsMasterArrayLength()) + "px" + }); + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + } + /* When a board is added */ + else { + if (ctrl.getAddBoardPressedFlag()) { + ctrl.maxVisibleIndex = ctrl.getBoardsMasterArrayLength() - 1; + ctrl.minVisibleIndex = Math.max(ctrl.maxVisibleIndex - BoardStripConfig.maxVisibleBoards + 1, 0); + + ctrl.setCurrentIndex(ctrl.maxVisibleIndex); + + $timeout(function () { + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "width": getBoardstripContainerWidth(ctrl.getBoardsMasterArrayLength()) + "px" + }); + + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + animateBoardstripContainerAdjustment(currentBoardArray[currentBoardArray.length - 1]); + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + } else { + if (ctrl.minVisibleIndex === 0 && ctrl.getBoardsMasterArrayLength() < BoardStripConfig.maxVisibleBoards + 1) { + ctrl.maxVisibleIndex = ctrl.getBoardsMasterArrayLength() - 1; + ctrl.rectifyMaxVisibleBoards(); + } + + $timeout(function () { + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "width": getBoardstripContainerWidth(ctrl.getBoardsMasterArrayLength()) + "px" + }); + + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + } + + ctrl.setAddBoardPressedFlag(false); + } + } + }); + + scope.nextBoard = function () { + ctrl.maxVisibleIndex += BoardStripConfig.boardsToScroll; + ctrl.rectifyMaxVisibleBoards(); + ctrl.minVisibleIndex = ctrl.maxVisibleIndex - (BoardStripConfig.maxVisibleBoards - 1); + + $timeout.cancel(oldTimeout); + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "left": calculateAndGetBoardstripContainerAdjustment() + "px" + }); + + $timeout(function () { + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + + /* Remove tabindex from non-visible boards */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + + if (!(scope.isNextBoard())) { + try { + currentBoardArray[currentBoardArray.length - 1].focus(); + } catch (e) { /* IE8 may throw exception */ } + } + }, animationTimeout); + }; + scope.prevBoard = function () { + + ctrl.minVisibleIndex -= BoardStripConfig.boardsToScroll; + if (ctrl.minVisibleIndex < 0) { + ctrl.minVisibleIndex = 0; + } + + ctrl.maxVisibleIndex = ctrl.minVisibleIndex + BoardStripConfig.maxVisibleBoards - 1; + ctrl.rectifyMaxVisibleBoards(); + + $timeout.cancel(oldTimeout); + angular.element(element[0].querySelector(".boardstrip-container")).css({ + "left": calculateAndGetBoardstripContainerAdjustment() + "px" + }); + + $timeout(function () { + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + + /* Remove tabindex from non-visible boards */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + + if (ctrl.minVisibleIndex === 0) { + try { + element[0].querySelector('div.boardstrip-item--add').focus(); + } catch (e) { /* IE8 may throw exception */ } + } + }); + }; + + scope.isPrevBoard = function () { + return (ctrl.minVisibleIndex > 0); + }; + scope.isNextBoard = function () { + return (ctrl.getBoardsMasterArrayLength() - 1 > ctrl.maxVisibleIndex); + }; + + ngModelCtrl.$render = function () { + if (ngModelCtrl.$viewValue || ngModelCtrl.$viewValue === 0) { + var newCurrentIndex = ngModelCtrl.$viewValue; + + if (!(newCurrentIndex = parseInt(newCurrentIndex, 10))) { + newCurrentIndex = 0; + } + + if (newCurrentIndex <= 0) { + ctrl.resetBoardStrip(); + newCurrentIndex = 0; + + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + if (currentBoardArray.length !== 0) { + animateBoardstripContainerAdjustment(currentBoardArray[0]); + } else { + element[0].querySelector('div.boardstrip-item--add').focus(); + } + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + } else if (newCurrentIndex >= ctrl.getBoardsMasterArrayLength()) { + ctrl.maxVisibleIndex = ctrl.getBoardsMasterArrayLength() - 1; + ctrl.rectifyMaxVisibleBoards(); + ctrl.minVisibleIndex = Math.max(ctrl.maxVisibleIndex - BoardStripConfig.maxVisibleBoards + 1, 0); + + newCurrentIndex = ctrl.maxVisibleIndex; + + $timeout(function () { + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + animateBoardstripContainerAdjustment(currentBoardArray[newCurrentIndex]); + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + } else { + + if (!(newCurrentIndex >= ctrl.minVisibleIndex && newCurrentIndex <= ctrl.maxVisibleIndex)) { + ctrl.minVisibleIndex = newCurrentIndex; + ctrl.maxVisibleIndex = ctrl.minVisibleIndex + BoardStripConfig.maxVisibleBoards - 1; + ctrl.rectifyMaxVisibleBoards(); + + if (ctrl.getBoardsMasterArrayLength() < BoardStripConfig.maxVisibleBoards) { + ctrl.minVisibleIndex = 0; + } else { + ctrl.minVisibleIndex = Math.max(ctrl.maxVisibleIndex - BoardStripConfig.maxVisibleBoards + 1, 0); + } + + $timeout(function () { + var currentBoardArray = element[0].querySelectorAll('[b2b-board]'); + animateBoardstripContainerAdjustment(currentBoardArray[newCurrentIndex]); + /* Update tabindecies to ensure keyboard navigation behaves correctly */ + updateBoardsTabIndex(currentBoardArray, ctrl.minVisibleIndex, ctrl.maxVisibleIndex); + }); + } + } + scope.currentIndex = newCurrentIndex; + ngModelCtrl.$setViewValue(newCurrentIndex); + } else { + ctrl.resetBoardStrip(); + ngModelCtrl.$setViewValue(0); + } + }; + + scope.$watch('currentIndex', function (newVal, oldVal) { + if (newVal !== oldVal && ngModelCtrl && ngModelCtrl.$viewValue !== newVal) { + ngModelCtrl.$setViewValue(newVal); + } + }); + } + }; + }]) + .directive('b2bAddBoard', ['BoardStripConfig', '$parse', function (BoardStripConfig, $parse) { + return { + restrict: 'AE', + replace: true, + require: '^b2bBoardStrip', + scope: { + onAddBoard: '&?' + }, + templateUrl: 'b2bTemplate/boardstrip/b2bAddBoard.html', + link: function (scope, element, attrs, ctrl) { + scope.addBoard = function () { + if (attrs['onAddBoard']) { + scope.onAddBoard = $parse(scope.onAddBoard); + scope.onAddBoard(); + ctrl.setAddBoardPressedFlag(true); + } + }; + } + }; + }]) + .directive('b2bBoardNavigation', ['keymap', 'events', function (keymap, events) { + return { + restrict: 'AE', + link: function (scope, elem) { + + var prevElem = keymap.KEY.LEFT; + var nextElem = keymap.KEY.RIGHT; + + elem.bind('keydown', function (ev) { + + if (!(ev.keyCode)) { + ev.keyCode = ev.which; + } + + switch (ev.keyCode) { + case nextElem: + events.preventDefault(ev); + events.stopPropagation(ev); + + if (elem[0].nextElementSibling && parseInt(angular.element(elem[0].nextElementSibling).attr('tabindex')) >= 0) { + angular.element(elem[0])[0].nextElementSibling.focus(); + } else { + /* IE8 fix */ + var el = angular.element(elem[0])[0]; + do { + if (el.nextSibling) { + el = el.nextSibling; + } else { + break; + } + } while (el && el.tagName !== 'LI'); + + if (el.tagName && el.tagName === 'LI' && parseInt(angular.element(el).attr('tabindex')) >= 0) { + el.focus(); + } + } + + break; + case prevElem: + events.preventDefault(ev); + events.stopPropagation(ev); + + if (elem[0].previousElementSibling && parseInt(angular.element(elem[0].previousElementSibling).attr('tabindex')) >= 0) { + angular.element(elem[0])[0].previousElementSibling.focus(); + } else { + /* IE8 fix */ + var el1 = angular.element(elem[0])[0]; + do { + if (el1.previousSibling) { + el1 = el1.previousSibling; + } else { + break; + } + } while (el1 && el1.tagName !== 'LI'); + + if (el1.tagName && el1.tagName === 'LI' && parseInt(angular.element(el1).attr('tabindex')) >= 0) { + el1.focus(); + } + } + break; + default: + break; + } + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Template.att:Bootstrap Grid Template + * + * @description + * + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.bootstrapGridTemplate', []) + +/** + * @ngdoc directive + * @name Navigation.att:breadcrumbs + * + * @description + * + * @usage + + * @example + + + + + */ +angular.module('b2b.att.breadcrumbs',[]) +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:buttonGroups + * + * @description + * + * + * @usage +

Radio Aproach

+
+ + + +
+ +

Checkbox Aproach

+ + + + + + + + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.buttonGroups', ['b2b.att.utilities']) + .constant('buttonConfig', { + activeClass: 'active', + toggleEvent: 'click' + }) + .directive('b2bBtnRadio', ['buttonConfig', function (buttonConfig) { + var activeClass = buttonConfig.activeClass || 'active'; + var toggleEvent = buttonConfig.toggleEvent || 'click'; + + return { + require: 'ngModel', + link: function (scope, element, attrs, ngModelCtrl) { + var notMobile = !/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); + + if (notMobile) { + element.bind('focus', function () { + scope.$apply(function () { + ngModelCtrl.$setViewValue(scope.$eval(attrs.b2bBtnRadio)); + ngModelCtrl.$render(); + }); + }); + } + + element.attr('role', 'radio'); + + //model -> UI + ngModelCtrl.$render = function () { + element.toggleClass(activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.b2bBtnRadio))); + if (angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.b2bBtnRadio))) { + element.attr("aria-checked", true); + } else { + element.attr("aria-checked", false); + } + }; + + //ui->model + element.bind(toggleEvent, function () { + if (!element.hasClass(activeClass)) { + scope.$apply(function () { + ngModelCtrl.$setViewValue(scope.$eval(attrs.b2bBtnRadio)); + ngModelCtrl.$render(); + }); + } + }); + } + }; + }]) + .directive('b2bBtnCheckbox', ['buttonConfig', function (buttonConfig) { + var activeClass = buttonConfig.activeClass || 'active'; + var toggleEvent = buttonConfig.toggleEvent || 'click'; + + return { + require: ['ngModel', '^^b2bButtonGroup'], + link: function (scope, element, attrs, ctrls) { + + var ngModelCtrl = ctrls[0]; + var parentCtrl = ctrls[1]; + + element.attr('role', 'checkbox'); + element.attr('aria-describedby', parentCtrl.getStateDescriptionElemId()); + + function getTrueValue() { + var trueValue = scope.$eval(attrs.b2bBtnCheckboxTrue); + return angular.isDefined(trueValue) ? trueValue : true; + } + + function getFalseValue() { + var falseValue = scope.$eval(attrs.b2bBtnCheckboxFalse); + return angular.isDefined(falseValue) ? falseValue : false; + } + + //model -> UI + ngModelCtrl.$render = function () { + element.toggleClass(activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); + if ((angular.equals(ngModelCtrl.$modelValue, getTrueValue()))) { + element.attr("aria-checked", true); + } else { + element.attr("aria-checked", false); + } + }; + + //ui->model + element.bind(toggleEvent, function () { + scope.$apply(function () { + ngModelCtrl.$setViewValue(element.hasClass(activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + } + }; + }]) + .directive('b2bButtonGroup', ['$timeout', '$compile', function ($timeout, $compile) { + return { + restrict: 'A', + scope: { + maxSelect: "=", + ngModelButtonState: '=ngModel' + }, + controller: ['$scope', '$element', function ($scope, $element) { + $scope.nSel = 0; + + var stateDescriptionElem = angular.element(''); + $compile(stateDescriptionElem)($scope); + $element.after(stateDescriptionElem); + + this.getStateDescriptionElemId = function () { + return stateDescriptionElem.attr('id'); + }; + }], + link: function (scope, element) { + + + var executeFxn = function () { + scope.nSel = 0; + angular.forEach(scope.ngModelButtonState, function (value, key) { + if (value === true) { + scope.nSel += 1; + } + }); + + if (scope.nSel >= scope.maxSelect) { + angular.forEach(element.children(), function (chd) { + if (chd.className.indexOf('active') < 0) { + chd.disabled = true; + chd.setAttribute('aria-disabled', true); + } + }); + } else { + angular.forEach(element.children(), function (chd) { + chd.disabled = false; + chd.setAttribute('aria-disabled', false); + }); + } + scope.$digest(); + }; + + $timeout(function () { + executeFxn(); + }); + element.bind('click', executeFxn); + } + }; + }]); +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:buttons + * @element input + * @function + * + * @description + * + * @usage + * +Button shape + button.btn (button shape only) + button.btn (button shape only) with custom aria label + button.btn with click functionality +Button a.btn (button shape only) + .btn-primary +Button a.btn-primary + +5 Button colors + .btn-secondary +Button a.btn-secondary + .btn-alt +Button a.btn-alt + .btn-specialty +Button a.btn-specialty + disabled="disabled" +Button a.disabled + +3 button heights + .btn is default and 46px height + .btn-medium is 42px + .btn-small is 36px + +.row-nowrap 2 up buttons +
+ + +
+ +.row 2 up buttons (desktop) stacked (mobile) (different order) +
+ + + +
+ + * @example + *
+ HTML + AngularJS + * + * + + * +
+ * + */ +angular.module('b2b.att.buttons', ['b2b.att.utilities']); +/** + * @ngdoc directive + * @name Forms.att:calendar + * + * @description + * + * @usage + * + * + * @example +
+ HTML + AngularJS + + + + +
+ */ +angular.module('b2b.att.calendar', ['b2b.att.position', 'b2b.att.utilities']) + +.constant('b2bDatepickerConfig', { + dateFormat: 'MM/dd/yyyy', + dayFormat: 'd', + monthFormat: 'MMMM', + yearFormat: 'yyyy', + dayHeaderFormat: 'EEEE', + dayTitleFormat: 'MMMM yyyy', + disableWeekend: false, + disableSunday: false, + disableDates: null, + onSelectClose: null, + startingDay: 0, + minDate: null, + maxDate: null, + dueDate: null, + fromDate: null, + legendIcon: null, + legendMessage: null, + calendarDisabled: false, + collapseWait: 0, + orientation: 'right', + inline: false, + helperText: 'The date you selected is $date. In case of mobile double tap to open calendar. Select a date to close the calendar.', + datepickerEvalAttributes: ['dateFormat', 'dayFormat', 'monthFormat', 'yearFormat', 'dayHeaderFormat', 'dayTitleFormat', 'disableWeekend', 'disableSunday', 'startingDay', 'collapseWait', 'orientation'], + datepickerWatchAttributes: ['min', 'max', 'due', 'from', 'legendIcon', 'legendMessage', 'ngDisabled'], + datepickerFunctionAttributes: ['disableDates', 'onSelectClose'] +}) + +.factory('b2bDatepickerService', ['b2bDatepickerConfig', 'dateFilter', function (b2bDatepickerConfig, dateFilter) { + var setAttributes = function (attr, elem) { + if (angular.isDefined(attr) && attr !== null && angular.isDefined(elem) && elem !== null) { + var attributes = b2bDatepickerConfig.datepickerEvalAttributes.concat(b2bDatepickerConfig.datepickerWatchAttributes, b2bDatepickerConfig.datepickerFunctionAttributes); + for (var key in attr) { + var val = attr[key]; + if (attributes.indexOf(key) !== -1 && angular.isDefined(val)) { + elem.attr(key.toSnakeCase(), key); + } + } + } + }; + + var bindScope = function (attr, scope) { + if (angular.isDefined(attr) && attr !== null && angular.isDefined(scope) && scope !== null) { + var evalFunction = function (key, val) { + scope[key] = scope.$parent.$eval(val); + }; + + var watchFunction = function (key, val) { + scope.$parent.$watch(val, function (value) { + scope[key] = value; + }); + scope.$watch(key, function (value) { + scope.$parent[val] = value; + }); + }; + + var evalAttributes = b2bDatepickerConfig.datepickerEvalAttributes; + var watchAttributes = b2bDatepickerConfig.datepickerWatchAttributes; + for (var key in attr) { + var val = attr[key]; + if (evalAttributes.indexOf(key) !== -1 && angular.isDefined(val)) { + evalFunction(key, val); + } else if (watchAttributes.indexOf(key) !== -1 && angular.isDefined(val)) { + watchFunction(key, val); + } + } + } + }; + + return { + setAttributes: setAttributes, + bindScope: bindScope + }; +}]) + +.controller('b2bDatepickerController', ['$scope', '$attrs', 'dateFilter', '$element', '$position', 'b2bDatepickerConfig', function ($scope, $attrs, dateFilter, $element, $position, dtConfig) { + var format = { + date: getValue($attrs.dateFormat, dtConfig.dateFormat), + day: getValue($attrs.dayFormat, dtConfig.dayFormat), + month: getValue($attrs.monthFormat, dtConfig.monthFormat), + year: getValue($attrs.yearFormat, dtConfig.yearFormat), + dayHeader: getValue($attrs.dayHeaderFormat, dtConfig.dayHeaderFormat), + dayTitle: getValue($attrs.dayTitleFormat, dtConfig.dayTitleFormat), + disableWeekend: getValue($attrs.disableWeekend, dtConfig.disableWeekend), + disableSunday: getValue($attrs.disableSunday, dtConfig.disableSunday) + }, + startingDay = getValue($attrs.startingDay, dtConfig.startingDay); + + if($attrs.disableDates !== undefined) { + format.disableDates = $attrs.disableDates; + } else { + format.disableDates = dtConfig.disableDates; + } + $scope.minDate = dtConfig.minDate ? $scope.resetTime(dtConfig.minDate) : null; + $scope.maxDate = dtConfig.maxDate ? $scope.resetTime(dtConfig.maxDate) : null; + $scope.dueDate = dtConfig.dueDate ? $scope.resetTime(dtConfig.dueDate) : null; + $scope.fromDate = dtConfig.fromDate ? $scope.resetTime(dtConfig.fromDate) : null; + $scope.legendIcon = dtConfig.legendIcon ? dtConfig.legendIcon : null; + $scope.legendMessage = dtConfig.legendMessage ? dtConfig.legendMessage : null; + $scope.ngDisabled = dtConfig.calendarDisabled ? dtConfig.calendarDisabled : null; + $scope.collapseWait = getValue($attrs.collapseWait, dtConfig.collapseWait); + $scope.orientation = getValue($attrs.orientation, dtConfig.orientation); + $scope.onSelectClose = getValue($attrs.onSelectClose, dtConfig.onSelectClose); + + $scope.inline = $attrs.inline === 'true' ? true : dtConfig.inline; + + function getValue(value, defaultValue) { + return angular.isDefined(value) ? $scope.$parent.$eval(value) : defaultValue; + } + + function getDaysInMonth(year, month) { + return new Date(year, month, 0).getDate(); + } + + function getDates(startDate, n) { + var dates = new Array(n); + var current = startDate, + i = 0; + while (i < n) { + dates[i++] = new Date(current); + current.setDate(current.getDate() + 1); + } + return dates; + } + + this.updatePosition = function (b2bDatepickerPopupTemplate) { + $scope.position = $position.offset($element); + $scope.position.top = $scope.position.top + $element.prop('offsetHeight'); + $scope.position.left = $scope.position.left - (((b2bDatepickerPopupTemplate && b2bDatepickerPopupTemplate.prop('offsetWidth')) || 290) - $element.prop('offsetWidth')); + }; + + this.isDateInRange = function(date) { + + if ((compare(date, $scope.minDate) >= 0) && (compare(date, $scope.maxDate) <= 0)) { + return true; + } else { + return false; + } + return false; + } + + this.isDisbaledDate = function(date) { + if ($attrs.from && !angular.isDate($scope.fromDate)) { + return true; + } + if (format.disableWeekend === true && (dateFilter(date, format.dayHeader) === "Saturday" || dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (format.disableSunday === true && (dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + + return (($scope.minDate && compare(date, $scope.minDate) < 0) || ($scope.maxDate && compare(date, $scope.maxDate) > 0) || ($scope.datesCallBack({ + date: date + }))); + + } + function isSelected(dt) { + if (dt && angular.isDate($scope.currentDate) && compare(dt, $scope.currentDate) === 0) { + return true; + } + return false; + } + + function isFromDate(dt) { + if (dt && angular.isDate($scope.fromDate) && compare(dt, $scope.fromDate) === 0) { + return true; + } + return false; + } + + function isDateRange(dt) { + if (dt && $scope.fromDate && angular.isDate($scope.currentDate) && (compare(dt, $scope.fromDate) >= 0) && (compare(dt, $scope.currentDate) <= 0)) { + return true; + } else if (dt && $scope.fromDate && compare(dt, $scope.fromDate) === 0) { + return true; + } + return false; + } + + function isOld(date, currentMonthDate) { + if (date && currentMonthDate && (new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0).getTime() < new Date(currentMonthDate.getFullYear(), currentMonthDate.getMonth(), 1, 0, 0, 0).getTime())) { + return true; + } else { + return false; + } + } + + function isNew(date, currentMonthDate) { + if (date && currentMonthDate && (new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0).getTime() > new Date(currentMonthDate.getFullYear(), currentMonthDate.getMonth(), 1, 0, 0, 0).getTime())) { + return true; + } else { + return false; + } + } + + function isPastDue(dt) { + if ($scope.dueDate) { + return (dt > $scope.dueDate); + } + return false; + } + + function isDueDate(dt) { + if ($scope.dueDate) { + return (dt.getTime() === $scope.dueDate.getTime()); + } + return false; + } + + var isDisabled = function (date, currentMonthDate) { + if ($attrs.from && !angular.isDate($scope.fromDate)) { + return true; + } + if (format.disableWeekend === true && (dateFilter(date, format.dayHeader) === "Saturday" || dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (format.disableSunday === true && (dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (isOld(date, currentMonthDate) || isNew(date, currentMonthDate)) { + return true; + } + return (($scope.minDate && compare(date, $scope.minDate) < 0) || ($scope.maxDate && compare(date, $scope.maxDate) > 0) || ($scope.datesCallBack({ + date: date + }))); + }; + + var compare = function (date1, date2) { + if(date2 !== null ){ + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + } else { + return false + } + + }; + + function isMinDateAvailable(startDate, endDate) { + if (($scope.minDate && $scope.minDate.getTime() >= startDate.getTime()) && ($scope.minDate.getTime() <= endDate.getTime())) { + $scope.disablePrev = true; + $scope.visibilityPrev = "hidden"; + } else { + $scope.disablePrev = false; + $scope.visibilityPrev = "visible"; + } + } + + function isMaxDateAvailable(startDate, endDate) { + if (($scope.maxDate && $scope.maxDate.getTime() >= startDate.getTime()) && ($scope.maxDate.getTime() <= endDate.getTime())) { + $scope.disableNext = true; + $scope.visibilityNext = "hidden"; + } else { + $scope.disableNext = false; + $scope.visibilityNext = "visible"; + } + } + + function getLabel(label) { + if (label) { + var labelObj = { + pre: label.substr(0, 1).toUpperCase(), + post: label + }; + return labelObj; + } + return; + } + + function makeDate(date, dayFormat, dayHeaderFormat, isSelected, isFromDate, isDateRange, isOld, isNew, isDisabled, dueDate, pastDue) { + return { + date: date, + label: dateFilter(date, dayFormat), + header: dateFilter(date, dayHeaderFormat), + selected: !!isSelected, + fromDate: !!isFromDate, + dateRange: !!isDateRange, + oldMonth: !!isOld, + nextMonth: !!isNew, + disabled: !!isDisabled, + dueDate: !!dueDate, + pastDue: !!pastDue, + focusable: !((isDisabled && !(isSelected || isDateRange)) || (isOld || isNew)) + }; + } + + this.modes = [ + { + name: 'day', + getVisibleDates: function (date) { + var year = date.getFullYear(), + month = date.getMonth(), + firstDayOfMonth = new Date(year, month, 1), + lastDayOfMonth = new Date(year, month + 1, 0); + var difference = startingDay - firstDayOfMonth.getDay(), + numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : -difference, + firstDate = new Date(firstDayOfMonth), + numDates = 0; + + if (numDisplayedFromPreviousMonth > 0) { + firstDate.setDate(-numDisplayedFromPreviousMonth + 1); + numDates += numDisplayedFromPreviousMonth; // Previous + } + numDates += getDaysInMonth(year, month + 1); // Current + numDates += (7 - numDates % 7) % 7; // Next + + var days = getDates(firstDate, numDates), + labels = new Array(7); + for (var i = 0; i < numDates; i++) { + var dt = new Date(days[i]); + days[i] = makeDate(dt, + format.day, + format.dayHeader, + isSelected(dt), + isFromDate(dt), + isDateRange(dt), + isOld(dt, date), + isNew(dt, date), + isDisabled(dt, date), + isDueDate(dt), + isPastDue(dt)); + } + for (var j = 0; j < 7; j++) { + labels[j] = getLabel(dateFilter(days[j].date, format.dayHeader)); + } + isMinDateAvailable(firstDayOfMonth, lastDayOfMonth); + isMaxDateAvailable(firstDayOfMonth, lastDayOfMonth); + return { + objects: days, + title: dateFilter(date, format.dayTitle), + labels: labels + }; + }, + split: 7, + step: { + months: 1 + } + } + ]; +}]) + +.directive('b2bDatepicker', ['$parse', '$log', '$timeout', '$document', '$documentBind', '$isElement', '$templateCache', '$compile', 'trapFocusInElement', '$position', '$window', '$filter', 'b2bDatepickerConfig', function ($parse, $log, $timeout, $document, $documentBind, $isElement, $templateCache, $compile, trapFocusInElement, $position, $window, $filter, b2bDatepickerConfig) { + return { + restrict: 'EA', + scope: { + model: '=ngModel', + datesCallBack: '&disableDates', + onSelectClose: '&', + disabledInput: '=?ngDisabled', + newSelectedDate: '=selectNextMonth' + }, + require: ['b2bDatepicker', 'ngModel', '?^b2bDatepickerGroup'], + controller: 'b2bDatepickerController', + link: function (scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0], + ngModel = ctrls[1], + b2bDatepickerGroupCtrl = ctrls[2]; + var b2bDatepickerPopupTemplate; + var isCalendarOpened = false; + + // Configuration parameters + var mode = 0, + selected; + scope.isOpen = false; + var isValidDate = false; + + scope.headers = []; + scope.footers = []; + + if(scope.disabledInput === undefined || scope.disabledInput === '') { + scope.disabledInput = false; + } + if(attrs.inline == 'true'){ + element.after($compile($templateCache.get('b2bTemplate/calendar/datepicker-popup.html'))(scope)); + var temp = element.after(); + element.remove(); + element = temp; + } else { + var buttonTabIndex = scope.disabledInput===true ? -1 : 0; + element.after($compile('')(scope)); + element.attr('placeholder', 'MM/dd/yyyy'); + element.attr('b2b-format-date', b2bDatepickerConfig.dateFormat); + } + + scope.$watch('newSelectedDate', function(newVal,oldValue){ + + if(newVal !== oldValue){ + if (newVal !== '' && newVal !== undefined){ + selectNextAvailableMonth(newVal); + } + } + }); + + scope.$watch('model', function(val) { + + if(val !== undefined && val !== '') { + var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ; + + if(scope.model.length <8){ + ngModel.$setValidity('datePattern', false); + } else { + var inputDate = Date.parse(scope.model); + var inputElement + if(isNaN(inputDate)) { + ngModel.$setValidity('datePattern', false); + } else { + inputElement = $filter('date')(scope.model, "MM/dd/yyyy"); + } + if(!date_regex.test(inputElement) ){ + ngModel.$setValidity('datePattern', false); + } else { + ngModel.$setValidity('datePattern', true); + element[0].value = $filter('date')(scope.model, "MM/dd/yyyy"); + var parts = element[0].value.split('/'); + var enteredDate = new Date(parts[2], parts[0] - 1, parts[1]); + if (datepickerCtrl.isDateInRange(enteredDate)) { + ngModel.$setValidity('outOfRange', true); + if (!datepickerCtrl.isDisbaledDate(enteredDate)) { + ngModel.$setValidity('disabledDate', true); + } else { + ngModel.$setValidity('disabledDate', false); + } + } else { + ngModel.$setValidity('outOfRange', false); + } + } + } + } else if (scope.newSelectedDate !== '' && scope.newSelectedDate !== undefined){ + + selectNextAvailableMonth(scope.newSelectedDate); + + } else { + ngModel.$setValidity('datePattern', true); + } + + }); + + if (!ngModel) { + $log.error("ng-model is required."); + return; // do nothing if no ng-model + } + + if(scope.model !== undefined && scope.model !== '') { + element[0].value = $filter('date')(scope.model, "MM/dd/yyyy"); + } + + if (b2bDatepickerGroupCtrl) { + b2bDatepickerGroupCtrl.registerDatepickerScope(scope); + } + + + var selectNextAvailableMonth = function(dateSelected) { + + var date_regexTwo = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ; + + if(dateSelected.length <8){ + ngModel.$setValidity('datePattern', false); + } else { + var nextInputDate = Date.parse(dateSelected); + var nextInputElement + if(isNaN(nextInputDate)) { + ngModel.$setValidity('datePattern', false); + } else { + nextInputElement = $filter('date')(dateSelected, "MM/dd/yyyy"); + } + if(!date_regexTwo.test(nextInputElement) ){ + ngModel.$setValidity('datePattern', false); + } else { + ngModel.$setValidity('datePattern', true); + //var nextAvailableMonthSelected = + //element[0].value = $filter('date')(nextAvailableMonth, "MM/dd/yyyy"); + var nextParts = $filter('date')(dateSelected, "MM/dd/yyyy").split('/'); + var nextEnteredDate = new Date(nextParts[2], nextParts[0] - 1, nextParts[1]); + if (datepickerCtrl.isDateInRange(nextEnteredDate)) { + ngModel.$setValidity('outOfRange', true); + if (!datepickerCtrl.isDisbaledDate(nextEnteredDate)) { + ngModel.$setValidity('disabledDate', true); + scope.select(nextEnteredDate, false); + } else { + ngModel.$setValidity('disabledDate', false); + } + } else { + ngModel.$setValidity('outOfRange', false); + } + } + } + + } + + var calendarButton = angular.element(element[0].nextElementSibling); + + calendarButton.bind('click',function(){ + openCalendarPopup = false; + if (!scope.ngDisabled) { + scope.isOpen = !scope.isOpen; + toggleCalendar(scope.isOpen); + scope.$apply(); + datepickerCtrl.updatePosition(b2bDatepickerPopupTemplate); + $timeout(function () { + // angular.element(element[0].querySelector('.datepicker-input')).scrollTop=0; + },10); + } + }) + var openCalendarPopup = false; + + element.bind('blur', function() { + if(scope.model !== undefined && scope.model !== '') { + var dateEntered = scope.model; + + var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ; + + if(date_regex.test(dateEntered)) { + var parts = dateEntered.split('/'); + var enteredDate = new Date(parts[2],parts[0]-1,parts[1]); + + if(datepickerCtrl.isDateInRange(enteredDate)) { + isValidDate -= 1; + ngModel.$setValidity('outOfRange', true); + $timeout(function(){ + ngModel.$setValidity('outOfRange', true); + },10); + isValidDate = true; + if(!datepickerCtrl.isDisbaledDate(enteredDate)) { + $timeout(function(){ + ngModel.$setValidity('disabledDate', true); + },10); + scope.select(enteredDate); + openCalendarPopup = true; + } else { + $timeout(function(){ + ngModel.$setValidity('disabledDate', false); + },10); + isValidDate = false; + openCalendarPopup = false; + } + + } else { + isValidDate += 1; + $timeout(function(){ + ngModel.$setValidity('outOfRange', false); + },10); + isValidDate = false; + openCalendarPopup = false; + } + + } + } + }); + + var toggleCalendar = function (flag) { + if (!scope.inline) { + if (flag) { + b2bDatepickerPopupTemplate = angular.element($templateCache.get('b2bTemplate/calendar/datepicker-popup.html')); + b2bDatepickerPopupTemplate = $compile(b2bDatepickerPopupTemplate)(scope); + $document.find('body').append(b2bDatepickerPopupTemplate); + b2bDatepickerPopupTemplate.bind('keydown', keyPress); + $timeout(function () { + scope.getFocus = true; + trapFocusInElement(flag, b2bDatepickerPopupTemplate); + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + }, 100); + handleTabEvent(); + }); + angular.element(document.querySelector('.b2b-calendar-icon')).attr('aria-expanded','true'); + } else { + if(!openCalendarPopup) { + b2bDatepickerPopupTemplate.unbind('keydown', keyPress); + b2bDatepickerPopupTemplate.remove(); + } + element[0].focus(); + scope.getFocus = false; + angular.element(document.querySelector('.b2b-calendar-icon')).attr('aria-expanded','false'); + trapFocusInElement(flag, b2bDatepickerPopupTemplate); + } + } + }; + + var handleTabEvent = function(){ + b2bDatepickerPopupTemplate.find('td').on('keydown', function (e) { + if (e.keyCode == '9') { + if(e.shiftKey){ + if(b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.next')){ + b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.next').focus(); + }else{ + b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.datepicker-switch').focus() + } + }else{ + if(b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.prev')){ + b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.prev').focus(); + }else{ + b2bDatepickerPopupTemplate.find('tr')[0].querySelector('th.datepicker-switch').focus() + } + } + + e.preventDefault(); + e.stopPropagation(); + } + }); + } + + var outsideClick = function (e) { + var isElement = $isElement(angular.element(e.target), element, $document); + var isb2bDatepickerPopupTemplate = $isElement(angular.element(e.target), b2bDatepickerPopupTemplate, $document); + if (!(isElement || isb2bDatepickerPopupTemplate)) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + scope.$apply(); + } + }; + + var keyPress = function (ev) { + if (!ev.keyCode) { + if (ev.which) { + ev.keyCode = ev.which; + } else if (ev.charCode) { + ev.keyCode = ev.charCode; + } + } + if (ev.keyCode) { + if (ev.keyCode === 27) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === 33) { + !scope.disablePrev && scope.move(-1); + $timeout(function () { + scope.getFocus = true; + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + }, 100); + }); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === 34) { + !scope.disableNext && scope.move(1); + $timeout(function () { + scope.getFocus = true; + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + }, 100); + }); + ev.preventDefault(); + ev.stopPropagation(); + } + scope.$apply(); + } + }; + + $documentBind.click('isOpen', outsideClick, scope); + + var modalContainer = angular.element(document.querySelector('.modalwrapper')); + var modalBodyContainer = angular.element(document.querySelector('.b2b-modal-body')); + if (modalContainer) { + modalContainer.bind('scroll', function () { + if (b2bDatepickerPopupTemplate) { + datepickerCtrl.updatePosition(b2bDatepickerPopupTemplate); + scope.$apply(); + } + }); + } + if (modalBodyContainer) { + modalBodyContainer.bind('scroll', function () { + if (b2bDatepickerPopupTemplate) { + datepickerCtrl.updatePosition(b2bDatepickerPopupTemplate); + var datepickerTextfield = $position.offset(element); + var modalBodyPosition = $position.offset(modalBodyContainer); + + if (((datepickerTextfield.top + datepickerTextfield.height) < modalBodyPosition.top || datepickerTextfield.top > (modalBodyPosition.top + modalBodyPosition.height)) && scope.isOpen) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + } + scope.$apply(); + } + }); + } + var window = angular.element($window); + window.bind('resize', function () { + if (b2bDatepickerPopupTemplate) { + datepickerCtrl.updatePosition(b2bDatepickerPopupTemplate); + scope.$apply(); + } + }); + + scope.$on('$destroy', function () { + if (scope.isOpen) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + } + }); + + scope.resetTime = function (date) { + if (typeof date === 'string') { + date = date + 'T12:00:00'; + } + var dt; + if (!isNaN(new Date(date))) { + dt = new Date(date); + } else { + return null; + } + return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); + }; + + if (attrs.min) { + scope.$parent.$watch($parse(attrs.min), function (value) { + scope.minDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.max) { + scope.$parent.$watch($parse(attrs.max), function (value) { + scope.maxDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.due) { + scope.$parent.$watch($parse(attrs.due), function (value) { + scope.dueDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.from) { + scope.$parent.$watch($parse(attrs.from), function (value) { + scope.fromDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + + if (attrs.legendIcon) { + scope.$parent.$watch(attrs.legendIcon, function (value) { + scope.legendIcon = value ? value : null; + refill(); + }); + } + if (attrs.legendMessage) { + scope.$parent.$watch(attrs.legendMessage, function (value) { + scope.legendMessage = value ? value : null; + refill(); + }); + } + if (attrs.ngDisabled) { + scope.$parent.$watch(attrs.ngDisabled, function (value) { + scope.ngDisabled = value ? value : null; + }); + } + + // Split array into smaller arrays + function split(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + } + + function refill(date) { + if (angular.isDate(date) && !isNaN(date)) { + selected = new Date(date); + } else { + if (!selected) { + selected = new Date(); + } + } + + if (selected) { + var currentMode = datepickerCtrl.modes[mode], + data = currentMode.getVisibleDates(selected); + scope.rows = split(data.objects, currentMode.split); + var flag = false; + var startFlag = false; + var firstSelected = false; + for (var i = 0; i < scope.rows.length; i++) { + for (var j = 0; j < scope.rows[i].length; j++) { + + if (scope.rows[i][j].label === "1" && !firstSelected) { + firstSelected = true; + var firstDay = scope.rows[i][j]; + } + + if (scope.rows[i][j].selected === true) { + flag = true; + break; + } + } + if (flag) { + break; + } + } + if (!flag) { + firstDay.firstFocus = true; + } + + scope.labels = data.labels || []; + scope.title = data.title; + + datepickerCtrl.updatePosition(b2bDatepickerPopupTemplate); + } + } + + scope.select = function (date, ngModelPresent) { + + if(ngModelPresent === undefined){ + ngModelPresent = true; + } + var dt = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + if (!scope.onSelectClose || (scope.onSelectClose && scope.onSelectClose({ + date: dt + }) !== false)) { + if(ngModelPresent) { + scope.currentDate = dt; + element[0].value = $filter('date')(dt, "MM/dd/yyyy"); + } else { + console.log("dt:"+dt) + refill(dt); + } + ngModel.$setValidity('outOfRange', true); + if (angular.isNumber(scope.collapseWait)) { + $timeout(function () { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + }, scope.collapseWait); + } else { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + } + } + }; + + scope.move = function (direction,$event) { + var step = datepickerCtrl.modes[mode].step; + selected.setDate(1); + selected.setMonth(selected.getMonth() + direction * (step.months || 0)); + selected.setFullYear(selected.getFullYear() + direction * (step.years || 0)); + refill(); + + $timeout(function () { + trapFocusInElement(); + handleTabEvent(); + }, 100); + + $event.preventDefault(); + $event.stopPropagation(); + }; + + scope.trapFocus = function () { + $timeout(function () { + trapFocusInElement(); + }, 100); + }; + + scope.$watch('currentDate', function (value) { + if (angular.isDefined(value) && value !== null) { + refill(value); + } else { + refill(); + } + ngModel.$setViewValue(value); + }); + + ngModel.$render = function () { + scope.currentDate = ngModel.$viewValue; + }; + + var stringToDate = function (value) { + if (!isNaN(new Date(value))) { + value = new Date(value); + } + return value; + }; + ngModel.$formatters.unshift(stringToDate); + } + }; +}]) + + +.directive('b2bDatepickerGroup', [function () { + return { + restrict: 'EA', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + this.$$headers = []; + this.$$footers = []; + this.registerDatepickerScope = function (datepickerScope) { + datepickerScope.headers = this.$$headers; + datepickerScope.footers = this.$$footers; + }; + }], + link: function (scope, elem, attr, ctrl) {} + }; +}]) + +.directive('b2bFormatDate', ['dateFilter', function (dateFilter) { + return { + restrict: 'A', + require: 'ngModel', + link: function (scope, elem, attr, ctrl) { + var b2bFormatDate = ""; + attr.$observe('b2bFormatDate', function (value) { + b2bFormatDate = value; + }); + var dateToString = function (value) { + if (!isNaN(new Date(value))) { + return dateFilter(new Date(value), b2bFormatDate); + } + return value; + }; + ctrl.$formatters.unshift(dateToString); + } + }; +}]) + +.directive('b2bDatepickerHeader', [function () { + return { + restrict: 'EA', + require: '^b2bDatepickerGroup', + transclude: true, + replace: true, + template: '', + compile: function (elem, attr, transclude) { + return function link(scope, elem, attr, ctrl) { + if (ctrl) { + ctrl.$$headers.push(transclude(scope, function () {})); + } + elem.remove(); + }; + } + }; +}]) + +.directive('b2bDatepickerFooter', [function () { + return { + restrict: 'EA', + require: '^b2bDatepickerGroup', + transclude: true, + replace: true, + template: '', + compile: function (elem, attr, transclude) { + return function link(scope, elem, attr, ctrl) { + if (ctrl) { + ctrl.$$footers.push(transclude(scope, function () {})); + } + elem.remove(); + }; + } + }; +}]); +/** + * @ngdoc directive + * @name Template.att:cards + * + * @description + * + * + * @usage + + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.cards', ['ngMessages','b2b.att.utilities']); +/** + * @ngdoc directive + * @name Forms.att:checkboxes + * + * @description + * + * @usage + * See demo section + * @example + + + + + */ +angular.module('b2b.att.checkboxes', ['b2b.att.utilities']) +.directive('b2bSelectGroup', [function (){ + return { + restrict: 'A', + require: 'ngModel', + scope: { + checkboxes: "=" + }, + link: function (scope, elem, attr, ctrl) { + elem.bind('change', function () { + var isChecked = elem.prop('checked'); + angular.forEach(scope.checkboxes, function (item) { + item.isSelected = isChecked; + }); + scope.$apply(); + }); + scope.$watch('checkboxes', function () { + var setBoxes = 0; + if(scope.checkboxes === undefined) { + return; + } + angular.forEach(scope.checkboxes, function (item) { + if (item.isSelected) { + setBoxes++; + } + }); + elem.prop('indeterminate', false); + if ( scope.checkboxes !==undefined && setBoxes === scope.checkboxes.length && scope.checkboxes.length > 0) { + ctrl.$setViewValue(true); + elem.removeClass('indeterminate'); + } else if (setBoxes === 0) { + ctrl.$setViewValue(false); + elem.removeClass('indeterminate'); + } else { + ctrl.$setViewValue(false); + elem.addClass('indeterminate'); + elem.prop('indeterminate', true); + } + ctrl.$render(); + }, true); + } + }; + }]); +/** + * @ngdoc directive + * @name Misc.att:coachmark + * + * @description + * + * + * @usage + * + + + * @example +
+ HTML + AngularJS + + + + +
+ */ + +angular.module('b2b.att.coachmark', ['b2b.att.utilities','b2b.att.position']) + + .directive('b2bCoachmark', ['$document', '$compile', '$position', '$timeout', 'b2bViewport', 'keymap', function($document, $compile, $position, $timeout, b2bViewport, keymap) { + return { + restrict: 'A', + scope: { + coachmarks: '=', + coachmarkIndex: '=', + startCoachmarkCallback: '&', + endCoachmarkCallback: '&', + actionCoachmarkCallback: '&' + }, + link: function (scope, element, attrs, ctrl) { + var coachmarkItems = scope.coachmarks; + var body = $document.find('body').eq(0); + var coackmarkJqContainer; + var coackmarkContainer; + var coachMarkElement; + var backdropjqLiteEl; + var coachmarkHighlight; + var initaitedCoachmark = false; + scope.coackmarkElPos ={ + 'top':'', + 'left':'' + }; + + scope.currentCoachmark = {}; + + + var coachmarkBackdrop = function(){ + backdropjqLiteEl = angular.element('
'); + body.append(backdropjqLiteEl); + + backdropjqLiteEl.bind('click', function() { + scope.closeCoachmark(); + scope.$apply(); + }); + }; + + + scope.closeButtonFocus = function(){ + if(document.getElementsByClassName('b2b-coachmark-header').length >0){ + document.getElementsByClassName('b2b-coachmark-header')[0].scrollLeft = 0; + document.getElementsByClassName('b2b-coachmark-header')[0].scrollTop = 0; + } + } + + scope.actionCoachmark = function(action){ + scope.actionCoachmarkCallback({ + 'action':action + }) + }; + + scope.closeCoachmark = function(){ + initaitedCoachmark = false; + backdropjqLiteEl.remove(); + coackmarkContainer.remove(); + coachmarkHighlight.remove(); + if(coachMarkElement !== undefined && coachMarkElement !==""){ + coachMarkElement.removeClass('b2b-coachmark-label') + } + if (angular.isFunction(scope.endCoachmarkCallback)){ + scope.endCoachmarkCallback(); + } + element[0].focus(); + } + + var realStyle = function(_elem, _style) { + var computedStyle; + if ( typeof _elem.currentStyle != 'undefined' ) { + computedStyle = _elem.currentStyle; + } else { + computedStyle = document.defaultView.getComputedStyle(_elem, null); + } + + return _style ? computedStyle[_style] : computedStyle; + }; + + var copyComputedStyle = function(src, dest) { + var s = realStyle(src); + for ( var i in s ) { + // Do not use `hasOwnProperty`, nothing will get copied + if ( typeof i == "string" && i != "cssText" && !/\d/.test(i) && i.indexOf('webkit') !== 0 ) { + // The try is for setter only properties + try { + dest.style[i] = s[i]; + // `fontSize` comes before `font` If `font` is empty, `fontSize` gets + // overwritten. So make sure to reset this property. (hackyhackhack) + // Other properties may need similar treatment + if ( i == "font" ) { + dest.style.fontSize = s.fontSize; + } + } catch (e) {} + } + } + }; + + function showCoachmark(targetElement) { + + scope.currentCoachmark = targetElement; + if(coachMarkElement !== undefined && coachMarkElement !==""){ + coachMarkElement.removeClass('b2b-coachmark-label') + coackmarkContainer.remove(); + coachmarkHighlight.remove(); + } + coachMarkElement = angular.element(document.querySelector(targetElement.elementId)); + + var elementPosition = $position.offset(coachMarkElement); + + coachmarkHighlight = angular.element('
'); + coachmarkHighlight.css({ + 'width': (elementPosition.width + 25) +'px', + 'top': (elementPosition.top -10) + 'px', + 'left': (elementPosition.left - 10) + 'px', + 'height': (elementPosition.height + 20) +'px' + }); + if(targetElement.cloneHtml){ + var copy = coachMarkElement[0].cloneNode(true); + copy.id = "b2b-unique-"+targetElement.elementId.slice(1); + copyComputedStyle(coachMarkElement[0],copy); + var copychildNodes = copy.childNodes; + var coachmarkChildNodes = coachMarkElement[0].childNodes; + for(i=0;i'); + coackmarkContainer = $compile(coackmarkJqContainer)(scope); + body.append(coackmarkContainer); + + + $timeout(function () { + var currentCoachmarkContainer = document.getElementsByClassName('b2b-coachmark-container')[0]; + currentCoachmarkContainer.focus(); + + newElem = angular.element(currentCoachmarkContainer); + newElem.bind('keydown', function (e) { + if(e.keyCode == keymap.KEY.TAB){ + if(e.shiftKey) { + if(e.target.className === 'b2b-coachmark-container'){ + e.preventDefault(); + e.stopPropagation(); + } + } + } + }); + var coachmarkHeight = window.getComputedStyle(currentCoachmarkContainer).height.split('px')[0]; + var newOffsetHeight = Math.round(elementPosition.top) - elementPosition.height; + + // We need a slight offset to show the lightboxed item + if(!targetElement.cloneHtml){ + TweenLite.to(window, 2, {scrollTo:{x: (scope.coackmarkElPos.left.split('px')[0] - 100), y: newOffsetHeight-200}}); + } + }, 200); + } + + element.bind('click', function (e) { + initaitedCoachmark = true; + + scope.$watch('coachmarkIndex', function () { + if(initaitedCoachmark === true){ + if(scope.coachmarkIndex === -1){ + scope.closeCoachmark(); + }else{ + findAvailableCoachmark(scope.coachmarkIndex); + showCoachmark(scope.coachmarks[scope.coachmarkIndex]); + } + } + }); + coachmarkBackdrop(); + var findAvailableCoachmark = function(index){ + if(index === -1){ + scope.coachmarkIndex = 0; + } else if(!angular.isDefined(scope.coachmarks[index]) || angular.element(document.querySelector(scope.coachmarks[index].elementId)).length === 0){ + findAvailableCoachmark(index-1); + } else { + scope.coachmarkIndex = index; + } + } + if (angular.isFunction(scope.startCoachmarkCallback)){ + scope.startCoachmarkCallback(); + } + findAvailableCoachmark(scope.coachmarkIndex); + showCoachmark(scope.coachmarks[scope.coachmarkIndex]); + + $document.bind('keydown', function (evt) { + if (evt.which === 27 && initaitedCoachmark) { + scope.closeCoachmark(); + scope.$apply(); + } + }); + }); + //performance technique to ensure scroll event doesn't cause lag + var throttle = function(type, name, obj) { + obj = obj || window; + var running = false; + var func = function() { + if (running) { return; } + running = true; + requestAnimationFrame(function() { + obj.dispatchEvent(new CustomEvent(name)); + running = false; + }); + }; + obj.addEventListener(type, func); + }; + + scope.viewportWidth = b2bViewport.viewportWidth(); + /* init - you can init any event */ + throttle("resize", "optimizedResize"); + window.addEventListener("optimizedResize", function() { + if(initaitedCoachmark){ + showCoachmark(scope.coachmarks[scope.coachmarkIndex]); + scope.viewportWidth = b2bViewport.viewportWidth(); + scope.$digest(); + } + }); + } + }; + }]) + .directive('b2bCoachmarkContainer', ['$document', '$position', function($document, $position) { + return { + restrict: 'A', + transclude: true, + replace: true, + templateUrl: 'b2bTemplate/coachmark/coachmark.html', + link: function (scope, element, attrs, ctrl) { + + } + }; + }]); + + +/** + * @ngdoc directive + * @name Template.att:Configuration Section + * + * @description + * + * + * @example + *
+ HTML + AngularJS + + + + +
+ * + */ +angular.module('b2b.att.configurationSection', []) + +/** + * @ngdoc directive + * @name Template.att:Directory Listing + * + * @description + * + * + * @example + *
+ HTML + AngularJS + + + + +
+ * + */ +angular.module('b2b.att.directoryListingTemplate', []) + +/** + * @ngdoc directive + * @name Forms.att:dropdowns + * + * @description + * + * @usage + * + * @example +
+ + + + +
+ */ +angular.module('b2b.att.dropdowns', ['b2b.att.utilities', 'b2b.att.position', 'ngSanitize']) + +.constant('b2bDropdownConfig', { + prev: '37,38', + next: '39,40', + menuKeyword: 'menu', + linkMenuKeyword: 'link-menu', + largeKeyword: 'large', + smallKeyword: 'small' +}) + +.directive("b2bDropdown", ['$timeout', '$compile', '$templateCache', 'b2bUserAgent', 'b2bDropdownConfig', '$position', function ($timeout, $compile, $templateCache, b2bUserAgent, b2bDropdownConfig, $position) { + return { + restrict: 'A', + scope: true, + require: 'ngModel', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + scope.isInputDropdown = true; + scope.placeHoldertext = attr.placeholderText; + scope.containsSearch = true; + if (angular.isDefined(attr.containsSearch)) { + scope.containsSearch = attr.containsSearch; + } + if (attr.type) { + if (attr.type.indexOf(b2bDropdownConfig.menuKeyword) > -1 || attr.type.indexOf(b2bDropdownConfig.linkMenuKeyword) > -1) { + scope.isInputDropdown = false; + if (attr.type.indexOf(b2bDropdownConfig.linkMenuKeyword) > -1) { + scope.dropdownType = b2bDropdownConfig.linkMenuKeyword; + } else if (attr.type.indexOf(b2bDropdownConfig.menuKeyword) > -1) { + scope.dropdownType = b2bDropdownConfig.menuKeyword; + } + } + if (attr.type.indexOf(b2bDropdownConfig.largeKeyword) > -1) { + scope.dropdownSize = b2bDropdownConfig.largeKeyword; + } else if (attr.type.indexOf(b2bDropdownConfig.smallKeyword) > -1) { + scope.dropdownSize = b2bDropdownConfig.smallKeyword; + } + } + + scope.labelText = attr.labelText; + + scope.setBlur = function () { + if(!scope.toggleFlag){ + scope.setTouched(); + } + }; + + if ((scope.isInputDropdown && b2bUserAgent.notMobile()) || (!scope.isInputDropdown)) { + var formCtrl = elem.controller('form'); + scope.setNgModelController = function (name, ngModelCtrl) { + if (name && formCtrl && ngModelCtrl) { + formCtrl[name] = ngModelCtrl; + } + }; + scope.setOptionalCta = function (optionalCta) { + scope.optionalCta = optionalCta; + }; + var innerHtml = angular.element('
').append(elem.html()); + innerHtml = ($compile(innerHtml)(scope)).html(); + var template = angular.element($templateCache.get('b2bTemplate/dropdowns/b2bDropdownDesktop.html')); + template.find('ul').eq(0).append(innerHtml); + template = $compile(template)(scope); + elem.replaceWith(template); + } else if (scope.isInputDropdown && b2bUserAgent.isMobile()) { + elem.css({ + 'opacity': '0', + 'filter': 'alpha(opacity=0)' + }); + elem.addClass('awd-select isWrapped'); + elem.wrap(''); + var cover = angular.element(''); + elem.parent().append(cover); + elem.parent().append(''); + var set = function () { + var sel = elem[0] ? elem[0] : elem; + var selectedText = ""; + var selIndex = sel.selectedIndex; + if (typeof selIndex !== 'undefined') { + selectedText = sel.options[selIndex].text; + } + cover.text(selectedText).append(''); + }; + var update = function (value) { + $timeout(set, 100); + }; + + if (attr.ngModel) { + scope.$watch(attr.ngModel, function (newVal, oldVal) { + update(); + }); + } + elem.bind('keyup', function (ev) { + if (ev.keyCode === keymap.KEY.TAB || ev.keyCode === keymap.KEY.ESC) { + return; + } + set(); + }); + } + + }], + link: function (scope, elem, attr, ctrl) { + if ((scope.isInputDropdown && b2bUserAgent.notMobile()) || (!scope.isInputDropdown)) { + scope.updateModel = function () { + ctrl.$setViewValue(scope.currentSelected.value); + if (scope.dropdownRequired && scope.currentSelected.value === '') { + scope.setRequired(false); + } else { + scope.setRequired(true); + } + + if (scope.dropdownType === b2bDropdownConfig.linkMenuKeyword) { + $timeout(function () { + scope.appendCaretPositionStyle(); + }, 100); + } + }; + ctrl.$render = function () { + + $timeout(function () { + + if ((angular.isUndefined(ctrl.$viewValue) || ctrl.$viewValue == '') && (angular.isUndefined(scope.placeHoldertext) || scope.placeHoldertext == '')) { + scope.dropdownLists[ctrl.$viewValue] && scope.dropdownLists[ctrl.$viewValue][0].updateDropdownValue(); + } else if ((angular.isUndefined(scope.placeHoldertext) || scope.placeHoldertext == '') && ctrl.$viewValue !== '' ) { + scope.dropdownLists[ctrl.$viewValue] && scope.dropdownLists[ctrl.$viewValue][0].updateDropdownValue(); + } else if ((angular.isUndefined(ctrl.$viewValue) || ctrl.$viewValue == '') && scope.placeHoldertext !== '' ) { + scope.currentSelected.text = scope.placeHoldertext; + ctrl.$setViewValue(scope.placeHoldertext); + } else { + scope.dropdownLists[ctrl.$viewValue] && scope.dropdownLists[ctrl.$viewValue][0].updateDropdownValue(); + } + + }, 100); + }; + + scope.disabled = false; + scope.dropdownName = attr.name; + scope.dropdownId = attr.id; + scope.labelId = attr.ariaLabelledby; + scope.dropdownDescribedBy = attr.ariaDescribedby; + if (attr.required) { + scope.dropdownRequired = true; + } else { + scope.dropdownRequired = false; + } + elem.removeAttr('name'); + elem.removeAttr('id'); + scope.$parent.$watch(attr.ngDisabled, function (val) { + scope.disabled = val; + }); + } + } + }; +}]) + +.directive("b2bDropdownToggle", ['$document', '$documentBind', '$isElement', 'b2bDropdownConfig', 'keymap', 'b2bUtilitiesConfig', '$timeout', '$position', function ($document, $documentBind, $isElement, b2bDropdownConfig, keymap, b2bUtilitiesConfig, $timeout, $position) { + return { + restrict: 'A', + require: '?^b2bKey', + link: function (scope, elem, attr, ctrl) { + scope.appendCaretPositionStyle = function () { + while (document.querySelector('style.b2bDropdownCaret')) { + document.querySelector('style.b2bDropdownCaret').remove(); + }; + var caretPosition = $position.position(elem).width - 26; + if (scope.dropdownType === b2bDropdownConfig.linkMenuKeyword) { + var template = angular.element(''); + $document.find('head').append(template); + } + }; + + if (scope.isInputDropdown && (scope.labelText !== undefined)) { + elem.attr('aria-label', scope.labelText); + } + + scope.toggleFlag = false; + scope.dropdownLists = {}; + scope.dropdownListValues = []; + scope.dropdown = { + totalIndex: -1 + }; + scope.currentSelected = { + value: '', + text: '', + label: '', + index: -1 + }; + scope.dropdownTextList = []; + var searchString = ''; + + scope.removeItem = function(value){ + delete scope.dropdownLists[value]; + var index = scope.dropdownListValues.indexOf(value); + scope.dropdownListValues.splice(index,1); + scope.dropdownTextList=[]; + scope.dropdown.totalIndex = scope.dropdownListValues.length-1; + }; + var getDropdownText = function(){ + var dropdownItems = elem.parent().find('ul').children(); + var count = dropdownItems.length; + for(var i=0;i -1) { + return position; + } + return undefined; + }; + var startTimer = function (time) { + if (searchString === '') { + $timeout(function () { + searchString = ''; + }, time); + } + }; + scope.toggleDropdown = function (toggleFlag) { + if (!scope.disabled) { + if (angular.isDefined(toggleFlag)) { + scope.toggleFlag = toggleFlag; + } else { + scope.toggleFlag = !scope.toggleFlag; + } + if (!scope.toggleFlag) { + if (scope.isInputDropdown) { + elem.parent().find('input')[0].focus(); + } else { + elem.parent().find('button')[0].focus(); + } + scope.setTouched(); + } else { + scope.dropdown.highlightedValue = scope.currentSelected.value; + if (ctrl && ctrl.enableSearch) { + if (angular.isDefined(scope.dropdownLists[scope.currentSelected.value])) { + ctrl.resetCounter(scope.dropdownLists[scope.currentSelected.value][2]); + } + } + $timeout(function () { + if(scope.dropdownLists[scope.currentSelected.value] !== undefined){ + (scope.dropdownLists[scope.currentSelected.value][1])[0].focus(); + } else { + if (scope.isInputDropdown) { + elem.parent().find('input')[0].focus(); + } else { + elem.parent().find('button')[0].focus(); + } + } + }, 100); + if (scope.dropdownType === b2bDropdownConfig.linkMenuKeyword) { + scope.appendCaretPositionStyle(); + } + } + } + }; + + elem.bind('keydown', function (ev) { + if (!ev.keyCode) { + if (ev.which) { + ev.keyCode = ev.which; + } else if (ev.charCode) { + ev.keyCode = ev.charCode; + } + } + if (!scope.toggleFlag) { + if (ev.keyCode) { + var currentIndex = scope.currentSelected.index; + if (ev.keyCode === keymap.KEY.DOWN) { + scope.toggleDropdown(true); + ev.preventDefault(); + ev.stopPropagation(); + } else if (b2bDropdownConfig.prev.split(',').indexOf(ev.keyCode.toString()) > -1) { + angular.isDefined(scope.dropdownListValues[currentIndex - 1]) ? scope.dropdownLists[scope.dropdownListValues[currentIndex - 1]][0].updateDropdownValue() : angular.noop(); + ev.preventDefault(); + ev.stopPropagation(); + } else if (b2bDropdownConfig.next.split(',').indexOf(ev.keyCode.toString()) > -1) { + angular.isDefined(scope.dropdownListValues[currentIndex + 1]) ? scope.dropdownLists[scope.dropdownListValues[currentIndex + 1]][0].updateDropdownValue() : angular.noop(); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode >= 48 && ev.keyCode <= 105) { + startTimer(b2bUtilitiesConfig.searchTimer); + searchString = searchString + (keymap.MAP[ev.keyCode] || ''); + var position = searchElement(searchString); + angular.isDefined(scope.dropdownListValues[position]) ? scope.dropdownLists[scope.dropdownListValues[position]][0].updateDropdownValue() : angular.noop(); + ev.preventDefault(); + ev.stopPropagation(); + } + } + } else { + if (ev.altKey === true && ev.keyCode === keymap.KEY.UP) { + scope.toggleDropdown(false); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === keymap.KEY.TAB || ev.keyCode === keymap.KEY.ESC) { + scope.toggleDropdown(false); + ev.preventDefault(); + ev.stopPropagation(); + } + } + scope.$apply(); // TODO: Move this into each block to avoid expensive digest cycles + }); + var outsideClick = function (e) { + var isElement = $isElement(angular.element(e.target), elem.parent(), $document); + if (!isElement) { + scope.toggleDropdown(false); + scope.$apply(); + } + }; + $documentBind.click('toggleFlag', outsideClick, scope); + $documentBind.touch('toggleFlag', outsideClick, scope); + } + }; +}]) + +.directive("b2bDropdownGroup", ['$compile', '$templateCache', 'b2bUserAgent', function ($compile, $templateCache, b2bUserAgent) { + return { + restrict: 'A', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + if ((scope.isInputDropdown && b2bUserAgent.notMobile()) || (!scope.isInputDropdown)) { + var innerHtml = angular.element('
').append(elem.html()); + innerHtml = ($compile(innerHtml)(scope)).html(); + var template = angular.element($templateCache.get('b2bTemplate/dropdowns/b2bDropdownGroupDesktop.html')); + template.attr('ng-repeat', attr.optGroupRepeat); + template.attr('label', elem.attr('label')); + template.find('ul').append(innerHtml); + elem.replaceWith(template); + } else if (scope.isInputDropdown && b2bUserAgent.isMobile()) { + var template = angular.element(elem.prop('outerHTML')); + template.attr('ng-repeat', attr.optGroupRepeat); + template.removeAttr('b2b-dropdown-group'); + template.removeAttr('opt-group-repeat'); + template = $compile(template)(scope); + elem.replaceWith(template); + } + }] + }; +}]) + +.directive("b2bDropdownGroupDesktop", [function () { + return { + restrict: 'A', + scope: true, + link: function (scope, elem, attr, ctrl) { + scope.groupHeader = attr.label; + } + }; +}]) + +.directive("b2bDropdownList", ['$compile', '$templateCache', 'b2bUserAgent', function ($compile, $templateCache, b2bUserAgent) { + return { + restrict: 'A', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + if ((scope.isInputDropdown && b2bUserAgent.notMobile()) || (!scope.isInputDropdown)) { + var innerHtml = angular.element('
').append(elem.html()); + innerHtml = ($compile(innerHtml)(scope)).html(); + var template = angular.element($templateCache.get('b2bTemplate/dropdowns/b2bDropdownListDesktop.html')); + template.attr('ng-repeat', attr.optionRepeat); + template.attr('value', elem.attr('value')); + template.attr('search-key', elem.text()); + if (elem.attr('aria-describedby')){ + template.attr('aria-describedby', attr.ariaDescribedby); + } + if (elem.attr('imgsrc')) { + if (elem.attr('imgalt')) { + template.append('' + elem.attr('imgalt') + ''); + } else { + template.append(''); + } + } + template.append(innerHtml); + elem.replaceWith(template); + } else if (scope.isInputDropdown && b2bUserAgent.isMobile()) { + var template = angular.element(elem.prop('outerHTML')); + template.attr('ng-repeat', attr.optionRepeat); + if (elem.attr('aria-describedby')){ + template.attr('aria-describedby', attr.ariaDescribedby); + } + template.removeAttr('b2b-dropdown-list'); + template.removeAttr('option-repeat'); + template = $compile(template)(scope); + elem.replaceWith(template); + } + }] + }; +}]) + +.directive("b2bDropdownListDesktop", ['$sce', 'keymap', 'b2bDropdownConfig', function ($sce, keymap, b2bDropdownConfig) { + return { + restrict: 'A', + scope: true, + + link: function (scope, elem, attr, ctrl) { + var dropdownListValue = scope.dropdownListValue = attr.value; + scope.dropdown.totalIndex++; + var dropdownListIndex = scope.dropdown.totalIndex; + scope.dropdownListValues.push(dropdownListValue); + scope.dropdownLists[dropdownListValue] = []; + scope.dropdownLists[dropdownListValue][0] = scope; + scope.dropdownLists[dropdownListValue][1] = elem; + scope.dropdownLists[dropdownListValue][2] = dropdownListIndex; + scope.$parent.$parent.dropdownTextList=[]; + scope.updateDropdownValue = function () { + scope.currentSelected.value = dropdownListValue; + if (scope.isInputDropdown) { + scope.currentSelected.text = elem.text(); + scope.currentSelected.label = elem.text(); + } else if ((scope.dropdownType === b2bDropdownConfig.linkMenuKeyword) || (scope.dropdownType === b2bDropdownConfig.menuKeyword && scope.dropdownSize === b2bDropdownConfig.smallKeyword)) { + scope.currentSelected.text = dropdownListValue; + scope.currentSelected.label = dropdownListValue; + } else if (scope.dropdownType === b2bDropdownConfig.menuKeyword) { + scope.currentSelected.text = $sce.trustAsHtml(elem.html()); + scope.currentSelected.label = elem.text(); + } + scope.currentSelected.index = dropdownListIndex; + scope.updateModel(); + }; + scope.selectDropdownItem = function () { + scope.setDirty(); + scope.updateDropdownValue(); + scope.toggleDropdown(false); + }; + scope.highlightDropdown = function () { + scope.dropdown.highlightedValue = dropdownListValue; + }; + elem.bind('mouseover', function (ev) { + elem[0].focus(); + }); + + elem.bind('keydown', function (ev) { + if (!ev.keyCode) { + if (ev.which) { + ev.keyCode = ev.which; + } else if (ev.charCode) { + ev.keyCode = ev.charCode; + } + } + if (ev.altKey === true && ev.keyCode === keymap.KEY.UP) { + scope.toggleDropdown(false); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === keymap.KEY.TAB || ev.keyCode === keymap.KEY.ESC) { + scope.toggleDropdown(false); + ev.preventDefault(); + ev.stopPropagation(); + } + scope.$apply(); + }); + scope.$on('$destroy',function(){ + scope.removeItem(dropdownListValue); + }); + } + }; +}]) + +.directive("b2bDropdownRepeat", ['$compile', 'b2bUserAgent', function ($compile, b2bUserAgent) { + return { + restrict: 'A', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + if ((scope.isInputDropdown && b2bUserAgent.notMobile()) || (!scope.isInputDropdown)) { + var innerHtml = angular.element('
').append(elem.html()); + innerHtml = ($compile(innerHtml)(scope)).html(); + var template = angular.element('
'); + template.attr('ng-repeat', attr.b2bDropdownRepeat); + template.append(innerHtml); + elem.replaceWith(template); + } else if (scope.isInputDropdown && b2bUserAgent.isMobile()) { + angular.noop(); + } + }] + }; +}]) + +.directive("b2bDropdownValidation", ['$timeout', function ($timeout) { + return { + restrict: 'A', + require: 'ngModel', + link: function (scope, elem, attr, ctrl) { + $timeout(function () { + scope.setNgModelController(attr.name, ctrl); + }, 100); + scope.setDirty = function () { + if (ctrl.$dirty === false) { + ctrl.$dirty = true; + ctrl.$pristine = false; + } + }; + scope.setTouched = function () { + ctrl.$touched2 = true; + ctrl.$pristine = false; + }; + scope.setRequired = function (flag) { + ctrl.$setValidity('required', flag); + }; + } + }; +}]) + +.directive('b2bDropdownOptionalCta', [function () { + return { + restrict: 'EA', + transclude: true, + replace: true, + template: '', + compile: function (elem, attr, transclude) { + return function link(scope, elem, attr, ctrl) { + if (scope.setOptionalCta) { + scope.setOptionalCta(transclude(scope, function () {})); + } + elem.remove(); + }; + } + }; +}]); +/** + * @ngdoc directive + * @name Forms.att:File Upload + * + * @description + * + * + * @usage + * +
+
+

+
To upload a file, drag & drop it here or + + click here to select from your computer. +
+

+
+
+ * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.fileUpload', ['b2b.att.utilities']) + .directive('b2bFileDrop', [function() { + return { + restrict: 'EA', + scope: { + fileModel: '=', + onDrop: '&' + }, + controller: ['$scope', '$attrs', function($scope, $attrs) { + this.onDrop = $scope.onDrop; + }], + link: function(scope, element) { + element.addClass('b2b-dragdrop'); + element.bind( + 'dragover', + function(e) { + if (e.originalEvent) { + e.dataTransfer = e.originalEvent.dataTransfer; + } + e.dataTransfer.dropEffect = 'move'; + // allows us to drop + if (e.preventDefault) { + e.preventDefault(); + } + element.addClass('b2b-dragdrop-over'); + return false; + } + ); + element.bind( + 'dragenter', + function(e) { + // allows us to drop + if (e.preventDefault) { + e.preventDefault(); + } + element.addClass('b2b-dragdrop-over'); + return false; + } + ); + element.bind( + 'dragleave', + function() { + element.removeClass('b2b-dragdrop-over'); + return false; + } + ); + element.bind( + 'drop', + function(e) { + // Stops some browsers from redirecting. + if (e.preventDefault) { + e.preventDefault(); + } + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.originalEvent) { + e.dataTransfer = e.originalEvent.dataTransfer; + } + element.removeClass('b2b-dragdrop-over'); + if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { + scope.fileModel = e.dataTransfer.files[0]; + scope.$apply(); + if (angular.isFunction(scope.onDrop)) { + scope.onDrop(); + } + } + return false; + } + ); + } + }; + }]) + .directive('b2bFileLink', [function() { + return { + restrict: 'EA', + require: '^?b2bFileDrop', + replace: true, + transclude: true, + templateUrl: 'b2bTemplate/fileUpload/fileUpload.html', + scope: { + fileModel: '=?', + onFileSelect: '&' + }, + controller: ['$scope', function($scope) { + this.setFileModel = function(fileModel) { + if ($scope.takeFileModelFromParent) { + $scope.$parent.fileModel = fileModel; + $scope.$parent.$apply(); + } else { + $scope.fileModel = fileModel; + $scope.$apply(); + } + }; + this.callbackFunction = function() { + if (angular.isFunction($scope.onFileSelect)) { + $scope.onFileSelect(); + } + }; + + }], + link: function(scope, element, attr, b2bFileDropCtrl) { + scope.takeFileModelFromParent = false; + if (!(attr.fileModel) && b2bFileDropCtrl) { + scope.takeFileModelFromParent = true; + } + if (!(attr.onFileSelect) && b2bFileDropCtrl) { + scope.onFileSelect = b2bFileDropCtrl.onDrop; + } + } + }; + }]) + .directive('b2bFileChange', ['$log', '$rootScope', function($log, $rootScope) { + return { + restrict: 'A', + require: '^b2bFileLink', + link: function(scope, element, attr, b2bFileLinkCtrl) { + element.bind('change', changeFileModel); + + function changeFileModel(e) { + if (e.target.files && e.target.files.length > 0) { + b2bFileLinkCtrl.setFileModel(e.target.files[0]); + b2bFileLinkCtrl.callbackFunction(); + } else { + var strFileName = e.target.value; + try { + var objFSO = new ActiveXObject("Scripting.FileSystemObject"); + b2bFileLinkCtrl.setFileModel(objFSO.getFile(strFileName)); + b2bFileLinkCtrl.callbackFunction(); + } catch (e) { + var errMsg = "There was an issue uploading " + strFileName + ". Please try again."; + $log.error(errMsg); + $rootScope.$broadcast('b2b-file-link-failure', errMsg); + } + } + } + } + }; + }]); +/** + * @ngdoc directive + * @name Banners, marquees & tiles.b2b:filmstrip + * + * @description + * + * @usage + * + * + * @example +
+ HTML + AngularJS + + + + +
+ */ +angular.module('b2b.att.filmstrip', ['b2b.att.position', 'b2b.att.utilities', 'ds2Scroll']) + .directive('b2bFilmstrip', ['$document', '$window', '$timeout', 'keymap', 'b2bUserAgent', function ($document, $window, $timeout, keymap, userAgent) { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + filmstripType: '@', + filmstripHeading: '@' + }, + templateUrl: 'b2bTemplate/filmstrip/b2bFilmstrip.html', + compile: function (elem, attr) { + return this.link; + }, + controller: ['$scope', '$timeout', '$position', '$element', '$window', function ($scope, $timeout, $position, $element, $window) { + this.groups = []; + this.index = 0; + + this.addGroup = function (groupScope) { + var that = this; + groupScope.index = this.groups.length; + groupScope.focused = false; + this.groups.push(groupScope); + groupScope.$on('$destroy', function () { + that.removeGroup(groupScope); + }); + return groupScope.index; + }; + + this.removeGroup = function (group) { + var index = this.groups.indexOf(group); + if (index !== -1) { + this.groups.splice(this.groups.indexOf(group), 1); + } + }; + + this.registerElement = function (elem) { + $scope.iwidth = elem[0].clientWidth; + var window = angular.element($window); + var showFilmstripContent = function () { + if ($position.isElementInViewport($element)) { + $timeout(function () { + var container = $element[0].querySelector(".contents"); + angular.element(container).addClass('items-in'); + /*enable right arrow button only when container has scrollable content*/ + if(container.scrollWidth > container.clientWidth){ + angular.element($element[0].querySelector('.right-arrow')).attr('disabled', null); + } + }, 100); + $timeout(function () { + window.unbind('scroll', showFilmstripContent); + window.unbind('orientationchange', showFilmstripContent); + window.unbind('resize', showFilmstripContent); + }); + } + $scope.$apply(); + }; + window.bind('scroll', showFilmstripContent); + window.bind('orientationchange', showFilmstripContent); + window.bind('resize', showFilmstripContent); + $timeout(showFilmstripContent, 500); + }; + + this.cycle = function (group, down, noRecycle) { + if (!down) { + if (this.index <= 0 && !noRecycle) { + this.index = this.groups.length - 1; + } else { + this.index--; + } + } else { + if (this.index >= (this.groups.length - 1) && !noRecycle) { + this.index = 0; + } else { + this.index++; + } + } + group.focused = false; + this.groups[this.index].focused = true; + $scope.$apply(); + }; + + this.setId = function (id) { + $scope.cfsId = id; + }; + + this.getId = function () { + return $scope.cfsId; + }; + }], + link: function (scope, elem, attr, ctrl) { + var fsContent = elem[0].querySelector('.contents'), + rightArrow = elem[0].querySelector('.right-arrow'), + leftArrow = elem[0].querySelector('.left-arrow'); + if(fsContent.scrollLeft === 0){ + angular.element(leftArrow).attr('disabled', true); + angular.element(rightArrow).attr('disabled', true); + }; + scope.fsId = attr.id ? attr.id : ""; + ctrl.setId(scope.fsId); + scope.count = 0; + scope.isMobile = userAgent.isMobile(); + fsContent.addEventListener('scroll',function(e){ + var csl = e.currentTarget.scrollLeft; + var msl = (e.currentTarget.scrollWidth - e.currentTarget.offsetWidth); + if( csl === 0){ + angular.element(leftArrow).attr('disabled', true); + angular.element(rightArrow).attr('disabled', null); + } + else if( csl > 0 & csl < msl){ + angular.element(leftArrow).attr('disabled', null); + angular.element(rightArrow).attr('disabled', null); + } + else if((msl - csl) < 5){ + angular.element(leftArrow).attr('disabled', null); + angular.element(rightArrow).attr('disabled', true); + } + }); + fsContent.addEventListener('dragstart', function(e) { + e.preventDefault(); + }); + var viewerWidth = function (){ + item_width = fsContent.querySelectorAll('.item')[0].clientWidth; + scroll_unit = itemQty(fsContent); + return (item_width * scroll_unit); + }; + scope.moveright = function (){ + var offsetL = fsContent.scrollLeft + viewerWidth(); + angular.element(fsContent).eq(0).scrollTo(offsetL, 0, 800); + }; + scope.moveleft = function (){ + var offsetL = fsContent.scrollLeft - viewerWidth(); + angular.element(fsContent).eq(0).scrollTo(offsetL, 0, 800); + }; + // returns the number of visible items in the filmstrip + var itemQty = function (obj){ + var item = obj.querySelectorAll('.item')[1], + width = item.offsetWidth + 25; + return Math.floor(obj.clientWidth / width); + }; + elem.on('keydown', function (e){ + var code = e.keyCode, + RIGHT = 39 === code, LEFT = 37 === code, SPACE = 32 === code, ENTER = 13 === code, + tar = angular.element(e.target); + // if left or right arrow on the keyboard is pressed + if (LEFT || RIGHT) { + e.preventDefault() + // if focus on ul.contents, go to first list item + if (tar.hasClass('contents')) + { + var first = tar.children(':first-child') + tar.attr({ + 'tabindex': '-1', + 'aria-activedescendant': first.attr('id') + }) + first.attr({ + 'tabindex': '0', + 'aria-selected': 'true' + }).focus() + } else if (tar.hasClass('item') || e.target.tagName.toLowerCase === 'a') { + var li = e.target.tagName.toLowerCase === 'a' ? e.target.parentElement : e.target; + var item; + // skip hidden item + if (RIGHT && li.nextElementSibling) { + if (window.getComputedStyle(li.nextElementSibling).display === "none") { + item = li.nextElementSibling.nextElementSibling; + } else { + item = li.nextElementSibling; + } + ctrl.index++; + if(ctrl.index % itemQty(fsContent) === 0){ + scope.count++; + angular.element(leftArrow).attr('disabled', null); + } + } else if (LEFT && li.previousElementSibling) { + if (window.getComputedStyle(li.previousElementSibling).display === "none") { + item = li.previousElementSibling.previousElementSibling; + } else { + item = li.previousElementSibling; + } + ctrl.index--; + if(ctrl.index % itemQty(fsContent) === 0){ + scope.count--; + } + } + if (angular.element(item).length && window.getComputedStyle(item).display !== "none") { + angular.element(li).attr({ + 'tabindex': '-1', + 'aria-selected': 'false' + }).parent().attr('aria-activedescendant', angular.element(item).attr('id')); + + angular.element(item).attr({ + 'tabindex': '0', + 'aria-selected': 'true' + }); + angular.element(item)[0].focus(); + } + } + } + else if ((ENTER || SPACE) && tar.hasClass('item')) { + e.preventDefault(); + tar.children('a')[0].click(); + } + }); + if(!userAgent.isMobile()) { + scope.mouseEvent={}; + angular.element(fsContent).on('mousedown', function(e){ + if(!!fsContent){ + scope.mouseEvent.mouseDown = true + scope.mouseEvent.pageX = e.pageX + scope.mouseEvent.pageY = e.pageY + } + }); + + $document.on('mouseup', function(e){ + // check only mouseDown is set + if(scope.mouseEvent.mouseDown) { + // if mouse motion acting as drag, stop click + if(scope.mouseEvent.trace && scope.mouseEvent.trace.length > 3){ + e.preventDefault(); + } + // reset variables + scope.mouseEvent.mouseDown = false + scope.mouseEvent.trace = scope.mouseEvent.fsc = scope.mouseEvent.pageX = scope.mouseEvent.pageY = undefined + } + + }); + + elem.on('mousemove', function(e){ + if(scope.mouseEvent.mouseDown) { + // recording the delta of movements + scope.mouseEvent.movementX = e.pageX - scope.mouseEvent.pageX; + scope.mouseEvent.movementY = e.pageY - scope.mouseEvent.pageY; + scope.mouseEvent.pageX = e.pageX; + scope.mouseEvent.pageY = e.pageY; + var moved = scope.mouseEvent.movementX; + scope.mouseEvent.fsc = {}; + scope.mouseEvent.fsc.tar = elem[0].querySelector('.contents'); + scope.mouseEvent.fsc.scrolled = fsContent.scrollLeft || 0; + fsContent.scrollLeft = (scope.mouseEvent.fsc.scrolled - moved); + //scope.mouseEvent.fsc.tar.scrollLeft(scope.mouseEvent.fsc.scrolled - moved); + // a variable to track if mouse travel far enough to be determine as drag/swipe + scope.mouseEvent.trace = scope.mouseEvent.trace || []; + scope.mouseEvent.trace.push(scope.mouseEvent.movementX); + } + }); + + } + + + } + }; + }]) + .directive('b2bFilmstripContent', ['$timeout', 'keymap', function ($timeout, keymap) { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: {}, + require: '^b2bFilmstrip', + templateUrl: 'b2bTemplate/filmstrip/b2bFilmstripContent.html', + link: function (scope, elem, attr, ctrl) { + ctrl.registerElement(elem); + scope.cFsId = ctrl.getId(); + scope.isSelected = false; + scope.fsIndex = ctrl.addGroup(scope); + elem.css('left','0px'); + + if (scope.$parent.$first) { + elem.attr('tabindex', 0); + } + else { + elem.attr('tabindex', -1); + } + + scope.$watch("focused", function (value) { + if (!!value) { + $timeout(function () { + elem[0].focus(); + scope.isSelected = true; + }, 0); + } + else + { + scope.isSelected = false; + } + }); + + } + }; + }]) + .directive('b2bFilmstripViewmore', ['$timeout', function($timeout) { + return { + restrict: 'A', + transclude: false, + link: function (scope, elem, attr) { + elem.bind('click', function(){ + var nextElement = elem.next(); + $timeout(function () { + if(nextElement.length > 0){ + nextElement[0].focus(); + } + }, 0); + elem.remove(); + }); + } + }; + }]); + +/** + * @ngdoc directive + * @name Navigation.att:filters + * + * @description + * + * + * @usage + *
+ * + * @example + *
+ HTML + AngularJS + + + + +
+ * + */ +angular.module('b2b.att.filters', ['b2b.att.utilities', 'b2b.att.multipurposeExpander']) + .filter('filtersSelectedItemsFilter', [function () { + return function (listOfItemsArray) { + + if (!listOfItemsArray) { + listOfItemsArray = []; + } + + var returnArray = []; + + for (var i = 0; i < listOfItemsArray.length; i++) { + for (var j = 0; j < listOfItemsArray[i].filterTypeItems.length; j++) { + if (listOfItemsArray[i].filterTypeItems[j].selected && !listOfItemsArray[i].filterTypeItems[j].inProgress) { + returnArray.push(listOfItemsArray[i].filterTypeItems[j]); + } + } + } + + return returnArray; + }; + }]); +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:flyout + * + * @description + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.flyout', ['b2b.att.utilities', 'b2b.att.position']) + .directive('b2bFlyout', ['$timeout', 'b2bDOMHelper', 'keymap', 'events', function ($timeout, b2bDOMHelper, keymap, events) { + return { + restrict: 'EA', + transclude: true, + templateUrl: 'b2bTemplate/flyout/flyout.html', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + scope.flyoutOpened = false; + var contentScope = ''; + var togglerScope = ''; + this.registerContentScope = function (scp) { + contentScope = scp; + }; + this.registerTogglerScope = function (scp) { + togglerScope = scp; + }; + + this.toggleFlyoutState = function () { + if (contentScope) { + contentScope.toggleFlyout(); + } + }; + this.getTogglerDimensions = function () { + return togglerScope.getTogglerDimensions(); + } + this.setTogglerFocus = function () { + return togglerScope.setTogglerFocus(); + } + + this.closeFlyout = function (e) { + contentScope.closeFromChild(e); + }; + this.gotFocus = function () { + contentScope.gotFocus(); + }; + + this.updateAriaModel = function (val) { + scope.flyoutOpened = val; + }; + + var firstTabableElement = undefined, + lastTabableElement = undefined; + + var firstTabableElementKeyhandler = function (e) { + if (!e.keyCode) { + e.keyCode = e.which; + } + if (e.keyCode === keymap.KEY.TAB && e.shiftKey && scope.flyoutOpened) { + contentScope.gotFocus(); + events.preventDefault(e); + events.stopPropagation(e); + } + }; + + var lastTabableElementKeyhandler = function (e) { + if (!e.keyCode) { + e.keyCode = e.which; + } + if (e.keyCode === keymap.KEY.TAB && !e.shiftKey) { + contentScope.gotFocus(); + events.preventDefault(e); + events.stopPropagation(e); + } + }; + this.associateTabEvent = function(){ + $timeout(function () { + var element = elem[0].getElementsByClassName('b2b-flyout-container')[0]; + firstTabableElement = b2bDOMHelper.firstTabableElement(element); + lastTabableElement = b2bDOMHelper.lastTabableElement(element); + if(angular.isUndefined(firstTabableElement)){ + angular.element(element).css('display','block'); + firstTabableElement = b2bDOMHelper.firstTabableElement(element); + lastTabableElement = b2bDOMHelper.lastTabableElement(element); + angular.element(element).css('display','none'); + } + angular.element(firstTabableElement).bind('keydown', firstTabableElementKeyhandler); + angular.element(lastTabableElement).bind('keydown', lastTabableElementKeyhandler); + }); + } + this.updateTabbableElements = function(){ + $timeout(function () { + var element = elem[0].getElementsByClassName('b2b-flyout-container')[0]; + angular.element(element).css('display','block'); + firstTabableElement = b2bDOMHelper.firstTabableElement(element); + lastTabableElement = b2bDOMHelper.lastTabableElement(element); + angular.element(firstTabableElement).bind('keydown', firstTabableElementKeyhandler); + angular.element(lastTabableElement).bind('keydown', lastTabableElementKeyhandler); + angular.element(element).css('display','none'); + }); + } + this.unbindTabbaleEvents = function(){ + if(angular.isDefined(firstTabableElement)){ + angular.element(firstTabableElement).unbind('keydown', firstTabableElementKeyhandler); + } + + if(angular.isDefined(lastTabableElement)){ + angular.element(lastTabableElement).unbind('keydown', lastTabableElementKeyhandler); + } + } + }], + link: function (scope, element, attrs, ctrl) { + + } + }; + }]) + .directive('b2bFlyoutToggler', [function () { + return { + restrict: 'A', + require: '^b2bFlyout', + link: function (scope, element, attrs, ctrl) { + element.bind('click', function (e) { + ctrl.toggleFlyoutState(); + }); + + scope.getTogglerDimensions = function () { + return element[0].getBoundingClientRect(); + } + + scope.setTogglerFocus = function () { + element[0].focus(); + } + + ctrl.registerTogglerScope(scope); + } + }; + }]) + .directive('b2bFlyoutContent', ['$position', '$timeout', '$documentBind', '$isElement', '$document', function ($position, $timeout, $documentBind, $isElement, $document) { + return { + restrict: 'EA', + transclude: true, + replace: true, + require: '^b2bFlyout', + scope: { + horizontalPlacement: '@', + verticalPlacement: '@', + flyoutStyle: '@', + flyoutTitle: '@', + contentUpdated: "=?" + }, + templateUrl: 'b2bTemplate/flyout/flyoutContent.html', + link: function (scope, element, attrs, ctrl) { + var flyoutStyleArray, eachCssProperty, cssPropertyKey, cssPropertyVal, temp; + scope.openFlyout = false; + if (!scope.horizontalPlacement) { + scope.horizontalPlacement = 'center'; + } + if (!scope.verticalPlacement) { + scope.verticalPlacement = 'below'; + } + + scope.toggleFlyout = function () { + + scope.openFlyout = !scope.openFlyout; + + if (scope.openFlyout) { + + if (angular.isDefined(scope.flyoutStyle) && scope.flyoutStyle != "") { + flyoutStyleArray = scope.flyoutStyle.split(";"); + for (i = 0; i < flyoutStyleArray.length; i++) { + eachCssProperty = flyoutStyleArray[i].split(":"); + if (eachCssProperty.length == 2) { + cssPropertyKey = eachCssProperty[0].trim(); + cssPropertyVal = eachCssProperty[1].trim(); + angular.element(element[0])[0].style[cssPropertyKey] = cssPropertyVal; + } + } + } + + angular.element(element[0]).css({ + 'opacity': 0, + 'display': 'block' + }); + + var flyoutIcons = angular.element(document.querySelectorAll(".b2b-flyout-icon")); + angular.forEach(flyoutIcons, function (elm) { + angular.element(elm)[0].blur(); + }); + + $timeout(function () { + ctrl.setTogglerFocus(); + + var togglerDimensions = ctrl.getTogglerDimensions(); + var flyoutDimensions = element[0].getBoundingClientRect(); + + switch (scope.horizontalPlacement) { + case "left": + angular.element(element[0]).css({ + 'left': ((togglerDimensions.width / 2) - 26) + 'px' + }); + break; + case "right": + angular.element(element[0]).css({ + 'right': ((togglerDimensions.width / 2) - 23) + 'px' + }); + break; + + case "centerLeft": + var marginLeft = 10-(flyoutDimensions.width)-20; + angular.element(element[0]).css({ + 'margin-left': marginLeft + 'px' + }); + break; + case "centerRight": + angular.element(element[0]).css({ + 'left': ((togglerDimensions.width + 9 )) + 'px' + }); + break; + + default: + var marginLeft = (togglerDimensions.width / 2) - (flyoutDimensions.width / 2) - 8; + angular.element(element[0]).css({ + 'margin-left': marginLeft + 'px' + }); + } + + switch (scope.verticalPlacement) { + case "above": + angular.element(element[0]).css({ + 'top': -(flyoutDimensions.height + 13) + 'px' + }); + break; + case "centerLeft": + angular.element(element[0]).css({ + 'top': -((togglerDimensions.height-13))+ 'px' + }); + break; + case "centerRight": + angular.element(element[0]).css({ + 'top': -(flyoutDimensions.height - 23)+ 'px' + }); + break; + default: + angular.element(element[0]).css({ + 'top': (togglerDimensions.height + 13) + 'px' + }); + } + + angular.element(element[0]).css({ + 'opacity': 1 + }); + }, 100); + } else { + scope.hideFlyout(); + } + }; + + scope.gotFocus = function () { + scope.openFlyout = false; + scope.hideFlyout(); + ctrl.setTogglerFocus(); + scope.$apply(); + }; + + scope.closeFromChild = function (e) { + scope.openFlyout = false; + scope.hideFlyout(); + ctrl.setTogglerFocus(); + scope.$apply(); + }; + + scope.hideFlyout = function () { + angular.element(element[0]).css({ + 'opacity': 0, + 'display': 'none' + }); + }; + + scope.closeFlyout = function (e) { + var isElement = $isElement(angular.element(e.target), element, $document); + if ((e.type === "keydown" && e.which === 27) || ((e.type === "click" || e.type==="touchend") && !isElement)) { + scope.openFlyout = false; + scope.hideFlyout(); + ctrl.setTogglerFocus(); + scope.$apply(); + } + }; + + scope.$watch('openFlyout', function () { + ctrl.updateAriaModel(scope.openFlyout); + }); + + $documentBind.click('openFlyout', scope.closeFlyout, scope); + $documentBind.event('keydown', 'openFlyout', scope.closeFlyout, scope); + $documentBind.event('touchend', 'openFlyout', scope.closeFlyout, scope); + ctrl.registerContentScope(scope); + + if (angular.isDefined(scope.contentUpdated) && scope.contentUpdated !== null) { + scope.$watch('contentUpdated', function (newVal, oldVal) { + if(newVal){ + if (newVal !== oldVal) { + ctrl.unbindTabbaleEvents(); + ctrl.associateTabEvent(); + } + scope.contentUpdated = false; + } + }); + } + + } + }; + }]) + .directive('b2bCloseFlyout', [function () { + return { + restrict: 'A', + require: '^b2bFlyout', + scope: { + closeFlyout: '&' + }, + link: function (scope, element, attrs, ctrl) { + element.bind('click touchstart', function (e) { + scope.closeFlyout(e); + ctrl.closeFlyout(e); + }); + } + }; + }]) + .directive('b2bFlyoutTrapFocusInside', [function () { + return { + restrict: 'A', + transclude: false, + require: '^b2bFlyout', + link: function (scope, elem, attr, ctrl) { + /* Before opening modal, find the focused element */ + ctrl.updateTabbableElements(); + } + }; + }]); +/** + * @ngdoc directive + * @name Layouts.att:footer + * + * @description + * + * + * @usage + * + + + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.footer', ['b2b.att.utilities']). + directive('b2bColumnSwitchFooter', [function() { + return { + restrict: 'A', + transclude: true, + scope: { + footerLinkItems: "=" + }, + templateUrl: 'b2bTemplate/footer/footer_column_switch_tpl.html', + link: function(scope) { + var tempFooterColumns = scope.footerLinkItems.length; + scope.footerColumns = 3; + if ( (tempFooterColumns === 5) || (tempFooterColumns === 4) ) { + scope.footerColumns = tempFooterColumns; + } + } + + }; + + }]); + + +/** + * @ngdoc directive + * @name Layouts.att:header + * + * @description + * + * + * @usage + * + * + * @example + *
+ + + + +
+ * + */ +angular.module('b2b.att.header', ['b2b.att.dropdowns','b2b.att.utilities']) + .directive('b2bHeaderMenu', ['keymap', '$documentBind', '$timeout', '$isElement', '$document', function (keymap, $documentBind, $timeout, $isElement, $document) { + return { + restrict: 'A', + controller:['$scope',function($scope){ + this.nextSiblingFocus = function (elObj,flag) { + if (elObj.nextElementSibling) { + if(flag){ + var nextmenuItem = this.getFirstElement(elObj.nextElementSibling,'a'); + nextmenuItem.focus(); + }else{ + elObj.nextElementSibling.focus(); + } + } + }; + + this.previousSiblingFocus = function (elObj,flag) { + if (elObj.previousElementSibling) { + if(flag){ + var prevmenuItem = this.getFirstElement(elObj.previousElementSibling,'a'); + prevmenuItem.focus(); + }else{ + elObj.previousElementSibling.focus(); + } + } + }; + + this.getFirstElement = function(elmObj,selector){ + return elmObj.querySelector(selector); + }; + }], + link: function (scope, elem,attr,ctrl) { + scope.showMenu = false; + var activeElm, subMenu, tertiaryMenu, el= angular.element(elem)[0], + menuItem = angular.element(elem[0].children[0]); + menuItem.bind('click', function () { + elem.parent().children().removeClass('active'); + elem.addClass('active'); + var elems= this.parentElement.parentElement.querySelectorAll('li[b2b-header-menu]>a'); + for (var i=0; i"); + $timeout(function(){ + var menuItem = angular.element(elem[0].children[0]); + menuItem.bind('focus mouseenter', function () { + elem.parent().children().removeClass('active'); + elem.addClass('active'); + if(elem[0].childElementCount > 1){ // > 1 has third level menu + menuItem.attr('aria-expanded',true); + menuItem.attr('aria-haspopup',true); + } + var caretLeft = (elem[0].offsetLeft + elem[0].offsetWidth/2) - 10; + caretSign.css({left: caretLeft + 'px'}); + angular.element(caretSign); + var tertiaryItems = elem[0].querySelectorAll('[b2b-header-tertiarymenu]'); + if(tertiaryItems.length >=1){ + elem.append(caretSign); + } + }); + menuItem.bind('blur', function () { + $timeout(function () { + var parentElm = document.activeElement.parentElement.parentElement; + if(parentElm){ + if (!(parentElm.hasAttribute('b2b-header-tertiarymenu'))) { + elem.removeClass('active'); + if(elem[0].childElementCount > 1){ // > 1 has third level menu + menuItem.attr('aria-expanded',false); + } + var caret = elem[0].querySelector('.menuCaret'); + if(caret){ + caret.remove(); + } + } + } + }); + }); + }); + } + }; + }]).directive('b2bHeaderTertiarymenu', ['$timeout','keymap', function ($timeout,keymap){ + return{ + restrict: 'A', + require:'^b2bHeaderMenu', + link: function (scope, elem,attr,ctrl) { + + elem.bind('keydown', function (evt) { + var activeElm = document.activeElement; + var activeParentElm = activeElm.parentElement; + var activeParentObj = angular.element(activeParentElm)[0]; + + if(activeParentElm.hasAttribute('b2b-tertiary-link')){ + var quarterNav = angular.element(activeParentElm)[0].querySelector('li[b2b-header-quarternarymenu]'); + if(quarterNav){ + var links = ctrl.getFirstElement(angular.element(quarterNav)[0],'a'); + } + } + var tertiaryMenu = activeElm.parentElement.parentElement.parentElement; + var tertiaryMenuFlag = tertiaryMenu.hasAttribute('b2b-tertiary-link'); + + switch (evt.keyCode) { + case keymap.KEY.DOWN: + evt.stopPropagation(); + evt.preventDefault(); + if (activeParentElm.hasAttribute('b2b-tertiary-link')) { + if(angular.element(quarterNav).hasClass('active')){ + links.focus(); + }else if(activeParentObj.nextElementSibling){ + ctrl.nextSiblingFocus(activeParentObj,true); + } + } + else if(angular.element(activeParentElm).hasClass('active')){ + ctrl.nextSiblingFocus(activeElm); + } + break; + case keymap.KEY.UP: + evt.stopPropagation(); + evt.preventDefault(); + if(activeParentElm.hasAttribute('b2b-tertiary-link')){ + if(activeParentObj.previousElementSibling.hasAttribute('b2b-tertiary-link')){ + ctrl.previousSiblingFocus(activeParentObj,true); + }else{ + var elm = angular.element(activeElm.parentElement.parentElement.parentElement.parentElement.parentElement)[0]; + ctrl.getFirstElement(elm,"a").focus(); + } + }else if(angular.element(activeParentElm).hasClass('active')){ + if (activeElm.previousElementSibling) { + ctrl.previousSiblingFocus(activeElm); + }else if (tertiaryMenuFlag) { + var elm = angular.element(tertiaryMenu)[0]; + ctrl.getFirstElement(elm,"a.header-tertiaryitem").focus(); + } + } + break; + default: + break; + } + }); + } + }; + }]).directive('b2bHeaderTogglemenu', ['$timeout', 'keymap', function ($timeout, keymap) { + return{ + restrict: 'A', + require: '^b2bHeaderMenu', + link: function (scope, elem, attrs, ctrl) { + var quarterNav; + $timeout(function () { + quarterNav = angular.element(elem.parent())[0].querySelector('li[b2b-header-quarternarymenu]'); + elem.bind('click', function () { + angular.element(quarterNav).toggleClass('active'); + }); + }); + } + }; + }]).directive('b2bHeaderResponsive', ['$timeout',function ($timeout) { + return{ + restrict: 'A', + controller: function($scope){ + this.applyMediaQueries = function(value){ + document.querySelector('style').textContent += + "@media screen and (max-width:950px) { \ + .header__item.profile { right: " + value + "px; } \ + }"; + }; + this.arrangeResponsiveHeader = function(children){ + /* + * clientWidth of 1090 === max-width of 1100px + * clientWidth of 920 === max-width of 950px + * see b2b-angular.css for rest of responsive header CSS + */ + if (document.documentElement.clientWidth <= 920) { + switch(children){ + case 1: + this.applyMediaQueries(200); + break; + case 2: + this.applyMediaQueries(200); + break; + default: // anthing above 3, however, should not have more than 3 to date + this.applyMediaQueries(200); + } + } + } + }, + link: function (scope, elem, attrs, ctrl) { + var children; + var profile; + + // onload of page + $timeout(function(){ + profile = document.querySelector('li.header__item.profile'); + children = angular.element(profile).children().length; + + ctrl.arrangeResponsiveHeader(children); // shift right-side icon flyovers + }); + + // on screen resize + window.addEventListener('resize', function(event){ // caret adjustmet + var activeSubmenu = elem[0].querySelector('[b2b-header-menu] [b2b-header-submenu].active'); + var activeSubmenuEl = angular.element(activeSubmenu); + if(activeSubmenu){ + var caretSign = activeSubmenu.querySelector('i.menuCaret'); + if(caretSign){ + var caretSignEl = angular.element(caretSign); + var caretLeft = (activeSubmenu.offsetLeft + activeSubmenu.offsetWidth/2) - 10; + caretSignEl.css({left: caretLeft + 'px'}); + } + } + + ctrl.arrangeResponsiveHeader(children); // shift right-side icon flyovers + }); + } + }; + }]); + +/** + * @ngdoc directive + * @name Layouts.att:headings & copy + * + * @description + * + * + * @example +
+ HTML + AngularJS + + + +
+ */ + +var b2bLegalCopy = angular.module('b2b.att.headingsAndCopy', []); +/** + * @ngdoc directive + * @name Tabs, tables & accordions.att:horizontalTable + * + * @description + * + * + * @usage + * @param {int} sticky - Number of sticky columns to have. Maximum of 3. + * @param {boolean} refresh - A boolean that when set to true will force a re-render of table. Only use when using 'bulk mode' + * @param {string} legendContent - A string of html to fill in the legend flyout. This should generally be a
    with
  • and should not rely on Angular for repeating. + * @param {boolean} retainColumnSet - A boolean that on re-render of the table, determines if the columns visible should reset to 0 or not. Default is false. + * @param {boolean} columnsUpdated - A boolean that needs to be set to when the number of columns are increased or decreased, or if the ordering of the columns is changed. + * @param {array} columnsPerView - A list of integers that tells how many columns needs to be displayed per view. + * @param {int} defaultNumberOfColumns - An integer that tells how many columns needs to be displayed per each view. By default value is 6. This can be used if the number of columns displayed per each view is constant instaed of columnsPerView attribue. + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.horizontalTable', []) + .constant('b2bHorizontalTableConfig', { + 'maxStickyColumns': 3, + 'defaultNumberOfColumns': 6 + }) + .directive('b2bHorizontalTable', ['$timeout', 'b2bHorizontalTableConfig', function ($timeout, b2bHorizontalTableConfig) { + return { + restrict: 'EA', + scope: true, + transclude: true, + scope: { + numOfStickyCols: '=?sticky', + refresh: '=?', + legendContent: '=?', + retainColumnSet: '=?', + columnsUpdated: '=?', + columnsPerView: '=?', + defaultNumberOfColumns: '=?' + }, + templateUrl: 'b2bTemplate/horizontalTable/horizontalTable.html', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + var columnSets = []; + var currentSet = []; + var setIndex = -1; + var thElements = elem.find('th'); + var tableColumns = []; + var tableRows = elem.find('tr'); + var displayNoneCSS = {'display': 'none'}; + var displayBlockCSS = {'display': 'table-cell'}; + var endIndex = -1; + var startDisplayIndex = -1; + var endDisplayIndex = -1; + + if (!(attr.retainColumnSet !== undefined && attr.retainColumnSet !== '')) { + scope.retainColumnSet = true; + } + var defaultNumberOfColumns = attr.defaultNumberOfColumns ? scope.$eval(attr.defaultNumberOfColumns) : b2bHorizontalTableConfig.defaultNumberOfColumns; + function init(){ + defaultNumberOfColumns = attr.defaultNumberOfColumns ? scope.$eval(attr.defaultNumberOfColumns) : b2bHorizontalTableConfig.defaultNumberOfColumns; + tableColumns = []; + scope.countDisplayText = ""; + for(var count = 1; count <= scope.numOfStickyCols; count++) { + scope.countDisplayText = scope.countDisplayText + count + ", " + } + tableRows = elem.find('tr'); + angular.forEach(tableRows, function(row, rowIndex) { + for(var j = 0; j < row.children.length; j++) { + if (tableColumns[j] === undefined) { + tableColumns[j] = []; + } + tableColumns[j].push(row.children[j]); + } + }); + scope.numOfCols = tableColumns.length; + columnSets = []; + var tempIndex = 0; + for (var i = scope.numOfStickyCols; i < tableColumns.length;) { + if(attr.columnsPerView !== undefined && attr.columnsPerView !== ''){ + endIndex = i+scope.columnsPerView[tempIndex]-scope.numOfStickyCols-1; + tempIndex++; + }else{ + endIndex = i+defaultNumberOfColumns-scope.numOfStickyCols-1; + } + + if(endIndex > tableColumns.length-1){ + endIndex = tableColumns.length-1 + } + columnSets.push([i, endIndex]); + i = endIndex + 1; + } + + for(var i = 0; i < scope.numOfStickyCols; i++) { + for (var j = 0; j < tableRows.length; j++) { + thObject = angular.element(tableRows[j].children[i]); + angular.element(thObject).css({ + 'background-color': '#F2F2F2' + }); + } + } + thElements = elem.find('th'); + currentSet = columnSets[setIndex]; + checkScrollArrows(); + if(!scope.retainColumnSet){ + setIndex = 0; + for(var i = 0; i < thElements.length; i++){ + angular.element(thElements[i]).css(displayNoneCSS) + } + for(var i = 0; i < defaultNumberOfColumns; i++){ + angular.element(thElements[i]).css(displayBlockCSS) + } + + if (!scope.$$phase) { + scope.$apply(); + } + } + if (!scope.$$phase) { + scope.$apply(); + } + } + + $timeout(function () { + setIndex = 0; + init(); + },200); + + if (scope.refresh !== undefined) { + scope.$watch('refresh', function(oldVal, newVal) { + if (scope.refresh) { + // From testing it takes about 30 ms before ngRepeat executes, so let's set initial timeout + // NOTE: May need to expose timeout to developers. Application is known to have digest cycle of 3-5k watches. + $timeout(init, 100, false); + scope.refresh = false; + } + }); + } + if (scope.columnsUpdated !== undefined) { + scope.$watch('columnsUpdated', function(oldVal, newVal) { + if (scope.columnsUpdated) { + // From testing it takes about 30 ms before ngRepeat executes, so let's set initial timeout + // NOTE: May need to expose timeout to developers. Application is known to have digest cycle of 3-5k watches. + setIndex = 0; + $timeout(function(){ + init(); + updateTableCellDisplay(columnSets[setIndex]); + },100); + scope.columnsUpdated = false; + } + }); + } + + + scope.getColumnSet = function () { + return columnSets[setIndex]; + }; + + this.updateCellDisplay = function(columnIndex,columnElement){ + if(setIndex === -1 || !scope.retainColumnSet || currentSet.length === 0){ + startDisplayIndex = 0; + endDisplayIndex = defaultNumberOfColumns - 1; + }else{ + startDisplayIndex = currentSet[0]; + endDisplayIndex = currentSet[1]; + } + if((columnIndex >= startDisplayIndex && columnIndex <= endDisplayIndex) || (columnIndex < scope.numOfStickyCols)){ + angular.element(columnElement).css(displayBlockCSS); + }else{ + angular.element(columnElement).css(displayNoneCSS); + } + }; + + function updateTableCellDisplay(set) { + currentSet = set; + for (var i = scope.numOfStickyCols; i < tableColumns.length; i++) { + angular.element(tableColumns[i]).css(displayNoneCSS); + } + + for (var i = set[0]; i <= set[1]; i++) { + angular.element(tableColumns[i]).css(displayBlockCSS); + } + } + + function checkScrollArrows() { + scope.disableLeft = (setIndex === 0); + scope.disableRight = !(setIndex < columnSets.length-1); + } + + scope.moveViewportLeft = function () { + setIndex--; + updateTableCellDisplay(columnSets[setIndex]); + checkScrollArrows(); + if (scope.disableLeft) { + elem[0].querySelector('.b2b-horizontal-table-column-info').focus(); + } + }; + + scope.moveViewportRight = function () { + setIndex++; + updateTableCellDisplay(columnSets[setIndex]); + checkScrollArrows(); + if (scope.disableRight) { + elem[0].querySelector('.b2b-horizontal-table-column-info').focus(); + } + }; + }], + link: function (scope, element, attrs, ctrl) { + + } + }; + }]) + .directive('b2bTableColumnToggler', [function () { + return { + restrict: 'A', + require: '^b2bHorizontalTable', + link: function (scope, element, attrs, ctrl) { + ctrl.updateCellDisplay(scope.$eval(attrs.b2bTableColumnToggler),element); + } + }; + }]); +/** + * @ngdoc directive + * @name Forms.att:hourPicker + * + * @description + * + * + * @usage + *
    + + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.hourPicker', ['b2b.att.utilities']) + +.constant('b2bHourpickerConfig', { + dayOptions: [{ + title: 'sunday', + caption: 'Sun', + label: 'S', + disabled: false + }, { + title: 'monday', + caption: 'Mon', + label: 'M', + disabled: false + }, { + title: 'tuesday', + caption: 'Tues', + label: 'T', + disabled: false + }, { + title: 'wednesday', + caption: 'Wed', + label: 'W', + disabled: false + }, { + title: 'thursday', + caption: 'Thu', + label: 'T', + disabled: false + }, { + title: 'friday', + caption: 'Fri', + label: 'F', + disabled: false + }, { + title: 'saturday', + caption: 'Sat', + label: 'S', + disabled: false + }], + startTimeOptions: ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00'], + startTimeDefaultOptionIndex: -1, + startTimeDefaultMeridiem: "am", + endTimeOptions: ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00'], + endTimeDefaultOptionIndex: -1, + endTimeDefaultMeridiem: "pm", + sameDayOption: true +}) + +.factory('b2bNormalizeHourpickerValues', [function () { + var _normalize = function (hourpickerValues) { + if (angular.isDefined(hourpickerValues) && hourpickerValues != null) { + var finalHourpickerValues = []; + var hourpickerValue = {}; + var days = {}; + for (var i = 0; i < hourpickerValues.length; i++) { + days = hourpickerValues[i].days ? hourpickerValues[i].days : {}; + hourpickerValue.startTime = hourpickerValues[i].startTime ? hourpickerValues[i].startTime : ''; + hourpickerValue.startMeridiem = hourpickerValues[i].startMeridiem ? hourpickerValues[i].startMeridiem : ''; + hourpickerValue.endTime = hourpickerValues[i].endTime ? hourpickerValues[i].endTime : ''; + hourpickerValue.endMeridiem = hourpickerValues[i].endMeridiem ? hourpickerValues[i].endMeridiem : ''; + hourpickerValue.days = []; + + var retrieveDaysText = function (daysDetails) { + var daysTexts = []; + var first = -1; + var last = -1; + var index = -1; + for (var i in days) { + if (days[i].value) { + daysTexts.push(i); + } + } + + first = daysTexts[0]; + last = daysTexts[0]; + index = 0; + hourpickerValue.days[index] = days[first].caption; + if (daysTexts.length > 1) { + for (var i = 1; i < daysTexts.length; i++) { + if (daysTexts[i] - last === 1) { + last = daysTexts[i]; + hourpickerValue.days[index] = days[first].caption + ' - ' + days[last].caption; + } else { + index++; + first = last = daysTexts[i]; + hourpickerValue.days[index] = days[first].caption; + } + } + } + }; + retrieveDaysText(); + + finalHourpickerValues.push(angular.copy(hourpickerValue)); + } + + return angular.copy(finalHourpickerValues); + } + }; + + return { + normalize: _normalize + }; +}]) + +.directive('b2bHourpicker', ['b2bHourpickerConfig', 'b2bNormalizeHourpickerValues', function (b2bHourpickerConfig, b2bNormalizeHourpickerValues) { + return { + restrict: 'EA', + replace: false, + scope: true, + require: 'ngModel', + templateUrl: 'b2bTemplate/hourPicker/b2bHourpicker.html', + controller: ['$scope', function (scope) { + + }], + link: function (scope, elem, attr, ctrl) { + scope.hourpicker = {}; + scope.hourpicker.dayOptions = attr.dayOptions ? scope.$parent.$eval(attr.dayOptions) : b2bHourpickerConfig.dayOptions; + scope.hourpicker.startTimeOptions = attr.startTimeOptions ? scope.$parent.$eval(attr.startTimeOptions) : b2bHourpickerConfig.startTimeOptions; + scope.hourpicker.endTimeOptions = attr.endTimeOptions ? scope.$parent.$eval(attr.endTimeOptions) : b2bHourpickerConfig.endTimeOptions; + scope.hourpicker.startTimeDefaultOptionIndex = attr.startTimeDefaultOptionIndex ? scope.$parent.$eval(attr.startTimeDefaultOptionIndex) : b2bHourpickerConfig.startTimeDefaultOptionIndex; + scope.hourpicker.endTimeDefaultOptionIndex = attr.endTimeDefaultOptionIndex ? scope.$parent.$eval(attr.endTimeDefaultOptionIndex) : b2bHourpickerConfig.endTimeDefaultOptionIndex; + scope.hourpicker.startTimeDefaultMeridiem = attr.startTimeDefaultMeridiem ? scope.$parent.$eval(attr.startTimeDefaultMeridiem) : b2bHourpickerConfig.startTimeDefaultMeridiem; + scope.hourpicker.endTimeDefaultMeridiem = attr.endTimeDefaultMeridiem ? scope.$parent.$eval(attr.endTimeDefaultMeridiem) : b2bHourpickerConfig.endTimeDefaultMeridiem; + scope.hourpicker.sameDayOption = attr.sameDayOption ? scope.$parent.$eval(attr.sameDayOption) : b2bHourpickerConfig.sameDayOption; + scope.hourpicker.editMode = -1; + + scope.hourpickerValues = []; + scope.finalHourpickerValues = []; + scope.addHourpickerValue = function (hourpickerPanelValue) { + if (hourpickerPanelValue) { + if (scope.hourpicker.editMode > -1) { + scope.hourpickerValues[scope.hourpicker.editMode] = hourpickerPanelValue; + scope.hourpicker.editMode = -1; + } else { + scope.hourpickerValues.push(hourpickerPanelValue); + } + } + scope.finalHourpickerValues = b2bNormalizeHourpickerValues.normalize(angular.copy(scope.hourpickerValues)); + ctrl.$setViewValue(angular.copy(scope.hourpickerValues)); + }; + ctrl.$render = function () { + if (angular.isDefined(ctrl.$modelValue)) { + scope.hourpickerValues = angular.copy(ctrl.$modelValue); + scope.finalHourpickerValues = b2bNormalizeHourpickerValues.normalize(angular.copy(scope.hourpickerValues)); + } + }; + scope.editHourpickerValue = function (index) { + scope.hourpickerPanelValue = angular.copy(scope.hourpickerValues[index]); + scope.hourpicker.editMode = index; + }; + scope.deleteHourpickerValue = function (index) { + scope.hourpickerValues.splice(index, 1); + scope.resetHourpickerPanelValue(); + scope.addHourpickerValue(); + }; + + scope.setValidity = function (errorType, errorValue) { + ctrl.$setValidity(errorType, errorValue); + } + } + } +}]) + +.directive('b2bHourpickerPanel', [function () { + return { + restrict: 'EA', + replace: false, + templateUrl: 'b2bTemplate/hourPicker/b2bHourpickerPanel.html', + controller: ['$scope', function (scope) { + + }], + link: function (scope, elem, attr, ctrl) { + var hourpickerPanelValueTemplate = { + days: {}, + startTime: '', + startMeridiem: 'am', + endTime: '', + endMeridiem: 'pm' + }; + for (var i = 0; i < scope.hourpicker.dayOptions.length; i++) { + hourpickerPanelValueTemplate.days[i] = { + value: false, + title: scope.hourpicker.dayOptions[i].title, + caption: scope.hourpicker.dayOptions[i].caption + }; + } + scope.hourpickerPanelValue = {}; + scope.disableAddBtn = true; + + scope.$watch('hourpickerPanelValue.days', function(){ + for(var i in scope.hourpickerPanelValue.days) + { + if(scope.hourpickerPanelValue.days[i].value) + { + scope.disableAddBtn = false; + break; + } + scope.disableAddBtn = true; + } + }, true); + + scope.resetHourpickerPanelValue = function () { + scope.hourpickerPanelValue = angular.copy(hourpickerPanelValueTemplate); + if (scope.hourpicker.startTimeDefaultOptionIndex > -1) { + scope.hourpickerPanelValue.startTime = scope.hourpicker.startTimeOptions[scope.hourpicker.startTimeDefaultOptionIndex]; + } + if (scope.hourpicker.endTimeDefaultOptionIndex > -1) { + scope.hourpickerPanelValue.endTime = scope.hourpicker.endTimeOptions[scope.hourpicker.endTimeDefaultOptionIndex]; + } + scope.hourpickerPanelValue.startMeridiem = scope.hourpicker.startTimeDefaultMeridiem; + scope.hourpickerPanelValue.endMeridiem = scope.hourpicker.endTimeDefaultMeridiem; + scope.hourpicker.editMode = -1; + scope.setValidity('invalidHourpickerData', true); + scope.setValidity('invalidHourpickerTimeRange', true); + }; + scope.resetHourpickerPanelValue(); + scope.updateHourpickerValue = function () { + if (scope.isFormValid() && !scope.isTimeOverlap()) { + scope.addHourpickerValue(angular.copy(scope.hourpickerPanelValue)); + scope.resetHourpickerPanelValue(); + } + }; + + scope.isFormValid = function () { + var isStartTimeAvailable = scope.hourpickerPanelValue.startTime ? true : false; + var isStartMeridiemAvailable = scope.hourpickerPanelValue.startMeridiem ? true : false; + var isEndTimeAvailable = scope.hourpickerPanelValue.endTime ? true : false; + var isEndMeridiemAvailable = scope.hourpickerPanelValue.endMeridiem ? true : false; + var currentStartTime = getTime(scope.hourpickerPanelValue.startTime, scope.hourpickerPanelValue.startMeridiem); + var currentEndTime = getTime(scope.hourpickerPanelValue.endTime, scope.hourpickerPanelValue.endMeridiem); + var isTimeInProperSequence = currentEndTime > currentStartTime; + var isDayChecked = false; + for (var i in scope.hourpickerPanelValue.days) { + if (scope.hourpickerPanelValue.days[i].value) { + isDayChecked = true; + break; + } + } + + if (isStartTimeAvailable && isStartMeridiemAvailable && isEndTimeAvailable && isEndMeridiemAvailable && isTimeInProperSequence && isDayChecked) { + scope.setValidity('invalidHourpickerData', true); + return true; + } else { + scope.setValidity('invalidHourpickerData', false); + return false; + } + }; + scope.isTimeOverlap = function () { + var selectedDays = []; + for (var i in scope.hourpickerPanelValue.days) { + if (scope.hourpickerPanelValue.days[i].value) { + selectedDays.push(i); + } + } + + var currentStartTime, currentEndTime, existingStartTime, existingEndTime; + currentStartTime = getTime(scope.hourpickerPanelValue.startTime, scope.hourpickerPanelValue.startMeridiem); + currentEndTime = getTime(scope.hourpickerPanelValue.endTime, scope.hourpickerPanelValue.endMeridiem); + for (var i = 0; i < scope.hourpickerValues.length; i++) { + + if (i === scope.hourpicker.editMode) { + continue; + } + + for (var j = 0; j < selectedDays.length; j++) { + existingStartTime = getTime(scope.hourpickerValues[i].startTime, scope.hourpickerValues[i].startMeridiem); + existingEndTime = getTime(scope.hourpickerValues[i].endTime, scope.hourpickerValues[i].endMeridiem); + if (scope.hourpickerValues[i].days[selectedDays[j]].value) { + if(!scope.hourpicker.sameDayOption){ + scope.setValidity('dayAlreadySelected', false); + return true; + } else if ((currentStartTime > existingStartTime && currentStartTime < existingEndTime) || (currentEndTime > existingStartTime && currentEndTime < existingEndTime)) { + scope.setValidity('invalidHourpickerTimeRange', false); + return true; + } else if ((existingStartTime > currentStartTime && existingStartTime < currentEndTime) || (existingEndTime > currentStartTime && existingEndTime < currentEndTime)) { + scope.setValidity('invalidHourpickerTimeRange', false); + return true; + } else if ((currentStartTime === existingStartTime) && (currentEndTime === existingEndTime)) { + scope.setValidity('invalidHourpickerTimeRange', false); + return true; + } + } + } + } + + scope.setValidity('dayAlreadySelected', true); + scope.setValidity('invalidHourpickerTimeRange', true); + return false; + }; + var getTime = function (timeString, meridiem) { + var tempDate = new Date(); + if (timeString && meridiem) { + var timeSplit = timeString.split(':'); + var hour = ((meridiem === 'PM' || meridiem === 'pm') && timeSplit[0] !== '12') ? parseInt(timeSplit[0], 10) + 12 : parseInt(timeSplit[0], 10); + tempDate.setHours(hour, parseInt(timeSplit[1], 10), 0, 0); + } + + return tempDate.getTime(); + }; + } + } +}]) + +.directive('b2bHourpickerValue', [function () { + return { + restrict: 'EA', + replace: false, + templateUrl: 'b2bTemplate/hourPicker/b2bHourpickerValue.html', + controller: ['$scope', function (scope) { + + }], + link: function (scope, elem, attr, ctrl) { + scope.hourpickerValue = {}; + scope.hourpickerValue.startTime = attr.startTime ? scope.$eval(attr.startTime) : ''; + scope.hourpickerValue.startMeridiem = attr.startMeridiem ? scope.$eval(attr.startMeridiem) : ''; + scope.hourpickerValue.endTime = attr.endTime ? scope.$eval(attr.endTime) : ''; + scope.hourpickerValue.endMeridiem = attr.endMeridiem ? scope.$eval(attr.endMeridiem) : ''; + scope.hourpickerValue.days = attr.days ? scope.$eval(attr.days).join(', ') : ''; + scope.hourpickerValue.index = attr.b2bHourpickerValue ? scope.$eval(attr.b2bHourpickerValue) : -1; + } + } +}]); +/** + * @ngdoc directive + * @name Template.att:inputTemplate + * + * @description + * + * + * @usage + * + * + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.inputTemplate', []); + +/** + * @ngdoc directive + * @name Navigation.att:leftNavigation + * + * @description + * + * + * @usage + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.leftNavigation', []) + .directive('b2bLeftNavigation', [function () { + return { + restrict: 'EA', + templateUrl: 'b2bTemplate/leftNavigation/leftNavigation.html', + scope: { + menuData: '=' + }, + link: function (scope, element, attrs, ctrl) { + scope.idx = -1; + scope.itemIdx = -1; + scope.navIdx = -1; + scope.toggleNav = function (val) { + if (val === scope.idx) { + scope.idx = -1; + return; + } + scope.idx = val; + }; + scope.liveLink = function (evt, val1, val2) { + scope.itemIdx = val1; + scope.navIdx = val2; + evt.stopPropagation(); + }; + } + }; + }]); +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:links + * + * @description + * + * @usage + * + * + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.links', []); +/** + * @ngdoc directive + * @name Misc.att:listbox + * + * @description + * + * + * @param {int} currentIndex - Current index of selected listbox item. Is not supported on multiselect listbox + * @param {Array} listboxData - Data of listbox items. Should include full data regardless if HTML will be filtered. + + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.listbox', ['b2b.att.utilities']) +.directive('b2bListBox', ['keymap', 'b2bDOMHelper', '$rootScope', function(keymap, b2bDOMHelper, $rootScope) { + return { + restrict: 'AE', + transclude: true, + replace: true, + scope: { + currentIndex: '=', + listboxData: '=' + }, + templateUrl: 'b2bTemplate/listbox/listbox.html', + link: function(scope, elem, attr) { + + if (attr.ariaMultiselectable !== undefined || attr.ariaMultiselectable === 'true') { + scope.multiselectable = true; + } else { + scope.multiselectable = false; + } + + var shiftKey = false; + var elements = []; + var prevDirection = undefined; // previous direction is used for an edge case when shifting + var shiftKeyPressed = false; // Used to handle shift clicking + var ctrlKeyPressed = false; + + var currentIndexSet = { + 'elementIndex': 0, + 'listboxDataIndex': 0 + }; + + function isTrue(item) { + if (item.selected === true) { + return true; + } + } + + function incrementIndex(elem) { + $rootScope.$apply(); + + var nextElem = elem.next(); + if (!angular.isDefined(nextElem) || nextElem.length === 0) { + return; + } + + currentIndexSet.elementIndex += 1; + currentIndexSet.listboxDataIndex = parseInt(nextElem.attr('data-index'), 10); + scope.currentIndex = currentIndexSet.listboxDataIndex; + + if (currentIndexSet.elementIndex >= elements.length - 1) { + currentIndexSet.elementIndex = elements.length-1; + } + } + + function decrementIndex(elem) { + $rootScope.$apply(); + var prevElem = angular.element(b2bDOMHelper.previousElement(elem)); + if (!angular.isDefined(prevElem) || prevElem.length === 0) { + return; + } + + currentIndexSet.elementIndex -= 1; + currentIndexSet.listboxDataIndex = parseInt(prevElem.attr('data-index'), 10); + scope.currentIndex = currentIndexSet.listboxDataIndex; + + if (currentIndexSet.elementIndex <= 0) { + currentIndexSet.elementIndex = 0; + } + } + + var focusOnElement = function(index) { + try { + elements[index].focus(); + } catch (e) {}; + } + + function selectItems(startIndex, endIndex, forceValue) { + for (var i = startIndex; i < endIndex; i++) { + if (forceValue === undefined) { + // We will flip the value + scope.listboxData[i].selected = !scope.listboxData[i].selected; + } else { + scope.listboxData[i].selected = forceValue; + } + } + + if (!scope.$$phase) { + scope.$apply(); + } + } + + elem.bind('focus', function(evt) { + // If multiselectable or not and nothing is selected, put focus on first element + // If multiselectable and a range is set, put focus on first element of range + // If not multiselectable and something selected, put focus on element + elements = elem.children(); + var selectedItems = scope.listboxData.filter(isTrue); + var elementsIndies = Array.prototype.map.call(elements, function(item) { + return parseInt(angular.element(item).attr('data-index'), 10); + }); + + if (selectedItems.length == 0) { + focusOnElement(0); + currentIndexSet.listboxDataIndex = 0; + } else if (attr.ariaMultiselectable) { + var index = scope.listboxData.indexOf(selectedItems[0]); + var indies = elementsIndies.filter(function(item) { + return (item === index); + }); + + if (indies.length === 0 || indies[0] != index) { + // Set focused on 0 + currentIndexSet.elementIndex = elementsIndies[0]; + currentIndexSet.listboxDataIndex = 0; + focusOnElement(currentIndexSet.elementIndex); + } else { + focusOnElement(indies[0]); + currentIndexSet.elementIndex = indies[0]; + currentIndexSet.listboxDataIndex = index; + } + } else { + focusOnElement(currentIndexSet.elementIndex); + } + scope.currentIndex = currentIndexSet.listboxDataIndex; + + if (!scope.$$phase) { + scope.$apply(); + } + }); + elem.bind('keyup', function(evt) { + if (evt.keyCode === keymap.KEY.SHIFT) { + shiftKeyPressed = false; + } else if (evt.keyCode === keymap.KEY.CTRL) { + ctrlKeyPressed = false; + } + }); + + elem.bind('keydown', function(evt) { + var keyCode = evt.keyCode; + elements = elem.children(); + if (keyCode === keymap.KEY.SHIFT) { + shiftKeyPressed = true; + } else if (evt.keyCode === keymap.KEY.CTRL) { + ctrlKeyPressed = true; + } + + switch(keyCode) { + case 65: // A key + { + if (scope.multiselectable && evt.ctrlKey) { + var arr = scope.listboxData.filter(isTrue); + var elementsIndies = Array.prototype.map.call(elements, function(item) { + return parseInt(angular.element(item).attr('data-index'), 10); + }); + var val = !(arr.length === scope.listboxData.length); + for (var i = 0; i < elementsIndies.length; i++) { + scope.listboxData[elementsIndies[i]].selected = val; + } + + if (!scope.$$phase) { + scope.$apply(); + } + + evt.preventDefault(); + evt.stopPropagation(); + } + break; + } + case keymap.KEY.END: + { + if (scope.multiselectable && evt.ctrlKey && evt.shiftKey) { + var elementsIndies = Array.prototype.map.call(elements, function(item) { + return parseInt(angular.element(item).attr('data-index'), 10); + }).filter(function(item) { + return (item >= currentIndexSet.listboxDataIndex); + }); + for (var i = 0; i < elementsIndies.length; i++) { + scope.listboxData[elementsIndies[i]].selected = true; + } + evt.preventDefault(); + evt.stopPropagation(); + + if (!scope.$$phase) { + scope.$apply(); + } + } + break; + } + case keymap.KEY.HOME: + { + if (scope.multiselectable && evt.ctrlKey && evt.shiftKey) { + selectItems(0, currentIndexSet.listboxDataIndex+1, true); // currentIndex+1 is what is being focused on + evt.preventDefault(); + evt.stopPropagation(); + } + break; + } + case keymap.KEY.LEFT: + case keymap.KEY.UP: + { + if (currentIndexSet.listboxDataIndex === 0) { + evt.preventDefault(); + evt.stopPropagation(); + return; + } + + decrementIndex(elements.eq(currentIndexSet.elementIndex)); + if (scope.multiselectable && (evt.shiftKey || evt.ctrlKey)) { + if (evt.shiftKey) { + if (prevDirection === 'DOWN') { + scope.listboxData[currentIndexSet.listboxDataIndex+1].selected = !scope.listboxData[currentIndexSet.listboxDataIndex+1].selected; + } + scope.listboxData[currentIndexSet.listboxDataIndex].selected = !scope.listboxData[currentIndexSet.listboxDataIndex].selected; + } + prevDirection = 'UP'; + } else { + // If no modifier keys are selected, all other items need to be unselected. + prevDirection = undefined; + selectItems(0, scope.listboxData.length, false); + if(currentIndexSet.listboxDataIndex !== undefined && !isNaN(currentIndexSet.listboxDataIndex)){ + scope.listboxData[currentIndexSet.listboxDataIndex].selected = true; + } + } + focusOnElement(currentIndexSet.elementIndex); + if(!scope.$$phase) { + scope.$apply(); + } + evt.preventDefault(); + evt.stopPropagation(); + break; + } + case keymap.KEY.RIGHT: + case keymap.KEY.DOWN: + { + if (currentIndexSet.listboxDataIndex === scope.listboxData.length-1) { + evt.preventDefault(); + evt.stopPropagation(); + return; + } + + incrementIndex(elements.eq(currentIndexSet.elementIndex)); + + if (scope.multiselectable && (evt.shiftKey || evt.ctrlKey)) { + if (evt.shiftKey) { + if (prevDirection === 'UP') { + scope.listboxData[currentIndexSet.listboxDataIndex-1].selected = !scope.listboxData[currentIndexSet.listboxDataIndex-1].selected; + } + + scope.listboxData[currentIndexSet.listboxDataIndex].selected = !scope.listboxData[currentIndexSet.listboxDataIndex].selected; + } + prevDirection = 'DOWN'; + } else { + // If no modifier keys are selected, all other items need to be unselected. + prevDirection = undefined; + selectItems(0, scope.listboxData.length, false); + if(currentIndexSet.listboxDataIndex !== undefined && !isNaN(currentIndexSet.listboxDataIndex)){ + scope.listboxData[currentIndexSet.listboxDataIndex].selected = true; + } + } + + focusOnElement(currentIndexSet.elementIndex); + if(!scope.$$phase) { + scope.$apply(); + } + evt.preventDefault(); + evt.stopPropagation(); + break; + } + case keymap.KEY.TAB: + if(evt.shiftKey) { + var previousElement = b2bDOMHelper.previousElement(elem.parent().parent(), true); + evt.preventDefault(); + previousElement.focus(); + } + break; + default: + break; + } + }); + + elem.bind('click', function(evt) { + var index = parseInt(evt.target.dataset.index, 10); + if (index === undefined || isNaN(index)) { + return; + } + if (scope.multiselectable && currentIndexSet.listboxDataIndex !== undefined) { + if (shiftKeyPressed) { + var min = Math.min(index, currentIndexSet.listboxDataIndex); + var max = Math.max(index, currentIndexSet.listboxDataIndex); + + if (index === min) { // clicking up + var firstIndex = scope.listboxData.some(function(item) { return item.selected == true; }); + // Given the firstIndex, let's find the matching element to get proper element match + elements = elem.children(); + elements.eq(firstIndex) + var elementsThatMatch = Array.prototype.filter.call(elements, function(item) { + if (parseInt(angular.element(item).attr('data-index'), 10) === firstIndex) { + return true; + } + }); + firstIndex = parseInt(angular.element(elementsThatMatch).attr('data-index'), 10); + + if (index <= firstIndex && scope.listboxData.filter(isTrue).length > 1) { + // Break the selection into 2 + selectItems(firstIndex + 1, max + 1, undefined); // + 1 needed because selectItems only selects up to MAX + selectItems(min, firstIndex, undefined); + } else if (scope.listboxData.filter(isTrue).length == 1){ + selectItems(min, max, undefined); + } else { + selectItems(min + 1, max + 1, undefined); + } + } else { // clicking down + selectItems(min + 1, max + 1, scope.listboxData[min].selected); + } + } else if (ctrlKeyPressed) { + scope.listboxData[index].selected = !scope.listboxData[index].selected; + } else { + selectItems(0, scope.listboxData.length, false); + scope.listboxData[index].selected = !scope.listboxData[index].selected; + } + } else { + selectItems(0, scope.listboxData.length, false); + scope.listboxData[index].selected = !scope.listboxData[index].selected; + } + currentIndexSet.elementIndex = index; + currentIndexSet.listboxDataIndex = index; + scope.currentIndex = currentIndexSet.listboxDataIndex; + if (!scope.$$phase) { + scope.$apply(); + } + focusOnElement(index); + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Videos, audio & animation.att:loaderAnimation + * + * @description + * + * + * @usage + * + * Angular library uses Global.css's icon-spinner. + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.loaderAnimation', []) + .constant('b2bSpinnerConfig', { + loadingText: 'Loading...', + startEvent: 'startButtonSpinner', + stopEvent: 'stopButtonSpinner' + }) + .constant("progressTrackerConfig", { + loadingText: 'Loading...', + minDuration: "", + activationDelay: "", + minDurationPromise: "", + activationDelayPromise: "" + }) + +.provider('progressTracker', function () { + this.$get = ['$q', '$timeout', function ($q, $timeout) { + function cancelTimeout(promise) { + if (promise) { + $timeout.cancel(promise); + } + } + return function ProgressTracker(options) { + //do new if user doesn't + if (!(this instanceof ProgressTracker)) { + return new ProgressTracker(options); + } + + options = options || {}; + //Array of promises being tracked + var tracked = []; + var self = this; + //Allow an optional "minimum duration" that the tracker has to stay active for. + var minDuration = options.minDuration; + //Allow a delay that will stop the tracker from activating until that time is reached + var activationDelay = options.activationDelay; + var minDurationPromise; + var activationDelayPromise; + self.active = function () { + //Even if we have a promise in our tracker, we aren't active until delay is elapsed + if (activationDelayPromise) { + return false; + } + return tracked.length > 0; + }; + self.tracking = function () { + //Even if we aren't active, we could still have a promise in our tracker + return tracked.length > 0; + }; + self.destroy = self.cancel = function () { + minDurationPromise = cancelTimeout(minDurationPromise); + activationDelayPromise = cancelTimeout(activationDelayPromise); + for (var i = tracked.length - 1; i >= 0; i--) { + tracked[i].resolve(); + } + tracked.length = 0; + }; + //Create a promise that will make our tracker active until it is resolved. + // @return deferred - our deferred object that is being tracked + self.createPromise = function () { + var deferred = $q.defer(); + tracked.push(deferred); + //If the tracker was just inactive and this the first in the list of promises, we reset our delay and minDuration again. + if (tracked.length === 1) { + if (activationDelay) { + activationDelayPromise = $timeout(function () { + activationDelayPromise = cancelTimeout(activationDelayPromise); + startMinDuration(); + }, activationDelay); + } else { + startMinDuration(); + } + } + deferred.promise.then(onDone(false), onDone(true)); + return deferred; + + function startMinDuration() { + if (minDuration) { + minDurationPromise = $timeout(angular.noop, minDuration); + } + } + //Create a callback for when this promise is done. It will remove our tracked promise from the array if once minDuration is complete + function onDone() { + return function () { + (minDurationPromise || $q.when()).then(function () { + var index = tracked.indexOf(deferred); + tracked.splice(index, 1); + //If this is the last promise, cleanup the timeouts for activationDelay + if (tracked.length === 0) { + activationDelayPromise = cancelTimeout(activationDelayPromise); + } + }); + }; + } + }; + self.addPromise = function (promise) { + +// we cannot assign then function in other var and then add the resolve and reject + var thenFxn = promise && (promise.then || promise.$then || (promise.$promise && promise.$promise.then)); + if (!thenFxn) { + throw new Error("progressTracker expects a promise object :: Not found"); + } + var deferred = self.createPromise(); + //When given promise is done, resolve our created promise + //Allow $then for angular-resource objects + + promise.then(function (value) { + deferred.resolve(value); + return value; + }, function (value) { + deferred.reject(value); + return $q.reject(value); + } + ); + return deferred; + }; + }; + }]; +}) + +.config(['$httpProvider', function ($httpProvider) { + $httpProvider.interceptors.push(['$q', 'progressTracker', function ($q) { + return { + request: function (config) { + if (config.tracker) { + if (!angular.isArray(config.tracker)) { + config.tracker = [config.tracker]; + } + config.$promiseTrackerDeferred = config.$promiseTrackerDeferred || []; + + angular.forEach(config.tracker, function (tracker) { + var deferred = tracker.createPromise(); + config.$promiseTrackerDeferred.push(deferred); + }); + } + return $q.when(config); + }, + response: function (response) { + if (response.config && response.config.$promiseTrackerDeferred) { + angular.forEach(response.config.$promiseTrackerDeferred, function (deferred) { + deferred.resolve(response); + }); + } + return $q.when(response); + }, + responseError: function (response) { + if (response.config && response.config.$promiseTrackerDeferred) { + angular.forEach(response.config.$promiseTrackerDeferred, function (deferred) { + deferred.reject(response); + }); + } + return $q.reject(response); + } + }; + }]); +}]) + +.directive('b2bClickSpin', ['$timeout', '$parse', '$rootScope', 'progressTracker', function ($timeout, $parse, $rootScope, progressTracker) { + return { + restrict: 'A', + link: function (scope, elm, attrs) { + var fn = $parse(attrs.b2bClickSpin); + elm.on('click', function (event) { + var promise = $timeout(function () {console.log("inside Promise")}, 5000); + scope.$apply(function () { + fn(scope, { + $event: event + }); + }); + //comment this line if not running unit test + $rootScope.loadingTracker = progressTracker({ + minDuration: 750 + }); + $rootScope.loadingTracker.addPromise(promise); + angular.forEach("$routeChangeSuccess $viewContentLoaded $locationChangeSuccess".split(" "), function (event) { + $rootScope.$on(event, function () { + + $timeout.cancel(promise); + }); + }); + }); + } + }; +}]) + +.directive('b2bProgressTracker', ['progressTrackerConfig', function (ptc) { + return { + restrict: 'EA', + replace: true, + template: '
    '+ ptc.loadingText+'
    ' + }; +}]) + +.directive('b2bLoadButton', ['b2bSpinnerConfig', '$timeout', function (spinnerConfig, $timeout) { + var spinButton = function (state, element, data) { + + var attr = element.html() ? 'html' : 'val'; + state = state + 'Text'; + if (state === 'loadingText') { + element[attr](data[state]); + element.attr("disabled",'disabled'); + element.addClass('disabled'); + } else if (state === 'resetText') { + element[attr](data[state]); + element.removeAttr("disabled"); + element.removeClass('disabled'); + } + }; + + return { + restrict: 'A', + replace: false, + scope: { + promise: '=promise', + startEvent: '@startEvent', + stopEvent: '@stopEvent' + }, + link: function (scope, element, attr) { + var validAttr = element.html() ? 'html' : 'val'; + var data = { + loadingText: '', + resetText: '' + }; + + var updateLoadingText = function (val) { + var loadingText = val; + if (!angular.isDefined(loadingText) || loadingText === "") { + loadingText = spinnerConfig.loadingText; + } + data.loadingText = validAttr === 'html' ? "" + loadingText : loadingText; + }; + var updateResetText = function (val) { + data.resetText = val; + }; + + attr.$observe('b2bLoadButton', function (val) { + updateLoadingText(val); + }); + $timeout(function () { + updateResetText(element[validAttr]()); + }, 500); + + if (!angular.isDefined(scope.startEvent) || scope.startEvent === "") { + scope.startEvent = spinnerConfig.startEvent; + } + + if (!angular.isDefined(scope.stopEvent) || scope.stopEvent === "") { + scope.stopEvent = spinnerConfig.stopEvent; + } + + scope.$watch('promise', function () { + if (angular.isDefined(scope.promise) && angular.isFunction(scope.promise.then)) { + spinButton('loading', element, data); + scope.promise.then(function () { + spinButton('reset', element, data); + }, function () { + spinButton('reset', element, data); + }); + } + }); + + scope.$on(scope.startEvent, function () { + spinButton('loading', element, data); + scope.$on(scope.stopEvent, function () { + spinButton('reset', element, data); + }); + }); + } + }; +}]); + /** + * @ngdoc directive + * @name Misc.att:messageWrapper + * @scope + * @param {boolean} trigger - A boolean that triggers directive to switch focus + * @param {integer} delay - Extra delay added to trigger code to allow for DOM to be ready. Default is 10ms. + * @param {string} noFocus - Attribute-based API to trigger whether first focusable element receives focus on trigger or whole message (assumes tabindex="-1" set on first child) + * @param {string} trapFocus - Attribute-based API to trap focus within the message. This should be enabled by default on all toast messages. + * @description + * + * @usage + * Code that contains at least one focusable element and will be shown/hidden on some logic. This must have tabindex="-1". + * + * @example + *
    + HTML + AngularJS + + + + +
    + * + */ +angular.module('b2b.att.messageWrapper', ['b2b.att.utilities']) +.directive('b2bMessageWrapper', ['b2bDOMHelper', '$compile', '$timeout', '$log', function(b2bDOMHelper, $compile, $timeout, $log) { + return { + restrict: 'AE', + scope: { + trigger: '=', + delay: '=?' + }, + transclude: true, + replace: true, + template: '
    ', + link: function(scope, elem, attrs) { + scope.delay = scope.delay || 10; + + if (attrs.trapFocus != undefined && !elem.children().eq(0).attr('b2b-trap-focus-inside-element')) { + // Append b2bTrapFocusInsideElement onto first child and recompile + elem.children().eq(0).attr('b2b-trap-focus-inside-element', 'false'); + elem.children().eq(0).attr('trigger', scope.trigger); + $compile(elem.contents())(scope); + } + + var firstElement = undefined, + launchingElement = undefined; + + scope.$watch('trigger', function(oldVal, newVal) { + if (oldVal === newVal) return; + if (!angular.isDefined(launchingElement)) { + launchingElement = document.activeElement; + } + $timeout(function() { + if (scope.trigger) { + + if (attrs.noFocus === true || attrs.noFocus === "") { + elem.children()[0].focus(); + } else { + firstElement = b2bDOMHelper.firstTabableElement(elem); + + if (angular.isDefined(firstElement)) { + firstElement.focus(); + } + } + + } else { + if (angular.isDefined(launchingElement) && launchingElement.nodeName !== 'BODY') { + if (launchingElement === document.activeElement) { + return; + } + + if (b2bDOMHelper.isInDOM(launchingElement) && b2bDOMHelper.isTabable(launchingElement)) { + // At this point, launchingElement is still a valid element, but focus will fail and + // activeElement will become body, hence we want to apply custom logic and find previousElement + var prevLaunchingElement = launchingElement; + launchingElement.focus(); + + if (document.activeElement !== launchingElement || document.activeElement.nodeName === 'BODY') { + launchingElement = b2bDOMHelper.previousElement(angular.element(prevLaunchingElement), true); + launchingElement.focus(); + } + } else { + launchingElement = b2bDOMHelper.previousElement(launchingElement, true); + launchingElement.focus(); + } + } + } + }, scope.delay); + }); + } + }; +}]); +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:modalsAndAlerts + * + * @description + * + * + * @usage + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.modalsAndAlerts', ['b2b.att.position', 'b2b.att.transition', 'b2b.att.utilities']) + +/** + * A helper, internal data structure that acts as a map but also allows getting / removing + * elements in the LIFO order + */ +.factory('$$stackedMap', function () { + return { + createNew: function () { + var stack = []; + + return { + add: function (key, value) { + stack.push({ + key: key, + value: value + }); + }, + get: function (key) { + for (var i = 0; i < stack.length; i++) { + if (key === stack[i].key) { + return stack[i]; + } + } + }, + keys: function () { + var keys = []; + for (var i = 0; i < stack.length; i++) { + keys.push(stack[i].key); + } + return keys; + }, + top: function () { + return stack[stack.length - 1]; + }, + remove: function (key) { + var idx = -1; + for (var i = 0; i < stack.length; i++) { + if (key === stack[i].key) { + idx = i; + break; + } + } + return stack.splice(idx, 1)[0]; + }, + removeTop: function () { + return stack.splice(stack.length - 1, 1)[0]; + }, + length: function () { + return stack.length; + } + }; + } + }; +}).factory('trapFocusInElement', ['$document', '$isElement', 'b2bDOMHelper', 'keymap', function ($document, $isElement, b2bDOMHelper, keymap) { + var elementStack = []; + var stackHead = undefined; + var firstTabableElement, lastTabableElement; + + var trapKeyboardFocusInFirstElement = function (e) { + if (!e.keyCode) { + e.keyCode = e.which; + } + + if (e.shiftKey === true && e.keyCode === keymap.KEY.TAB) { + lastTabableElement[0].focus(); + e.preventDefault(e); + e.stopPropagation(e); + } + + }; + + var trapKeyboardFocusInLastElement = function (e) { + if (!e.keyCode) { + e.keyCode = e.which; + } + + if (e.shiftKey === false && e.keyCode === keymap.KEY.TAB) { + firstTabableElement[0].focus(); + e.preventDefault(e); + e.stopPropagation(e); + } + }; + + var trapFocusInElement = function (flag, firstTabableElementParam, lastTabableElementParam) { + var bodyElements = $document.find('body').children(); + + firstTabableElement = firstTabableElementParam ? firstTabableElementParam : angular.element(b2bDOMHelper.firstTabableElement(stackHead)); + lastTabableElement = lastTabableElementParam ? lastTabableElementParam : angular.element(b2bDOMHelper.lastTabableElement(stackHead)); + + if (flag) { + for (var i = 0; i < bodyElements.length; i++) { + if (bodyElements[i] !== stackHead[0]) { + bodyElements.eq(i).attr('aria-hidden', true); + } + } + firstTabableElement.bind('keydown', trapKeyboardFocusInFirstElement); + lastTabableElement.bind('keydown', trapKeyboardFocusInLastElement); + } else { + for (var j = 0; j < bodyElements.length; j++) { + if (bodyElements[j] !== stackHead[0]) { + bodyElements.eq(j).removeAttr('aria-hidden'); + } + } + firstTabableElement.unbind('keydown', trapKeyboardFocusInFirstElement); + lastTabableElement.unbind('keydown', trapKeyboardFocusInLastElement); + } + }; + var toggleTrapFocusInElement = function (flag, element) { + if (angular.isDefined(flag) && angular.isDefined(element)) { + if (angular.isUndefined(stackHead)) { + stackHead = element; + trapFocusInElement(flag); + } else { + if (flag) { + trapFocusInElement(false); + elementStack.push(stackHead); + stackHead = element; + trapFocusInElement(true); + } else { + if (stackHead.prop('$$hashKey') === element.prop('$$hashKey')) { + trapFocusInElement(false); + stackHead = elementStack.pop(); + if (angular.isDefined(stackHead)) { + trapFocusInElement(true); + } + } + } + } + }else { + if (angular.isDefined(stackHead)) { + trapFocusInElement(false, firstTabableElement, lastTabableElement); + trapFocusInElement(true); + } + } + }; + + return toggleTrapFocusInElement; +}]) + +/** + * A helper directive for the $modal service. It creates a backdrop element. + */ +.directive('b2bModalBackdrop', ['$modalStack', '$timeout', function ($modalStack, $timeout) { + return { + restrict: 'EA', + replace: true, + templateUrl: 'b2bTemplate/modalsAndAlerts/b2b-backdrop.html', + link: function (scope, element, attrs) { + scope.close = function (evt) { + var modal = $modalStack.getTop(); + if (modal && modal.value.backdrop && modal.value.backdrop !== 'static') { + evt.preventDefault(); + evt.stopPropagation(); + $modalStack.dismiss(modal.key, 'backdrop click'); + } + }; + } + }; +}]) + +.directive('b2bModalWindow', ['$timeout', 'windowOrientation', '$window', 'keymap', function ($timeout, windowOrientation, $window, keymap) { + return { + restrict: 'EA', + scope: { + index: '@' + }, + replace: true, + transclude: true, + templateUrl: 'b2bTemplate/modalsAndAlerts/b2b-window.html', + controller: ['$scope', '$element', '$attrs', function (scope, element, attrs) { + scope.windowClass = attrs.windowClass || ''; + scope.sizeClass = attrs.sizeClass || ''; + scope.isNotifDialog = false; + scope.modalClose = attrs.modalClose || false; + + this.setTitle = function (title) { + scope.title = title; + }; + this.setContent = function (content) { + scope.content = content; + scope.isNotifDialog = true; + }; + this.isDockedModal = scope.windowClass.indexOf('modal-docked') > -1; + }], + link: function (scope, element, attrs, ctrl) { + if (ctrl.isDockedModal) { + scope.isModalLandscape = false; + + var window = angular.element($window); + scope.updateCss = function () { + if (windowOrientation.isPotrait()) { // Potrait Mode + scope.isModalLandscape = false; + } else if (windowOrientation.isLandscape()) { // Landscape Mode + scope.isModalLandscape = true; + } + }; + + $timeout(function () { + scope.updateCss(); + scope.$apply(); + }, 100); + window.bind('orientationchange', function () { + scope.updateCss(); + scope.$apply(); + }); + window.bind('resize', function () { + scope.updateCss(); + scope.$apply(); + }); + }else { + angular.element(element[0].querySelectorAll(".b2b-dropdown-desktop-list")).css({ + "max-height": "200px" + }); + } + + var isIE = /msie|trident/i.test(navigator.userAgent); + if (isIE) { + if(angular.element(element[0].querySelector('.corner-button button.close')).length > 0){ + angular.element(element[0].querySelector('.corner-button button.close')).bind('focus', function () { + angular.element(element[0].querySelector('.b2b-modal-header'))[0].scrollLeft = 0; + angular.element(element[0].querySelector('.b2b-modal-header'))[0].scrollTop = 0; + }); + } + } + + if(scope.modalClose){ + element.bind('keydown', function (e) { + if(e.keyCode == keymap.KEY.ESC){ + e.preventDefault(); + e.stopPropagation(); + } + }); + } + } + }; +}]) + +.directive('b2bModalTitle', [function () { + return { + restrict: 'A', + require: '^b2bModalWindow', + link: function (scope, elem, attr, ctrl) { + ctrl.setTitle(attr.id); + } + }; +}]) + +.directive('b2bModalContent', [function () { + return { + restrict: 'A', + require: '^b2bModalWindow', + link: function (scope, elem, attr, ctrl) { + ctrl.setContent(attr.id); + } + }; +}]) + + +.directive('b2bModalBody', ['$timeout', '$position', '$document', '$window', 'windowOrientation', 'b2bAwdBreakpoints', function ($timeout, $position, $document, $window, windowOrientation, b2bAwdBreakpoints) { + return { + restrict: 'AC', + scope: { + index: '@' + }, + require: '^b2bModalWindow', + link: function (scope, element, attrs, ctrl) { + var window = angular.element($window); + var body = $document.find('body').eq(0); + scope.setModalHeight = function () { + var modalHeaderHeight, modalFooterHeight, modalBodyHeight, windowHeight, windowWidth, modalHeight; + modalHeaderHeight = 0; + modalFooterHeight = 0; + windowHeight = $window.innerHeight; + windowWidth = $window.innerWidth; + body.css({ + 'height': windowHeight + 'px' + }); + + if (ctrl.isDockedModal) { + var modalElements = element.parent().children(); + for (var i = 0; i < modalElements.length; i++) { + if (modalElements.eq(i).hasClass('b2b-modal-header')) { + modalHeaderHeight = $position.position(modalElements.eq(i)).height; + } else if (modalElements.eq(i).hasClass('b2b-modal-footer')) { + modalFooterHeight = $position.position(modalElements.eq(i)).height; + } + } + + var el = element[0]; + while((el = el.parentElement) && !el.classList.contains('modal') && !el.classList.contains('fade') && !el.classList.contains('in')); + if (el !== document.documentElement) { + modalHeight = el.getBoundingClientRect().height + } else { + modalHeight = $position.position(element.parent()).height; + } + + modalBodyHeight = modalHeight - (modalHeaderHeight + modalFooterHeight) + 'px'; + + if (windowOrientation.isPotrait()) { // Potrait Mode + element.removeAttr('style').css({ + height: modalBodyHeight + }); + } else if (windowOrientation.isLandscape() && windowWidth < b2bAwdBreakpoints.breakpoints.mobile.max) { // Landscape Mode Mobile + element.removeAttr('style'); + } else if (windowOrientation.isLandscape() && windowWidth >= b2bAwdBreakpoints.breakpoints.mobile.max) { // Landscape Mode Non-Mobile + element.removeAttr('style').css({ + height: modalBodyHeight + }); + } + } + }; + + $timeout(function () { + scope.setModalHeight(); + scope.$apply(); + }, 100); + window.bind('orientationchange', function () { + scope.setModalHeight(); + scope.$apply(); + }); + window.bind('resize', function () { + scope.setModalHeight(); + scope.$apply(); + }); + } + }; +}]) + +.directive('b2bModalFooter', ['windowOrientation', '$window', function (windowOrientation, $window) { + return { + restrict: 'AC', + scope: { + index: '@' + }, + link: function (scope, element, attrs) { + + } + }; +}]) + +.factory('$modalStack', ['$document', '$compile', '$rootScope', '$$stackedMap', '$log', '$timeout', 'trapFocusInElement', function ($document, $compile, $rootScope, $$stackedMap, $log, $timeout, trapFocusInElement) { + var backdropjqLiteEl, backdropDomEl; + var backdropScope = $rootScope.$new(true); + var body = $document.find('body').eq(0); + var html = $document.find('html').eq(0); + var openedWindows = $$stackedMap.createNew(); + var $modalStack = {}; + + function backdropIndex() { + var topBackdropIndex = -1; + var opened = openedWindows.keys(); + for (var i = 0; i < opened.length; i++) { + if (openedWindows.get(opened[i]).value.backdrop) { + topBackdropIndex = i; + } + } + return topBackdropIndex; + } + + $rootScope.$watch(backdropIndex, function (newBackdropIndex) { + backdropScope.index = newBackdropIndex; + }); + + function removeModalWindow(modalInstance) { + //background scroll fix + html.removeAttr('style'); + body.removeAttr('style'); + body.removeClass('styled-by-modal'); + + var modalWindow = openedWindows.get(modalInstance).value; + trapFocusInElement(false, modalWindow.modalDomEl); + + //clean up the stack + openedWindows.remove(modalInstance); + + //remove window DOM element + modalWindow.modalDomEl.remove(); + + //remove backdrop if no longer needed + if (backdropDomEl && backdropIndex() === -1) { + backdropDomEl.remove(); + backdropDomEl = undefined; + } + + //destroy scope + modalWindow.modalScope.$destroy(); + } + + $document.bind('keydown', function (evt) { + var modal; + + if (evt.which === 27) { + modal = openedWindows.top(); + if (modal && modal.value.keyboard) { + $rootScope.$apply(function () { + $modalStack.dismiss(modal.key); + }); + } + } + }); + + $modalStack.open = function (modalInstance, modal) { + + openedWindows.add(modalInstance, { + deferred: modal.deferred, + modalScope: modal.scope, + backdrop: modal.backdrop, + keyboard: modal.keyboard + }); + + var angularDomEl = angular.element('
    '); + angularDomEl.attr('window-class', modal.windowClass); + angularDomEl.attr('size-class', modal.sizeClass); + angularDomEl.attr('index', openedWindows.length() - 1); + angularDomEl.attr('modal-close', modal.modalClose); + angularDomEl.html(modal.content); + + var modalDomEl = $compile(angularDomEl)(modal.scope); + openedWindows.top().value.modalDomEl = modalDomEl; + //background page scroll fix + html.css({ + 'overflow-y': 'hidden' + }); + body.css({ + 'overflow-y': 'hidden', + 'width': '100%', + 'height': window.innerHeight + 'px' + }); + body.addClass('styled-by-modal'); + body.append(modalDomEl); + + if (backdropIndex() >= 0 && !backdropDomEl) { + backdropjqLiteEl = angular.element('
    '); + backdropDomEl = $compile(backdropjqLiteEl)(backdropScope); + body.append(backdropDomEl); + } + + $timeout(function () { + + if (modal.scope.$$childHead.isNotifDialog) { + angular.element(modalDomEl).find('button')[0].focus(); + } else { + angular.element(modalDomEl)[0].focus(); + } + trapFocusInElement(true, angular.element(modalDomEl).eq(0)); + }, 200); + }; + + $modalStack.close = function (modalInstance, result) { + var modal = openedWindows.get(modalInstance); + if (modal) { + modal.value.deferred.resolve(result); + removeModalWindow(modalInstance); + } + }; + + $modalStack.dismiss = function (modalInstance, reason) { + var modalWindow = openedWindows.get(modalInstance).value; + if (modalWindow) { + modalWindow.deferred.reject(reason); + removeModalWindow(modalInstance); + } + }; + + $modalStack.getTop = function () { + return openedWindows.top(); + }; + + return $modalStack; +}]) + +.provider('$modal', function () { + var $modalProvider = { + options: { + backdrop: true, //can be also false or 'static' + keyboard: true + }, + $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack', function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) { + var $modal = {}; + + function getTemplatePromise(options) { + return options.template ? $q.when(options.template) : + $http.get(options.templateUrl, { + cache: $templateCache + }).then(function (result) { + return result.data; + }); + } + + function getResolvePromises(resolves) { + var promisesArr = []; + angular.forEach(resolves, function (value, key) { + if (angular.isFunction(value) || angular.isArray(value)) { + promisesArr.push($q.when($injector.invoke(value))); + } + }); + return promisesArr; + } + + $modal.open = function (modalOptions) { + + var modalResultDeferred = $q.defer(); + var modalOpenedDeferred = $q.defer(); + //prepare an instance of a modal to be injected into controllers and returned to a caller + var modalInstance = { + result: modalResultDeferred.promise, + opened: modalOpenedDeferred.promise, + close: function (result) { + $modalStack.close(modalInstance, result); + }, + dismiss: function (reason) { + $modalStack.dismiss(modalInstance, reason); + } + }; + + //merge and clean up options + modalOptions = angular.extend({}, $modalProvider.options, modalOptions); + modalOptions.resolve = modalOptions.resolve || {}; + + //verify options + if (!modalOptions.template && !modalOptions.templateUrl) { + throw new Error('One of template or templateUrl options is required.'); + } + + var templateAndResolvePromise = + $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); + + + templateAndResolvePromise.then(function resolveSuccess(tplAndVars) { + + var modalScope = (modalOptions.scope || $rootScope).$new(); + modalScope.$close = modalInstance.close; + modalScope.$dismiss = modalInstance.dismiss; + + var ctrlInstance, ctrlLocals = {}; + var resolveIter = 1; + + //controllers + if (modalOptions.controller) { + ctrlLocals.$scope = modalScope; + ctrlLocals.$modalInstance = modalInstance; + angular.forEach(modalOptions.resolve, function (value, key) { + ctrlLocals[key] = tplAndVars[resolveIter++]; + }); + + ctrlInstance = $controller(modalOptions.controller, ctrlLocals); + } + + $modalStack.open(modalInstance, { + scope: modalScope, + deferred: modalResultDeferred, + content: tplAndVars[0], + backdrop: modalOptions.backdrop, + keyboard: modalOptions.keyboard, + windowClass: modalOptions.windowClass, + sizeClass: modalOptions.sizeClass, + modalClose: modalOptions.modalClose + }); + + }, function resolveError(reason) { + modalResultDeferred.reject(reason); + }); + + templateAndResolvePromise.then(function () { + modalOpenedDeferred.resolve(true); + }, function () { + modalOpenedDeferred.reject(false); + }); + + return modalInstance; + }; + + return $modal; + }] + }; + + return $modalProvider; +}) + +.directive("b2bModal", ["$modal", "$log", '$scrollTo', function ($modal, $log, $scrollTo) { + return { + restrict: 'A', + scope: { + b2bModal: '@', + modalController: '@', + modalOk: '&', + modalCancel: '&', + windowClass: '@', + sizeClass: '@', + modalClose: '@' + }, + link: function (scope, elm, attr) { + elm.bind('click', function (ev) { + var currentPosition = ev.pageY - ev.clientY; + ev.preventDefault(); + if (angular.isDefined(elm.attr("href")) && elm.attr("href") !== "") { + scope.b2bModal = elm.attr("href"); + } + $modal.open({ + templateUrl: scope.b2bModal, + controller: scope.modalController, + windowClass: scope.windowClass, + sizeClass: scope.sizeClass, + modalClose: scope.modalClose + }).result.then(function (value) { + scope.modalOk({ + value: value + }); + elm[0].focus(); + }, function (value) { + scope.modalCancel({ + value: value + }); + elm[0].focus(); + }); + }); + } + }; +}]) + +.directive("utilityFilter", ["$modal", "$log", '$scrollTo', function ($modal, $log, $scrollTo) { + return { + restrict: 'EA', + scope: { + utilityFilter: '@' + }, + require: 'ngModel', + templateUrl: 'b2bTemplate/modal/u-filter.html', + link: function (scope, element, attribute, ctrl) { + //controller to be passed to $modal service + scope.options = angular.copy(scope.$parent.$eval(attribute.ngModel)); + scope.$parent.$watch(attribute.ngModel, function (newVal, oldVal) { + if (newVal !== oldVal) { + scope.options = newVal; + } + }); + var modalCtrl = function ($scope, options) { + $scope.options = angular.copy(options); + }; + + if (angular.isDefined(scope.utilityFilter)) { + scope.templateUrl = scope.utilityFilter; + } else { + scope.templateUrl = 'b2bTemplate/modal/u-filter-window.html'; + } + element.bind('click', function (ev) { + var currentPosition = ev.pageY - ev.clientY; + $modal.open({ + templateUrl: scope.templateUrl, + controller: modalCtrl, + resolve: { + options: function () { + return scope.options; + } + } + }).result.then(function (value) { + ctrl.$setViewValue(value); + element[0].focus(); + $scrollTo(0, currentPosition, 0); + }, function () { + element[0].focus(); + $scrollTo(0, currentPosition, 0); + }); + }); + } + }; +}]); +/** + * @ngdoc directive + * @name Forms.att:monthSelector + * + * @description + * + * + * @usage + *
    + + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.monthSelector', ['b2b.att.position', 'b2b.att.utilities']) + +.constant('b2bMonthpickerConfig', { + dateFormat: 'MM/dd/yyyy', + dayFormat: 'd', + monthFormat: 'MMMM', + yearFormat: 'yyyy', + dayHeaderFormat: 'EEEE', + dayTitleFormat: 'MMMM yyyy', + disableWeekend: false, + disableSunday: false, + disableDates: null, + onSelectClose: null, + startingDay: 0, + minDate: null, + maxDate: null, + dueDate: null, + fromDate: null, + legendIcon: null, + legendMessage: null, + calendarDisabled: false, + collapseWait: 0, + orientation: 'left', + inline: false, + mode:0, + helperText: 'The date you selected is $date. Double tap to open calendar. Select a date to close the calendar.', + descriptionText: 'Use tab to navigate between previous button, next button and month. Use arrow keys to navigate between months. Use space or enter to select a month.', + MonthpickerEvalAttributes: ['dateFormat', 'dayFormat', 'monthFormat', 'yearFormat', 'dayHeaderFormat', 'dayTitleFormat', 'disableWeekend', 'disableSunday', 'startingDay', 'collapseWait', 'orientation','mode','id'], + MonthpickerWatchAttributes: ['min', 'max', 'due', 'from', 'legendIcon', 'legendMessage', 'ngDisabled'], + MonthpickerFunctionAttributes: ['disableDates', 'onSelectClose'] +}) + +.factory('b2bMonthpickerService', ['b2bMonthpickerConfig', 'dateFilter', function (b2bMonthpickerConfig, dateFilter) { + var setAttributes = function (attr, elem) { + if (angular.isDefined(attr) && attr !== null && angular.isDefined(elem) && elem !== null) { + var attributes = b2bMonthpickerConfig.MonthpickerEvalAttributes.concat(b2bMonthpickerConfig.MonthpickerWatchAttributes, b2bMonthpickerConfig.MonthpickerFunctionAttributes); + for (var key in attr) { + var val = attr[key]; + if (attributes.indexOf(key) !== -1 && angular.isDefined(val)) { + elem.attr(key.toSnakeCase(), key); + } + } + } + }; + + var bindScope = function (attr, scope) { + if (angular.isDefined(attr) && attr !== null && angular.isDefined(scope) && scope !== null) { + var evalFunction = function (key, val) { + scope[key] = scope.$parent.$eval(val); + }; + + var watchFunction = function (key, val) { + scope.$parent.$watch(val, function (value) { + scope[key] = value; + }); + scope.$watch(key, function (value) { + scope.$parent[val] = value; + }); + }; + + var evalAttributes = b2bMonthpickerConfig.MonthpickerEvalAttributes; + var watchAttributes = b2bMonthpickerConfig.MonthpickerWatchAttributes; + for (var key in attr) { + var val = attr[key]; + if (evalAttributes.indexOf(key) !== -1 && angular.isDefined(val)) { + evalFunction(key, val); + } else if (watchAttributes.indexOf(key) !== -1 && angular.isDefined(val)) { + watchFunction(key, val); + } + } + } + }; + + return { + setAttributes: setAttributes, + bindScope: bindScope + }; +}]) + +.controller('b2bMonthpickerController', ['$scope', '$attrs', 'dateFilter', '$element', '$position', 'b2bMonthpickerConfig', function ($scope, $attrs, dateFilter, $element, $position, dtConfig) { + var format = { + date: getValue($attrs.dateFormat, dtConfig.dateFormat), + day: getValue($attrs.dayFormat, dtConfig.dayFormat), + month: getValue($attrs.monthFormat, dtConfig.monthFormat), + year: getValue($attrs.yearFormat, dtConfig.yearFormat), + dayHeader: getValue($attrs.dayHeaderFormat, dtConfig.dayHeaderFormat), + dayTitle: getValue($attrs.dayTitleFormat, dtConfig.dayTitleFormat), + disableWeekend: getValue($attrs.disableWeekend, dtConfig.disableWeekend), + disableSunday: getValue($attrs.disableSunday, dtConfig.disableSunday), + disableDates: getValue($attrs.disableDates, dtConfig.disableDates) + }, + startingDay = getValue($attrs.startingDay, dtConfig.startingDay); + + $scope.minDate = dtConfig.minDate ? $scope.resetTime(dtConfig.minDate) : null; + $scope.maxDate = dtConfig.maxDate ? $scope.resetTime(dtConfig.maxDate) : null; + $scope.dueDate = dtConfig.dueDate ? $scope.resetTime(dtConfig.dueDate) : null; + $scope.fromDate = dtConfig.fromDate ? $scope.resetTime(dtConfig.fromDate) : null; + $scope.legendIcon = dtConfig.legendIcon ? dtConfig.legendIcon : null; + $scope.legendMessage = dtConfig.legendMessage ? dtConfig.legendMessage : null; + $scope.ngDisabled = dtConfig.calendarDisabled ? dtConfig.calendarDisabled : null; + $scope.collapseWait = getValue($attrs.collapseWait, dtConfig.collapseWait); + $scope.orientation = getValue($attrs.orientation, dtConfig.orientation); + $scope.onSelectClose = getValue($attrs.onSelectClose, dtConfig.onSelectClose); + $scope.mode = getValue($attrs.mode, dtConfig.mode); + + $scope.inline = $attrs.inline === 'true' ? true : dtConfig.inline; + + function getValue(value, defaultValue) { + return angular.isDefined(value) ? $scope.$parent.$eval(value) : defaultValue; + } + + function getDaysInMonth(year, month) { + return new Date(year, month, 0).getDate(); + } + + function getDates(startDate, n) { + var dates = new Array(n); + var current = startDate, + i = 0; + while (i < n) { + dates[i++] = new Date(current); + current.setDate(current.getDate() + 1); + } + return dates; + } + + this.updatePosition = function (b2bMonthpickerPopupTemplate) { + $scope.position = $position.offset($element); + if($element.find('input').length > 0 ){ + $scope.position.top += $element.find('input').prop('offsetHeight'); + }else{ + $scope.position.top += $element.find('a').prop('offsetHeight'); + } + + if ($scope.orientation === 'right') { + $scope.position.left -= (((b2bMonthpickerPopupTemplate && b2bMonthpickerPopupTemplate.prop('offsetWidth')) || 290) - $element.find('input').prop('offsetWidth')); + } + }; + + function isSelected(dt) { + if (dt && angular.isDate($scope.currentDate) && compare(dt, $scope.currentDate) === 0) { + return true; + } + return false; + } + + function isFromDate(dt) { + if (dt && angular.isDate($scope.fromDate) && compare(dt, $scope.fromDate) === 0) { + return true; + } + return false; + } + + function isDateRange(dt) { + if (dt && $scope.fromDate && angular.isDate($scope.currentDate) && (compare(dt, $scope.fromDate) >= 0) && (compare(dt, $scope.currentDate) <= 0)) { + return true; + } else if (dt && $scope.fromDate && compare(dt, $scope.fromDate) === 0) { + return true; + } + return false; + } + + function isOld(date, currentMonthDate) { + if (date && currentMonthDate && (new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0).getTime() < new Date(currentMonthDate.getFullYear(), currentMonthDate.getMonth(), 1, 0, 0, 0).getTime())) { + return true; + } else { + return false; + } + } + + function isNew(date, currentMonthDate) { + if (date && currentMonthDate && (new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0).getTime() > new Date(currentMonthDate.getFullYear(), currentMonthDate.getMonth(), 1, 0, 0, 0).getTime())) { + return true; + } else { + return false; + } + } + + function isPastDue(dt) { + if ($scope.dueDate) { + return (dt > $scope.dueDate); + } + return false; + } + + function isDueDate(dt) { + if ($scope.dueDate) { + return (dt.getTime() === $scope.dueDate.getTime()); + } + return false; + } + + var isDisabled = function (date, currentMonthDate) { + if ($attrs.from && !angular.isDate($scope.fromDate)) { + return true; + } + if (format.disableWeekend === true && (dateFilter(date, format.dayHeader) === "Saturday" || dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (format.disableSunday === true && (dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (isOld(date, currentMonthDate) || isNew(date, currentMonthDate)) { + return true; + } + return (($scope.minDate && compare(date, $scope.minDate) < 0) || ($scope.maxDate && compare(date, $scope.maxDate) > 0) || (format.disableDates && format.disableDates({ + date: date + }))); + }; + + var isDisabledMonth = function (date, currentMonthDate) { + if ($attrs.from && !angular.isDate($scope.fromDate)) { + return true; + } + if (format.disableWeekend === true && (dateFilter(date, format.dayHeader) === "Saturday" || dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + if (format.disableSunday === true && (dateFilter(date, format.dayHeader) === "Sunday")) { + return true; + } + return (($scope.minDate && compare(date, $scope.minDate) < 0) || ($scope.maxDate && compare(date, $scope.maxDate) > 0) || (format.disableDates && format.disableDates({ + date: date + }))); + }; + + var compare = function (date1, date2) { + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + }; + + function isMinDateAvailable(startDate, endDate) { + if (($scope.minDate && $scope.minDate.getTime() >= startDate.getTime()) && ($scope.minDate.getTime() <= endDate.getTime())) { + $scope.disablePrev = true; + $scope.visibilityPrev = "hidden"; + } else { + $scope.disablePrev = false; + $scope.visibilityPrev = "visible"; + } + } + + function isMaxDateAvailable(startDate, endDate) { + if (($scope.maxDate && $scope.maxDate.getTime() >= startDate.getTime()) && ($scope.maxDate.getTime() <= endDate.getTime())) { + $scope.disableNext = true; + $scope.visibilityNext = "hidden"; + } else { + $scope.disableNext = false; + $scope.visibilityNext = "visible"; + } + } + + function isYearInRange(currentYear) { + + if ($scope.minDate && currentYear === $scope.minDate.getFullYear()) { + $scope.disablePrev = true; + $scope.visibilityPrev = "hidden"; + } else { + $scope.disablePrev = false; + $scope.visibilityPrev = "visible"; + } + + if ($scope.maxDate && currentYear === $scope.maxDate.getFullYear()) { + $scope.disableNext = true; + $scope.visibilityNext = "hidden"; + } else { + $scope.disableNext = false; + $scope.visibilityNext = "visible"; + } + + } + + this.focusNextPrev = function(b2bMonthpickerPopupTemplate,init){ + if(init){ + if (!$scope.disablePrev){ + b2bMonthpickerPopupTemplate[0].querySelector('th.prev').focus(); + }else if (!$scope.disableNext){ + b2bMonthpickerPopupTemplate[0].querySelector('th.next').focus(); + }else{ + b2bMonthpickerPopupTemplate[0].querySelector('th.b2b-monthSelector-label').focus(); + } + }else{ + if ($scope.disableNext || $scope.disablePrev){ + b2bMonthpickerPopupTemplate[0].querySelector('th.b2b-monthSelector-label').focus(); + } + } + }; + + function getLabel(label) { + if (label) { + var labelObj = { + pre: label.substr(0, 1).toUpperCase(), + post: label + }; + return labelObj; + } + return; + } + + function makeDate(date, dayFormat, dayHeaderFormat, isSelected, isFromDate, isDateRange, isOld, isNew, isDisabled, dueDate, pastDue) { + return { + date: date, + label: dateFilter(date, dayFormat), + header: dateFilter(date, dayHeaderFormat), + selected: !!isSelected, + fromDate: !!isFromDate, + dateRange: !!isDateRange, + oldMonth: !!isOld, + nextMonth: !!isNew, + disabled: !!isDisabled, + dueDate: !!dueDate, + pastDue: !!pastDue, + focusable: !((isDisabled && !(isSelected || isDateRange)) || (isOld || isNew)) + }; + } + + this.modes = [ + { + name: 'day', + getVisibleDates: function (date) { + var year = date.getFullYear(), + month = date.getMonth(), + firstDayOfMonth = new Date(year, month, 1), + lastDayOfMonth = new Date(year, month + 1, 0); + var difference = startingDay - firstDayOfMonth.getDay(), + numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : -difference, + firstDate = new Date(firstDayOfMonth), + numDates = 0; + + if (numDisplayedFromPreviousMonth > 0) { + firstDate.setDate(-numDisplayedFromPreviousMonth + 1); + numDates += numDisplayedFromPreviousMonth; // Previous + } + numDates += getDaysInMonth(year, month + 1); // Current + numDates += (7 - numDates % 7) % 7; // Next + + var days = getDates(firstDate, numDates), + labels = new Array(7); + for (var i = 0; i < numDates; i++) { + var dt = new Date(days[i]); + days[i] = makeDate(dt, + format.day, + format.dayHeader, + isSelected(dt), + isFromDate(dt), + isDateRange(dt), + isOld(dt, date), + isNew(dt, date), + isDisabled(dt, date), + isDueDate(dt), + isPastDue(dt)); + } + for (var j = 0; j < 7; j++) { + labels[j] = getLabel(dateFilter(days[j].date, format.dayHeader)); + } + isMinDateAvailable(firstDayOfMonth, lastDayOfMonth); + isMaxDateAvailable(firstDayOfMonth, lastDayOfMonth); + return { + objects: days, + title: dateFilter(date, format.dayTitle), + labels: labels + }; + }, + split: 7, + step: { + months: 1 + } + }, + { + name: 'month', + getVisibleDates: function(date) { + var months = [], + labels = [], + year = date.getFullYear(); + for (var i = 0; i < 12; i++) { + var dt = new Date(year,i,1); + months[i] = makeDate(dt, + format.month, + format.dayHeader, + isSelected(dt), + isFromDate(dt), + isDateRange(dt), + false, + false, + isDisabledMonth(dt, date), + isDueDate(dt), + isPastDue(dt)); + } + isYearInRange(year); + return {objects: months, title: dateFilter(date, format.year), labels: labels}; + }, + split:4, + step: {years: 1} + } + ]; +}]) + +.directive('b2bMonthpickerPopup', ['$parse', '$log', '$timeout', '$document', '$documentBind', '$isElement', '$templateCache', '$compile','$interval', 'trapFocusInElement', 'keymap', function ($parse, $log, $timeout, $document, $documentBind, $isElement, $templateCache, $compile, $interval,trapFocusInElement, keymap) { + return { + restrict: 'EA', + scope: { + trigger: '=' + }, + replace: true, + transclude: true, + templateUrl: function (elem, attr) { + if (attr.inline === 'true') { + return 'b2bTemplate/monthSelector/monthSelector-popup.html'; + }else if (attr.link === 'true') { + return 'b2bTemplate/monthSelector/monthSelectorLink.html'; + }else { + return 'b2bTemplate/monthSelector/monthSelector.html'; + } + }, + scope: {}, + require: ['b2bMonthpickerPopup', 'ngModel', '?^b2bMonthpickerGroup'], + controller: 'b2bMonthpickerController', + link: function (scope, element, attrs, ctrls) { + var MonthpickerCtrl = ctrls[0], + ngModel = ctrls[1], + b2bMonthpickerGroupCtrl = ctrls[2]; + var b2bMonthpickerPopupTemplate; + + if (!ngModel) { + $log.error("ng-model is required."); + return; // do nothing if no ng-model + } + + // Configuration parameters + var mode = scope.mode, + selected; + scope.isOpen = false; + + scope.headers = []; + scope.footers = []; + scope.triggerInterval=undefined; + + + if (b2bMonthpickerGroupCtrl) { + b2bMonthpickerGroupCtrl.registerMonthpickerScope(scope); + } + + element.bind('keydown', function (ev) { + if (!ev.keyCode) { + if (ev.which) { + ev.keyCode = ev.which; + } else if (ev.charCode) { + ev.keyCode = ev.charCode; + } + } + if(ev.keyCode === keymap.KEY.ESC) + { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + scope.$apply(); + } + }); + + element.find('button').bind('click', function () { + onClicked(); + }); + + element.find('a').bind('click', function () { + onClicked(); + }); + + + element.find('input').bind('click', function () { + onClicked(); + }); + + var onClicked = function() { + if (!scope.ngDisabled) { + scope.isOpen = !scope.isOpen; + toggleCalendar(scope.isOpen); + MonthpickerCtrl.updatePosition(b2bMonthpickerPopupTemplate); + scope.$apply(); + } + }; + + var toggleCalendar = function (flag) { + if (!scope.inline) { + if (flag) { + b2bMonthpickerPopupTemplate = angular.element($templateCache.get('b2bTemplate/monthSelector/monthSelector-popup.html')); + b2bMonthpickerPopupTemplate.attr('b2b-trap-focus-inside-element', 'false'); + b2bMonthpickerPopupTemplate.attr('trigger', 'true'); + b2bMonthpickerPopupTemplate = $compile(b2bMonthpickerPopupTemplate)(scope); + $document.find('body').append(b2bMonthpickerPopupTemplate); + b2bMonthpickerPopupTemplate.bind('keydown', escPress); + $timeout(function () { + scope.getFocus = true; + scope.trigger=0; + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + MonthpickerCtrl.focusNextPrev(b2bMonthpickerPopupTemplate,true); + }, 100); + }); + scope.triggerInterval = $interval(function () { + //This value is updated to trigger init() function of directive on year change. + scope.trigger=(scope.trigger === 0 ? 1 : 0); + }, 200); + + } else { + if(b2bDatepickerPopupTemplate !== undefined) { + b2bMonthpickerPopupTemplate.unbind('keydown', escPress); + b2bMonthpickerPopupTemplate.remove(); + } + if(scope.triggerInterval) + { + $interval.cancel(scope.triggerInterval); + scope.triggerInterval=undefined; + } + + if(element.find('button').length > 0){ + element.find('button')[0].focus(); + }else{ + element.find('a')[0].focus(); + } + + scope.getFocus = false; + } + } + }; + + var outsideClick = function (e) { + var isElement = $isElement(angular.element(e.target), element, $document); + var isb2bMonthpickerPopupTemplate = $isElement(angular.element(e.target), b2bMonthpickerPopupTemplate, $document); + if (!(isElement || isb2bMonthpickerPopupTemplate)) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + scope.$apply(); + } + }; + + var escPress = function (ev) { + if (!ev.keyCode) { + if (ev.which) { + ev.keyCode = ev.which; + } else if (ev.charCode) { + ev.keyCode = ev.charCode; + } + } + if (ev.keyCode) { + if (ev.keyCode === keymap.KEY.ESC) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === 33) { + !scope.disablePrev && scope.move(-1); + $timeout(function () { + scope.getFocus = true; + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + }, 100); + }); + ev.preventDefault(); + ev.stopPropagation(); + } else if (ev.keyCode === 34) { + !scope.disableNext && scope.move(1); + $timeout(function () { + scope.getFocus = true; + scope.$apply(); + $timeout(function () { + scope.getFocus = false; + scope.$apply(); + }, 100); + }); + ev.preventDefault(); + ev.stopPropagation(); + } + scope.$apply(); + } + }; + + $documentBind.click('isOpen', outsideClick, scope); + + scope.$on('$destroy', function () { + if (scope.isOpen) { + scope.isOpen = false; + toggleCalendar(scope.isOpen); + } + }); + + scope.resetTime = function (date) { + if (typeof date === 'string') { + date = date + 'T12:00:00'; + } + var dt; + if (!isNaN(new Date(date))) { + dt = new Date(date); + if(scope.mode === 1){ + dt = new Date(dt.getFullYear(), dt.getMonth()); + }else{ + dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); + } + } else { + return null; + } + return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); + }; + + if (attrs.min) { + scope.$parent.$watch($parse(attrs.min), function (value) { + scope.minDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.max) { + scope.$parent.$watch($parse(attrs.max), function (value) { + scope.maxDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.due) { + scope.$parent.$watch($parse(attrs.due), function (value) { + scope.dueDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + if (attrs.from) { + scope.$parent.$watch($parse(attrs.from), function (value) { + scope.fromDate = value ? scope.resetTime(value) : null; + refill(); + }); + } + + if (attrs.legendIcon) { + scope.$parent.$watch(attrs.legendIcon, function (value) { + scope.legendIcon = value ? value : null; + refill(); + }); + } + if (attrs.legendMessage) { + scope.$parent.$watch(attrs.legendMessage, function (value) { + scope.legendMessage = value ? value : null; + refill(); + }); + } + if (attrs.ngDisabled) { + scope.$parent.$watch(attrs.ngDisabled, function (value) { + scope.ngDisabled = value ? value : null; + }); + } + + + // Split array into smaller arrays + function split(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + } + + var moveMonth = function(selectedDate, direction) { + var step = MonthpickerCtrl.modes[scope.mode].step; + selectedDate.setDate(1); + selectedDate.setMonth(selectedDate.getMonth() + direction * (step.months || 0)); + selectedDate.setFullYear(selectedDate.getFullYear() + direction * (step.years || 0)); + + return selectedDate; + }; + + function refill(date) { + if (angular.isDate(date) && !isNaN(date)) { + selected = new Date(date); + } else { + if (!selected) { + selected = new Date(); + } + } + + if (selected) { + var selectedCalendar; + if(scope.mode === 1){ + if(!angular.isDate(selected)) + { + selected = new Date(); + } + selectedCalendar = moveMonth(angular.copy(selected), -1); + } else { + selectedCalendar = angular.copy(selected); + } + + var currentMode = MonthpickerCtrl.modes[mode], + data = currentMode.getVisibleDates(selected); + + scope.rows = split(data.objects, currentMode.split); + + var flag=false; + var startFlag=false; + var firstSelected = false; + for(var i=0; i' + helperText + ''; + elem.attr('tabindex', '-1'); + elem.attr('aria-hidden', 'true'); + elem.attr('readonly', 'true'); + }else{ + selectedDateMessage = '' + elem.attr('aria-label', helperText); + } + + var descriptionTextSpan = ''+descriptionText+''; + elem.removeAttr('b2b-Monthpicker'); + elem.removeAttr('ng-model'); + elem.removeAttr('ng-disabled'); + elem.addClass('Monthpicker-input'); + elem.attr('ng-model', 'dt'); + elem.attr('aria-describedby', 'monthpicker-description'+scope.$id); + + + + elem.attr('ng-disabled', 'ngDisabled'); + elem.attr('b2b-format-date', dateFormatString); + + var wrapperElement = angular.element('
    '); + wrapperElement.attr('b2b-Monthpicker-popup', ''); + wrapperElement.attr('ng-model', 'dt'); + if (inline) { + wrapperElement.attr('inline', inline); + } + if (elem.prop('nodeName') === 'A'){ + wrapperElement.attr('link', true); + } + b2bMonthpickerService.setAttributes(attr, wrapperElement); + b2bMonthpickerService.bindScope(attr, scope); + + wrapperElement.html(''); + wrapperElement.append(selectedDateMessage); + wrapperElement.append(''); + wrapperElement.append(descriptionTextSpan); + wrapperElement.append(''); + wrapperElement.append(elem.prop('outerHTML')); + + var elm = wrapperElement.prop('outerHTML'); + elm = $compile(elm)(scope); + elem.replaceWith(elm); + }], + link: function (scope, elem, attr, ctrl) { + if (!ctrl) { + $log.error("ng-model is required."); + return; // do nothing if no ng-model + } + + scope.$watch('dt', function (value) { + ctrl.$setViewValue(value); + }); + ctrl.$render = function () { + scope.dt = ctrl.$viewValue; + }; + } + }; +}]) + +.directive('b2bMonthpickerGroup', [function () { + return { + restrict: 'EA', + controller: ['$scope', '$element', '$attrs', function (scope, elem, attr) { + this.$$headers = []; + this.$$footers = []; + this.registerMonthpickerScope = function (MonthpickerScope) { + MonthpickerScope.headers = this.$$headers; + MonthpickerScope.footers = this.$$footers; + }; + }], + link: function (scope, elem, attr, ctrl) {} + }; +}]) + +.directive('b2bFormatDate', ['dateFilter', function (dateFilter) { + return { + restrict: 'A', + require: 'ngModel', + link: function (scope, elem, attr, ctrl) { + var b2bFormatDate = ""; + attr.$observe('b2bFormatDate', function (value) { + b2bFormatDate = value; + }); + var dateToString = function (value) { + if (!isNaN(new Date(value))) { + return dateFilter(new Date(value), b2bFormatDate); + } + return value; + }; + ctrl.$formatters.unshift(dateToString); + } + }; +}]) + +.directive('b2bMonthpickerHeader', [function () { + return { + restrict: 'EA', + require: '^b2bMonthpickerGroup', + transclude: true, + replace: true, + template: '', + compile: function (elem, attr, transclude) { + return function link(scope, elem, attr, ctrl) { + if (ctrl) { + ctrl.$$headers.push(transclude(scope, function () {})); + } + elem.remove(); + }; + } + }; +}]) + +.directive('b2bMonthpickerFooter', [function () { + return { + restrict: 'EA', + require: '^b2bMonthpickerGroup', + transclude: true, + replace: true, + template: '', + compile: function (elem, attr, transclude) { + return function link(scope, elem, attr, ctrl) { + if (ctrl) { + ctrl.$$footers.push(transclude(scope, function () {})); + } + elem.remove(); + }; + } + }; +}]); +/** + * @ngdoc directive + * @name Navigation.att:multiLevelNavigation + * + * @description + * + * + * @usage + *
    + * + *
    + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.multiLevelNavigation', ['b2b.att.utilities']) + //directive b2bMlNav Test coverage 100% on 5/13 + .directive('b2bMlNav', ['keymap', function (keymap) { + return { + restrict: 'EA', + link: function (scope, element) { + var rootE, parentE, upE, downE, lastE, homeE, endE; + //default root tree element tabindex set zero + if (element.parent().parent().hasClass('b2b-ml-nav') && (element[0].previousElementSibling === null)) { + element.attr('tabindex', 0); + } + //check root via class + var isRoot = function (elem) { + if (elem.parent().parent().eq(0).hasClass('b2b-ml-nav')) { + return true; + } else { + return false; + } + + } + //for any expandable tree item on click + var toggleState = function (e) { + + if (angular.element(e.target).attr("b2b-ml-nav") !== "endNode") { + var eLink = element.find('a').eq(0); + if (eLink.hasClass('active')) { + eLink.removeClass('active'); + eLink.parent().attr("aria-expanded", "false"); + eLink.find('i').eq(0).removeClass('icon-expanded'); + eLink.find('i').eq(0).addClass('icon-collapsed'); + } else { + eLink.addClass('active'); + eLink.parent().attr("aria-expanded", "true"); + eLink.find('i').eq(0).removeClass('icon-collapsed'); + eLink.find('i').eq(0).addClass('icon-expanded'); + } + } + }; + //function finds the main root-item from particular tree-group + var findRoot = function (elem) { + if (isRoot(elem)) { + rootE = elem; + return; + } + if (elem.attr("b2b-ml-nav") === "middleNode" || elem.attr("b2b-ml-nav") === "endNode") { + parentE = elem.parent().parent(); + } else { + parentE = elem; + } + if (parentE.attr("b2b-ml-nav") === "rootNode") { + rootE = parentE; + } else { + findRoot(parentE); + } + }; + //finds the last visible node of the previous tree-group + var findPreActive = function (elem) { + if (!(elem.hasClass("active"))) { + return; + } else { + var childElems = angular.element(elem[0].nextElementSibling.children); + lastE = angular.element(childElems[childElems.length - 1]); + if (lastE.attr("b2b-ml-nav") === "middleNode" && lastE.find('a').eq(0).hasClass('active')) { + findPreActive(lastE.find('a').eq(0)); + } + upE = lastE; + } + }; + //find above visible link + var findUp = function (elem) { + if (elem[0].previousElementSibling !== null) { + upE = angular.element(elem[0].previousElementSibling); + } else { + upE = elem.parent().parent(); + } + if (isRoot(elem) || (upE.attr('b2b-ml-nav') === "middleNode" && upE[0] !== elem.parent().parent()[0])) { + findPreActive(upE.find('a').eq(0)); + } + }; + //find below visible link + var findDown = function (elem) { + if (elem.hasClass('active')) { + downE = elem.next().find('li').eq(0); + } else { + if (elem.parent().next().length !== 0) { + downE = elem.parent().next().eq(0); + } else { + if (elem.parent().parent().parent().next().length !== 0) { + downE = elem.parent().parent().parent().next().eq(0); + return; + } + downE = elem.parent().eq(0); + } + } + }; + //finds last root-group element of the tree + var findEnd = function (elem) { + findRoot(elem); + endE = angular.element(rootE.parent()[0].children[rootE.parent()[0].children.length - 1]); + }; + //finds first root element of tree + var findHome = function (elem) { + findRoot(elem); + homeE = angular.element(rootE.parent()[0].children[0]); + }; + element.bind('click', function (e) { + if(element.attr("b2b-ml-nav") !== "endNode") { + toggleState(e); + } + if (rootE==undefined){ + findRoot(element); + } + var currSelected = rootE.parent()[0].querySelector('.selected'); + if(currSelected){ + angular.element(currSelected).removeClass('selected'); + } + element.find('a').eq(0).addClass('selected'); + e.stopPropagation(); + }); + element.bind('focus', function (e) { + if(element.attr("b2b-ml-nav") !== "endNode") { + if(element.find('a').eq(0).hasClass('active')) { + element.attr("aria-expanded", true); + } + else { + element.attr("aria-expanded", false); + } + + } + }) + //Keyboard functionality approach: + //find keycode + //set set tabindex -1 on the current focus element + //find the next element to be focussed, set tabindex 0 and throw focus + element.bind('keydown', function (evt) { + switch (evt.keyCode) { + case keymap.KEY.ENTER: + case keymap.KEY.SPACE: + element.triggerHandler('click'); + evt.stopPropagation(); + evt.preventDefault(); + break; + case keymap.KEY.END: + evt.preventDefault(); + element.attr('tabindex', -1); + findEnd(element); + endE.eq(0).attr('tabindex', 0); + endE[0].focus(); + evt.stopPropagation(); + break; + case keymap.KEY.HOME: + evt.preventDefault(); + element.attr('tabindex', -1); + findHome(element); + homeE.eq(0).attr('tabindex', 0); + homeE[0].focus(); + evt.stopPropagation(); + break; + case keymap.KEY.LEFT: + evt.preventDefault(); + if (!isRoot(element)) { + element.attr('tabindex', -1); + parentE = element.parent().parent(); + parentE.eq(0).attr('tabindex', 0); + parentE[0].focus(); + parentE.eq(0).triggerHandler('click'); + } else { + if (element.find('a').eq(0).hasClass('active')) { + element.triggerHandler('click'); + } + } + evt.stopPropagation(); + break; + case keymap.KEY.UP: + evt.preventDefault(); + if (!(isRoot(element) && element[0].previousElementSibling === null)) { + element.attr('tabindex', -1); + findUp(element); + upE.eq(0).attr('tabindex', 0); + upE[0].focus(); + } + evt.stopPropagation(); + break; + case keymap.KEY.RIGHT: + evt.preventDefault(); + if (element.attr("b2b-ml-nav") !== "endNode") { + if (!element.find('a').eq(0).hasClass('active')) { + element.triggerHandler('click'); + } + element.attr('tabindex', -1); + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + } + evt.stopPropagation(); + break; + case keymap.KEY.DOWN: + evt.preventDefault(); + element.attr('tabindex', -1); + if (!(element.attr("b2b-ml-nav") === "middleNode" && element.find('a').eq(0).hasClass('active')) && (element.next().length === 0)) { + if(element.parent().parent().attr("b2b-ml-nav") !== "rootNode" && element.parent().parent()[0].nextElementSibling !== null) + { + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + evt.stopPropagation(); + break; + } + findRoot(element); + if (!(rootE.next().length === 0)) { + rootE.next().eq(0).attr('tabindex', 0); + rootE.next()[0].focus(); + } else { + rootE.eq(0).attr('tabindex', 0); + rootE[0].focus(); + } + evt.stopPropagation(); + break; + } + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + evt.stopPropagation(); + break; + default: + break; + } + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Tabs, tables & accordions.att:multipurposeExpander + * + * @description + * + * + * @usage + * + * + * + * Heading content goes here + * +

    body content goes here

    +
    + *
    + *
    + * + * + * + * Heading content goes here + * +

    body content goes here

    +
    + *
    + * + * @example + *
    + + + + +
    + * + */ + +angular.module('b2b.att.multipurposeExpander', ['b2b.att', 'b2b.att.collapse']) +.directive('b2bExpanderGroup', function () { + return { + restrict: 'EA', + transclude: true, + template: "", + controller:['$scope','$attrs', function($scope,$attrs){ + this.groups = []; + this.index = -1; + this.scope = $scope; + + this.addGroup = function (groupScope) { + var that = this; + groupScope.index = this.groups.length; + this.groups.push(groupScope); + if(this.groups.length > 0){ + this.index = 0; + } + groupScope.$on('$destroy', function () { + that.removeGroup(groupScope); + }); + }; + + this.closeOthers = function (openGroup) { + var closeOthers = angular.isDefined($attrs.closeOthers); + if (closeOthers && !$scope.forceExpand) { + angular.forEach(this.groups, function (group) { + if (group !== openGroup) { + group.isOpen = false; + } + }); + } + if (this.groups.indexOf(openGroup) === (this.groups.length - 1) && $scope.forceExpand) { + $scope.forceExpand = false; + } + }; + this.removeGroup = function (group) { + var index = this.groups.indexOf(group); + if (index !== -1) { + this.groups.splice(this.groups.indexOf(group), 1); + } + }; + }] + + }; + +}) +.directive('b2bExpanders', function () { + return{ + restrict: 'EA', + replace: true, + require:['b2bExpanders','?^b2bExpanderGroup'], + transclude: true, + scope:{isOpen:'=?'}, + template: "
    ", + controller: ['$scope', function ($scope){ + var bodyScope = null; + var expanderScope = null; + this.isOpened = function(){ + if($scope.isOpen) + { + return true; + }else + { + return false; + } + }; + this.setScope = function (scope) { + bodyScope = scope; + bodyScope.isOpen = $scope.isOpen; + }; + this.setExpanderScope = function (scope) { + expanderScope = scope; + }; + this.toggle = function () { + $scope.isOpen = bodyScope.isOpen = !bodyScope.isOpen; + return bodyScope.isOpen; + + }; + this.watchToggle = function(io){ + if(bodyScope !== null && angular.isDefined(bodyScope) && expanderScope !== null && angular.isDefined(expanderScope)){ + bodyScope.isOpen = io; + expanderScope.updateIcons(io); + } + }; + }], + link: function (scope, elem, attr, myCtrl) + { + //scope.isOpen = false; + if(myCtrl[1]){ + myCtrl[1].addGroup(scope); + } + scope.$watch('isOpen', function(val){ + myCtrl[0].watchToggle(scope.isOpen); + if(val && myCtrl[1]){ + myCtrl[1].closeOthers(scope); + } + }); + } + }; +}) + +.directive('b2bExpanderHeading', function () { + return{ + require: "^b2bExpanders", + restrict: 'EA', + replace: true, + transclude: true, + scope: true, + template: "
    " + }; +}) + +.directive('b2bExpanderBody', function () { + return{ + restrict: 'EA', + require: "^b2bExpanders", + replace: true, + transclude: true, + scope: {}, + template: "
    ", + link: function (scope, elem, attr, myCtrl) { + scope.isOpen = false; + myCtrl.setScope(scope); + } + }; +}) + +.directive('b2bExpanderToggle', function () { + return{ + restrict: 'EA', + require: "^b2bExpanders", + scope: { + expandIcon: '@', + collapseIcon: '@' + }, + + link: function (scope, element, attr, myCtrl) + { + myCtrl.setExpanderScope(scope); + var isOpen = myCtrl.isOpened(); + + scope.setIcon = function () { + element.attr("role", "button"); + + if (scope.expandIcon && scope.collapseIcon) + { + if (isOpen) { + element.removeClass(scope.expandIcon); + element.addClass(scope.collapseIcon); + + element.attr("aria-expanded", "true"); + } + else { + element.removeClass(scope.collapseIcon); + element.addClass(scope.expandIcon); + + element.attr("aria-expanded", "false"); + } + } + }; + + element.bind('click', function (){ + scope.toggleit(); + }); + scope.updateIcons = function(nStat){ + isOpen = nStat; + scope.setIcon(); + }; + scope.toggleit = function (){ + isOpen = myCtrl.toggle(); + scope.setIcon(); + scope.$apply(); + }; + scope.setIcon(); + } + }; +}); +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:notesMessagesAndErrors + * + * @description + * + * + * @usage + * See Demo + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.notesMessagesAndErrors', []); +/** + * @ngdoc directive + * @name Template.att:Notification Card + * + * @description + * + * + * @example + *
    + HTML + AngularJS + + + + +
    + * + */ +angular.module('b2b.att.notificationCardTemplate', []) + +/** + * @ngdoc directive + * @name Template.att:Order Confirmation Template + * + * @description + * + * + * @example + *
    + HTML + AngularJS + + + + +
    + * + */ +angular.module('b2b.att.orderConfirmationTemplate', []); + +/** + * @ngdoc directive + * @name Navigation.att:pagination + * + * @description + * + * @param {int} total-pages - Total # of pages, set in your controller $scope + * @param {int} current-page - Current selected page, set in your controller $scope + * @param {function} click-handler - Handler function on click of page number, defined in your controller $scope + * @param {string} input-id - _UNIQUE ID_ __MUST__ be provided for 508 compliance, set in your HTML as static text + * @param {string} input-class - optional class that can be given to use for the go to page container + * + * @usage + *
    + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.pagination', ['b2b.att.utilities', 'ngTouch']) + .directive('b2bPagination', ['b2bUserAgent', 'keymap', '$window', '$timeout', function (b2bUserAgent, keymap, $window, $timeout) { + return { + restrict: 'A', + scope: { + totalPages: '=', + currentPage: '=', + clickHandler: '=?', + inputId: '=', + isDroppable: '=?' + }, + replace: true, + templateUrl: 'b2bTemplate/pagination/b2b-pagination.html', + link: function (scope, elem, attr) { + scope.isMobile = b2bUserAgent.isMobile(); + scope.notMobile = b2bUserAgent.notMobile(); + scope.focusedPage; + scope.meanVal = 3; + scope.inputClass = attr.inputClass; + scope.droppableAttribute = scope.isDroppable ? true : false; + scope.$watch('totalPages', function (value) { + if (angular.isDefined(value) && value !== null) { + scope.pages = []; + if (value < 1) { + scope.totalPages = 1; + return; + } + if (value <= 10) { + for (var i = 1; i <= value; i++) { + scope.pages.push(i); + } + } else if (value > 10) { + var midVal = Math.ceil(value / 2); + scope.pages = [midVal - 2, midVal - 1, midVal, midVal + 1, midVal + 2]; + } + if(scope.currentPage === undefined || scope.currentPage === 1) + { + currentPageChanged(1); + } + } + }); + scope.$watch('currentPage', function (value) { + currentPageChanged(value); + callbackHandler(value); + }); + var callbackHandler = function (num) { + if (angular.isFunction(scope.clickHandler)) { + scope.clickHandler(num); + } + }; + var getBoundary = function(value){ + if ( value < 100 ) { + return 5; + } else if ( 100 <= value && value < 1000 ) { + return 4; + } else if ( 1000 <= value ) { + return 3; + } else { + return 5; // error + } + }; + function currentPageChanged(value) { + if (angular.isDefined(value) && value !== null) { + if (!value || value < 1) { + value = 1; + } + if (value > scope.totalPages) { + value = scope.totalPages; + } + if (scope.currentPage !== value) { + scope.currentPage = value; + callbackHandler(scope.currentPage); + } + if (scope.totalPages > 10) { + var val = parseInt(value); + scope.boundary = getBoundary(val); + if (val <= 6) { // Left (first) section + scope.pages = [1, 2, 3, 4, 5, 6, 7]; + } else if ( val <= (scope.totalPages - scope.boundary) ) { // Middle section + if ( 7 <= val && val < 9 ) { + if(scope.totalPages < 100) { + scope.pages = [val - 3, val - 2, val - 1, val, val + 1, val + 2]; + } else if(scope.totalPages < 1000) { + scope.pages = [val - 2, val - 1, val, val + 1, val + 2]; + } else if(scope.totalPages < 1000) { + scope.pages = [val - 2, val - 1, val, val + 1, val + 2]; + } + } else if ( 9 <= val && val < 100 ) { + scope.pages = [val - 3, val - 2, val - 1, val, val + 1, val + 2]; + } else if ( 100 <= val && val < 1000 ) { + scope.pages = [val - 2, val - 1, val, val + 1]; + } else if ( 1000 <= val ) { + scope.pages = [val - 1, val, val + 1]; + } + } else if ( (scope.totalPages - scope.boundary) < val ) { // Right (last) section + if ( val < 100 ) { + scope.pages = [scope.totalPages - 5, scope.totalPages - 4, scope.totalPages - 3, scope.totalPages - 2, scope.totalPages - 1, scope.totalPages]; + } else if ( 100 <= val && val < 1000 ) { + scope.pages = [scope.totalPages - 4, scope.totalPages - 3, scope.totalPages - 2, scope.totalPages - 1, scope.totalPages]; + } else if ( 1000 <= val ) { + scope.pages = [scope.totalPages - 3, scope.totalPages - 2, scope.totalPages - 1, scope.totalPages]; + } + } + } + if (scope.isMobile) { + var inWidth = $window.innerWidth; + var viewLimit = 7; + if (inWidth <= 400) { + viewLimit = 7; + } else if (inWidth > 400 && inWidth < 500) { + viewLimit = 9; + } else if (inWidth >= 500 && inWidth < 600) { + viewLimit = 11; + } else if (inWidth >= 600 && inWidth < 700) { + viewLimit = 13; + } else if (inWidth >= 700 && inWidth < 800) { + viewLimit = 15; + } + + var val = parseInt(value); + + scope.meanVal = Math.floor(viewLimit / 2); + var lowerLimit = (val - scope.meanVal) < 1 ? 1 : val - scope.meanVal; + var upperLimit = (lowerLimit + viewLimit - 1) > scope.totalPages ? scope.totalPages : lowerLimit + viewLimit - 1; + scope.pages = []; + for (var i = lowerLimit; i <= upperLimit; i++) { + scope.pages.push(i); + } + } + } + } + scope.gotoKeyClick = function (keyEvent) { + if (keyEvent.which === keymap.KEY.ENTER) { + scope.gotoBtnClick() + } + } + scope.gotoBtnClick = function () { + currentPageChanged(parseInt(scope.gotoPage)); + callbackHandler(scope.currentPage); + var qResult = elem[0].querySelector('button'); + angular.element(qResult).attr('disabled','true'); + $timeout(function(){ + elem[0].querySelector('.b2b-pager__item--active').focus(); + }, 50); + scope.gotoPage = null; + } + scope.onfocusIn = function(evt) + { + var qResult = elem[0].querySelector('button'); + angular.element(qResult).removeAttr('disabled'); + } + scope.onfocusOut = function(evt) + { + if(evt.target.value === "") + { + var qResult = elem[0].querySelector('button'); + angular.element(qResult).attr('disabled','true'); + } + } + scope.next = function (event) { + if (event != undefined) { + event.preventDefault(); + } + if (scope.currentPage < scope.totalPages) { + scope.currentPage += 1; + callbackHandler(scope.currentPage); + } + }; + scope.prev = function (event) { + if (event != undefined) { + event.preventDefault(); + } + if (scope.currentPage > 1) { + scope.currentPage -= 1; + callbackHandler(scope.currentPage); + } + }; + scope.selectPage = function (value, event) { + event.preventDefault(); + scope.currentPage = value; + scope.focusedPage = value; + callbackHandler(scope.currentPage); + }; + scope.checkSelectedPage = function (value) { + if (scope.currentPage === value) { + return true; + } + return false; + }; + scope.isFocused = function (page) { + return scope.focusedPage === page; + }; + } + }; + }]); + +/** + * @ngdoc directive + * @name Navigation.att:paneSelector + * + * @description + * + * + * @usage + * Please refer demo.html tab in Example section below. + * + * @example +
    + HTML + AngularJS + + + + +
    + */ + +angular.module('b2b.att.paneSelector', ['b2b.att.tabs', 'b2b.att.utilities']) + +.filter('paneSelectorSelectedItemsFilter', [function () { + return function (listOfItemsArray) { + + if (!listOfItemsArray) { + listOfItemsArray = []; + } + + var returnArray = []; + + for (var i = 0; i < listOfItemsArray.length; i++) { + if (listOfItemsArray[i].isSelected) { + returnArray.push(listOfItemsArray[i]); + } + } + + return returnArray; + }; +}]) + +.filter('paneSelectorFetchChildItemsFilter', [function () { + return function (listOfItemsArray) { + + if (!listOfItemsArray) { + listOfItemsArray = []; + } + + var returnArray = []; + + for (var i = 0; i < listOfItemsArray.length; i++) { + for (var j = 0; j < listOfItemsArray[i].childItems.length; j++) { + returnArray.push(listOfItemsArray[i].childItems[j]); + } + } + + return returnArray; + }; +}]) + +.directive('b2bPaneSelector', [function () { + return { + restrict: 'AE', + replace: true, + templateUrl: 'b2bTemplate/paneSelector/paneSelector.html', + transclude: true, + scope: {} + }; +}]) + +.directive('b2bPaneSelectorPane', [ function () { + return { + restrict: 'AE', + replace: true, + templateUrl: 'b2bTemplate/paneSelector/paneSelectorPane.html', + transclude: true, + scope: {} + }; +}]) + +.directive('b2bTabVertical', ['$timeout', 'keymap', function ($timeout, keymap) { + return { + restrict: 'A', + require: '^b2bTab', + link: function (scope, element, attr, b2bTabCtrl) { + + if (!b2bTabCtrl) { + return; + } + + // retreive the isolateScope + var iScope = angular.element(element).isolateScope(); + + $timeout(function () { + angular.element(element[0].querySelector('a')).unbind('keydown'); + angular.element(element[0].querySelector('a')).bind('keydown', function (evt) { + + if (!(evt.keyCode)) { + evt.keyCode = evt.which; + } + + switch (evt.keyCode) { + case keymap.KEY.DOWN: + evt.preventDefault(); + iScope.nextKey(); + break; + + case keymap.KEY.UP: + evt.preventDefault(); + iScope.previousKey(); + break; + + default:; + } + }); + }); + } + }; +}]); +/** + * @ngdoc directive + * @name Forms.att:phoneNumberInput + * + * @description + * + * + * @usage +
    +
    + +
    + +
    + This field is mandatory! + Please enter valid phone number! + Please enter valid phone number! +
    +
    +
    +
    + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.phoneNumberInput', ['ngMessages', 'b2b.att.utilities']) + .constant("CoreFormsUiConfig", { + phoneMask: '(___) ___-____', + phoneMaskDot: '___.___.____', + phoneMaskHyphen: '___-___-____' + }) + .directive('b2bPhoneMask', ['$parse', 'CoreFormsUiConfig', 'keymap', 'b2bUserAgent', function ($parse, CoreFormsUiConfig, keymap, b2bUserAgent) { + return { + require: 'ngModel', + scope: { + ngModel: '=' + }, + link: function (scope, iElement, iAttrs, ctrl) { + + var mask = ''; + var validPhoneNumber = false; + var currentKey = ''; + if (b2bUserAgent.isMobile()) { + mask = "__________"; + } else { + switch (iAttrs.b2bPhoneMask) { + case "phoneMask": + mask = CoreFormsUiConfig.phoneMask; + break; + case "phoneMaskDot": + mask = CoreFormsUiConfig.phoneMaskDot; + break; + case "phoneMaskHyphen": + mask = CoreFormsUiConfig.phoneMaskHyphen; + break; + default: + mask = CoreFormsUiConfig.phoneMask; + } + } + iElement.attr("maxlength", mask.length); + var checkValidity = function (unmaskedValue, rawValue) { + var valid = false; + if (angular.isUndefined(rawValue) || rawValue === '') { + valid = true; + } else if (unmaskedValue) { + valid = (unmaskedValue.length === 10); + } + ctrl.$setValidity('invalidPhoneNumber', validPhoneNumber); + ctrl.$setValidity('mask', valid); + return valid; + }; + var handleKeyup = function (evt) { + + if (evt && evt.keyCode === keymap.KEY.SHIFT) { + return; + } + + var index, formattedNumber; + if (ctrl.$modelValue) { + formattedNumber = ctrl.$modelValue; + } else { + formattedNumber = iElement.val(); + } + if (!formattedNumber.length && currentKey === '') { + return; + } + var maskLength, inputNumbers, maskArray, tempArray, maskArrayLength; + tempArray = []; + maskArray = mask.split(""); + maskArrayLength = maskArray.length; + maskLength = formattedNumber.substring(0, mask.length); + inputNumbers = formattedNumber.replace(/[^0-9]/g, "").split(""); + for (index = 0; index < maskArrayLength; index++) { + tempArray.push(maskArray[index] === "_" ? inputNumbers.shift() : maskArray[index]); + if (inputNumbers.length === 0) { + break; + } + } + formattedNumber = tempArray.join(""); + if (formattedNumber === '(') { + formattedNumber = ''; + } + + if ( (angular.isDefined(evt) && evt.which) && currentKey !== '') { + if (maskArray[0] === currentKey && formattedNumber === '') { + formattedNumber = '('; + } else if (maskArray[0] === currentKey && formattedNumber === '') { + formattedNumber = formattedNumber + currentKey; + } else if (maskArray[formattedNumber.length] === currentKey) { + formattedNumber = formattedNumber + currentKey; + } + currentKey = ''; + } + + ctrl.$setViewValue(formattedNumber); + ctrl.$render(); + return formattedNumber; + }; + + + // since we are only allowing 0-9, why even let the keypress go forward? + // also added in delete... in case they want to delete :) + var handlePress = function (e) { + if (e.which) { + if ((e.which < 48 || e.which > 57) && (e.which < 96 || e.which > 105)) { + if (e.which !== keymap.KEY.BACKSPACE && e.which !== keymap.KEY.TAB && e.which !== keymap.KEY.DELETE && e.which !== keymap.KEY.ENTER && e.which !== keymap.KEY.LEFT && e.which !== keymap.KEY.RIGHT && + // Allow: Ctrl+V/v + (!(e.ctrlKey) && (e.which !== '118' || e.which !== '86')) && + // Allow: Ctrl+C/c + (!(e.ctrlKey) && (e.which !== '99' || e.which !== '67')) && + // Allow: Ctrl+X/x + (!(e.ctrlKey) && (e.which !== '120' || e.which !== '88')) && + /* 229 key code will sent as placeholder key for andriod devices */ + (e.which != 229 )) { + e.preventDefault ? e.preventDefault() : e.returnValue = false; + validPhoneNumber = false; + } + } else { + validPhoneNumber = true; + } + + setCurrentKey(e); + } + scope.$apply(); + }; + // i moved this out because i thought i might need focus as well.. + // to handle setting the model as the view changes + var parser = function (fromViewValue) { + var letters = /^[A-Za-z]+$/; + var numbers = /^[0-9]+$/; + if (angular.isUndefined(fromViewValue) || fromViewValue === '') { + validPhoneNumber = true; + } else { + if (fromViewValue.match(letters)) { + validPhoneNumber = false; + } + if (fromViewValue.match(numbers)) { + validPhoneNumber = true; + } + } + var clean = ""; + if (fromViewValue && fromViewValue.length > 0) { + clean = fromViewValue.replace(/[^0-9]/g, ''); + } + checkValidity(clean, fromViewValue); + return clean; + }; + + //to handle reading the model and formatting it + var formatter = function (fromModelView) { + var input = ''; + checkValidity(fromModelView); + if (fromModelView) { + input = handleKeyup(); + } + return input; + }; + + var setCurrentKey = function (e) { + switch (e.which) { + case 189: + case 109: + currentKey = '-'; + break; + case 190: + case 110: + currentKey = '.'; + break; + case 57: + if (e.shiftKey === true) { + currentKey = '('; + } + break; + case 48: + if (e.shiftKey === true) { + currentKey = ')'; + } + break; + case 32: + currentKey = ' '; + break; + } + }; + + if (angular.isDefined(scope.ngModel)) { + parser(scope.ngModel); + } + + ctrl.$parsers.push(parser); + ctrl.$formatters.push(formatter); + iElement.bind('keyup', handleKeyup); + iElement.bind('keydown', handlePress); + } + }; +}]); +/** + * @ngdoc directive + * @name Template.att:Profile Blocks + * + * @description + * + * @example + *
    + + + + +
    + * + */ + +angular.module('b2b.att.profileBlockTemplate', []) + + + +/** + * @ngdoc directive + * @name Layouts.att:profileCard + * + * @description + * + * + * @usage + * + * + * @example +
    + + + + +
    + */ + +angular.module('b2b.att.profileCard', ['b2b.att']) +.constant('profileStatus',{ + status: { + ACTIVE: { + status: "Active", + color: "green" + }, + DEACTIVATED: { + status: "Deactivated", + color: "red" + }, + LOCKED: { + status: "Locked", + color: "red" + }, + IDLE: { + status: "Idle", + color: "yellow" + }, + PENDING: { + status: "Pending", + color: "blue" + } + }, + role: "COMPANY ADMINISTRATOR" + +}) +.directive('b2bProfileCard',['$http','$q','profileStatus', function($http,$q,profileStatus) { + return { + restrict: 'EA', + replace: 'true', + templateUrl: function(element, attrs){ + if(!attrs.addUser){ + return 'b2bTemplate/profileCard/profileCard.html'; + } + else{ + return 'b2bTemplate/profileCard/profileCard-addUser.html'; + } + }, + scope: { + profile:'=', + characterLimit: '@' + }, + link: function(scope, elem, attr){ + scope.characterLimit = parseInt(attr.characterLimit, 10) || 25; + scope.shouldClip = function(str) { + return str.length > scope.characterLimit; + }; + + scope.showEmailTooltip = false; + + scope.image=true; + function isImage(src) { + var deferred = $q.defer(); + var image = new Image(); + image.onerror = function() { + deferred.reject(false); + }; + image.onload = function() { + deferred.resolve(true); + }; + if(src !== undefined && src.length>0 ){ + image.src = src; + } else { + deferred.reject(false); + } + return deferred.promise; + } + if(!attr.addUser){ + scope.image=false; + isImage(scope.profile.img).then(function(img) { + scope.image=img; + }); + var splitName=(scope.profile.name).split(' '); + scope.initials=''; + for(var i=0;i + * + * @usage + * See demo section + * + * @param {boolean} refreshRadioGroup - A trigger that recalculates and updates the accessibility roles on radios in a group. + * + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.radios', ['b2b.att.utilities']) +.directive('b2bRadioGroupAccessibility', ['$timeout', 'b2bUserAgent', function($timeout, b2bUserAgent) { + return { + restrict: "A", + scope: { + refreshRadioGroup: "=", + }, + link: function(scope, ele, attr) { + + var roleRadioElement, radioProductSelectElement, radioInputTypeElement; + + $timeout(calculateNumberOfRadio); + + scope.$watch('refreshRadioGroup', function(value) { + if (value === true) { + addingRoleAttribute(); + $timeout(calculateNumberOfRadio); + scope.refreshRadioGroup = false; + } else { + return; + } + }) + + + function calculateNumberOfRadio() { + roleRadioElement = ele[0].querySelectorAll('[role="radio"]'); + + radioProductSelectElement = ele[0].querySelectorAll('[role="radiogroup"] li.radio-box'); + + radioInputTypeElement = ele[0].querySelectorAll('input[type="radio"]'); + + for (var i = 0; i < radioInputTypeElement.length; i++) { + var isChecked = radioInputTypeElement[i].checked ? 'true' : 'false'; + var isDisabled = radioInputTypeElement[i].disabled ? 'true' : 'false'; + var numOfx = i + 1 + ' of ' + radioInputTypeElement.length; + angular.element(roleRadioElement[i]).attr({ + 'aria-checked': isChecked, + 'aria-disabled': isDisabled, + 'data-opNum': numOfx + }); + if (b2bUserAgent.notMobile() || (radioProductSelectElement && radioProductSelectElement.length > 0) ) { + angular.element(roleRadioElement[i]).removeAttr("role"); + } + + if (radioProductSelectElement.length) { + isChecked === 'true' ? angular.element(radioProductSelectElement[i]).addClass('active') : angular.element(radioProductSelectElement[i]).removeClass('active'); + } + + if (/Android/i.test(navigator.userAgent)) { + angular.element(roleRadioElement[i]).append('. ' + numOfx + '.'); + } + + + angular.element(radioInputTypeElement[i]).bind('click', radioStateChangeonClick); + + } + } + + function addingRoleAttribute() { + if(radioInputTypeElement){ + for (var i = 0; i < radioInputTypeElement.length; i++) { + if (b2bUserAgent.notMobile() || (radioProductSelectElement && radioProductSelectElement.length > 0) ) { + angular.element(roleRadioElement[i]).attr("role","radio"); + } + } + } + } + + function radioStateChangeonClick() { + for (var i = 0; i < radioInputTypeElement.length; i++) { + var isChecked = radioInputTypeElement[i].checked ? 'true' : 'false'; + var isDisabled = radioInputTypeElement[i].disabled ? 'true' : 'false'; + if (radioProductSelectElement.length) { + isChecked === 'true' ? angular.element(radioProductSelectElement[i]).addClass('active') : angular.element(radioProductSelectElement[i]).removeClass('active'); + } + angular.element(roleRadioElement[i]).attr({ + 'aria-checked': isChecked, + 'aria-disabled': isDisabled + }); + } + + } + } + } + +}]); + +/** + * @ngdoc directive + * @name Misc.att:reorderList + * + * @description + * + * + * @param {int} currentIndex - Current index of focussed list item. + * @param {Array} listData - Data of list items. Should include full data regardless if HTML will be filtered. + + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.reorderList', ['b2b.att.utilities']) +.directive('b2bReorderList', ['keymap', 'b2bDOMHelper', '$rootScope','$timeout','$document', function(keymap, b2bDOMHelper, $rootScope, $timeout, $document) { + return { + restrict: 'AE', + transclude: true, + replace: true, + scope: { + currentIndex: '=', + listData: '=' + }, + templateUrl: 'b2bTemplate/reorderList/reorderList.html', + link: function(scope, elem, attr) { + //in case of a filter, scope.listboxData array holds only the filtered items + // removal/readdition of items while filtering is handled in b2bReorderListItem directive + scope.listboxData = []; + scope.backup = angular.copy(scope.listData); + if (attr.ariaMultiselectable !== undefined || attr.ariaMultiselectable === 'true') { + scope.multiselectable = true; + } else { + scope.multiselectable = false; + } + + var shiftKey = false; + var elements = []; + var prevDirection = undefined; // previous direction is used for an edge case when shifting + var shiftKeyPressed = false; // Used to handle shift clicking + var ctrlKeyPressed = false; + scope.firstAvailableIndex = 0; + + function isSelected(item) { + if (item.selected === true ) { + return true; + } + } + var firstSelected,lastSelected,firstAvailable,lastAvailable; + scope.moveUp = false; + scope.moveDown = false; + scope.init = function(){ + scope.$parent.selectedCount = 0; + firstSelected=-1; + lastSelected=-1; + firstAvailable=-1; + lastAvailable =-1; + scope.$parent.selectedCount =0; + scope.lastAvailableIndex= scope.listboxData.length-1; + for(var i=0;ifirstAvailable && firstAvailable != -1){ + scope.moveUp = true; + }else{ + scope.moveUp = false; + } + if(firstSelected=0;i--){ + if(scope.listboxData[i].selected == val){ + return i; + } + } + return -1; + } + } + + function enableButton(index,selected){ + if(selected){ + if(indexlastSelected || lastSelected ==-1){ + lastSelected =index; + } + if(index == lastAvailable){ + lastAvailable = get('last',false); + } + }else{ + if(indexlastAvailable || lastAvailable ==-1){ + lastAvailable =index; + } + if(index == lastSelected){ + lastSelected = get('last',true); + } + } + if(lastSelected>firstAvailable && firstAvailable != -1){ + scope.moveUp = true; + }else{ + scope.moveUp = false; + } + if(firstSelected-1){ + elem.children().eq(0).children()[parseInt(attr.fixedOptions)+scope.currentIndex].focus(); + } + }); + /*elem.children().eq(0).bind('mouseover', function(evt) { + var index = parseInt(evt.target.parentElement.getAttribute("index"), 10); + if (index === undefined || isNaN(index)) { + return; + } + scope.currentIndex = index; + + if (!scope.$$phase) { + scope.$apply(); + } + });*/ + /* elem.children().eq(0).bind('mouseleave', function(evt) { + scope.currentIndex = -1; + if (!scope.$$phase) { + scope.$apply(); + } + });*/ + elem.children().eq(0).bind('keyup', function(evt) { + if (evt.keyCode === keymap.KEY.SHIFT) { + shiftKeyPressed = false; + } else if (evt.keyCode === keymap.KEY.CTRL) { + ctrlKeyPressed = false; + } + }); + + var lastSelected = 0; + elem.children().eq(0).bind('click', function(evt) { + var index = parseInt(evt.target.parentElement.getAttribute("index"), 10); + if (index === undefined || isNaN(index)) { + return; + } + if (shiftKeyPressed) { + selectItems(Math.min(index, lastSelected), Math.max(index, lastSelected)+1, true); + } else if (ctrlKeyPressed) { + if(scope.listboxData[index].selected){ + scope.$parent.selectedCount--; + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[index].selected = !scope.listboxData[index].selected; + firstSelected = -1; + lastSelected = -1; + for(var i = 0 ;i -1 ? startIndex : 0; + for (var index = startIndex; index < scope.listboxData.length; index++) { + if (scope.listboxData[index][prop].toString().match(regex) ){ + return index; + } + } + for (var index = 0; index < startIndex; index++) { + if (scope.listboxData[index][prop].toString().match(regex)) { + return index; + } + } + return -1; + } + + var timerPromise,searchString="" ; + + elem.children().eq(0).bind('keydown', function(evt) { + var keyCode = evt.keyCode; + if (keyCode === keymap.KEY.SHIFT) { + shiftKeyPressed = true; + } else if (evt.keyCode === keymap.KEY.CTRL) { + ctrlKeyPressed = true; + } + + if(((keyCode >=65 && keyCode<=90) || (keyCode >=97 && keyCode<=122) ||(keyCode >=48 && keyCode<=57)) && !evt.ctrlKey){ + searchString += keymap.MAP[keyCode]; + var regex = new RegExp("^" + searchString, "i"); + var next = getNext(regex,'title',parseInt(scope.currentIndex)+1); + if(next != -1){ + scope.currentIndex = next; + } + if(timerPromise){ + $timeout.cancel(timerPromise); + } + timerPromise = $timeout (function(){ + searchString =""; + },600,false); + if (!scope.$$phase) { + scope.$apply(); + } + } + switch(keyCode) { + case 65: // A key + { + if (scope.multiselectable && evt.ctrlKey) { + var arr = scope.listboxData.filter(isSelected); + var val = !(arr.length === scope.listboxData.length); + selectItems(0,scope.listboxData.length,val); + + evt.preventDefault(); + evt.stopPropagation(); + + if (!scope.$$phase) { + scope.$apply(); + } + } + break; + } + case keymap.KEY.END: + { + if (scope.multiselectable && evt.ctrlKey && evt.shiftKey) { + selectItems(scope.currentIndex,scope.listboxData.length,true); + }else{ + scope.currentIndex = scope.lastAvailableIndex; + } + evt.preventDefault(); + evt.stopPropagation(); + if (!scope.$$phase) { + scope.$apply(); + } + break; + } + case keymap.KEY.HOME: + { + if (scope.multiselectable && evt.ctrlKey && evt.shiftKey) { + selectItems(0,scope.currentIndex+1,true); + }else{ + scope.currentIndex = scope.firstAvailableIndex; + } + evt.preventDefault(); + evt.stopPropagation(); + + if (!scope.$$phase) { + scope.$apply(); + } + break; + } + case keymap.KEY.LEFT: + case keymap.KEY.UP: + { + if (scope.currentIndex == scope.firstAvailableIndex) { + evt.preventDefault(); + evt.stopPropagation(); + return; + } + scope.currentIndex--; + + if (scope.multiselectable && (evt.shiftKey )) { + + if (prevDirection === 'DOWN') { + if(scope.listboxData[scope.currentIndex+1].selected){ + scope.$parent.selectedCount--; + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[scope.currentIndex+1].selected = !scope.listboxData[scope.currentIndex+1].selected; + enableButton(scope.currentIndex+1, scope.listboxData[scope.currentIndex+1].selected); + } + if(scope.listboxData[scope.currentIndex].selected){ + scope.$parent.selectedCount--; + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[scope.currentIndex].selected = !scope.listboxData[scope.currentIndex].selected; + enableButton(scope.currentIndex, scope.listboxData[scope.currentIndex].selected); + prevDirection = 'UP'; + } + + if(!scope.$$phase) { + scope.$apply(); + } + evt.preventDefault(); + evt.stopPropagation(); + break; + } + case keymap.KEY.RIGHT: + case keymap.KEY.DOWN: + { + if (scope.currentIndex == scope.lastAvailableIndex) { + evt.preventDefault(); + evt.stopPropagation(); + return; + } + scope.currentIndex++; + if (scope.multiselectable && evt.shiftKey) { + enableButton(scope.currentIndex,scope.listboxData[scope.currentIndex].selected); + if (prevDirection === 'UP') { + if(scope.listboxData[scope.currentIndex-1].selected){ + scope.$parent.selectedCount--; + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[scope.currentIndex-1].selected = !scope.listboxData[scope.currentIndex-1].selected; + enableButton(scope.currentIndex-1,scope.listboxData[scope.currentIndex-1].selected); + } + if(scope.listboxData[scope.currentIndex].selected){ + scope.$parent.selectedCount--; + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[scope.currentIndex].selected = !scope.listboxData[scope.currentIndex].selected; + enableButton(scope.currentIndex,scope.listboxData[scope.currentIndex].selected); + prevDirection = 'DOWN'; + } + + if(!scope.$$phase) { + scope.$apply(); + } + evt.preventDefault(); + evt.stopPropagation(); + break; + } + case keymap.KEY.SPACE: + if (scope.multiselectable){ + if(scope.listboxData[scope.currentIndex].selected){ + scope.$parent.selectedCount--; + + }else{ + scope.$parent.selectedCount++; + } + scope.listboxData[scope.currentIndex].selected = !scope.listboxData[scope.currentIndex].selected; + enableButton(scope.currentIndex,scope.listboxData[scope.currentIndex].selected); + } + if(!scope.$$phase) { + scope.$apply(); + } + evt.preventDefault(); + evt.stopPropagation(); + break; + case keymap.KEY.TAB: + if(evt.shiftKey) { + var previousElement = b2bDOMHelper.previousElement(elem.parent().parent(), true); + evt.preventDefault(); + previousElement.focus(); + } + scope.currentIndex =-1; + if(!scope.$$phase) { + scope.$apply(); + } + break; + default: + break; + } + }); + + }, + controller : ['$scope',function($scope){ + function swap (from,to){ + var temp = $scope.listboxData[from],j = $scope.listboxData[from].parentIndex,k=$scope.listboxData[to].parentIndex; + $scope.listboxData[from] = $scope.listboxData[to]; + $scope.listboxData[to] = temp; + temp = $scope.listData[j]; + $scope.listData[j] = $scope.listData[k]; + $scope.listData[k] = temp; + $scope.listboxData[to].parentIndex = k; + $scope.listboxData[from].parentIndex = j; + } + function handleFilter(temp){ + var filteredIndices = []; + var i =0; + for(;i<$scope.listData.length;i++){ + if(!$scope.listData[i].notFiltered){ + filteredIndices.push(i); + } + } + for(i=0;i=0;i--){ + if($scope.listData[i].selected){ + if($scope.listData[i+1] == undefined || $scope.listData[i+1].selected==true){ + continue; + } + swap(i,i+1); + } + } + $scope.init(); + if($scope.moveDown == false){ + document.getElementById('resetLink').focus(); + } + }else if (to == 'top'){ + var temp=[]; + for(var i=$scope.listboxData.length-1,j=0;i>=0;i--,j++){ + if($scope.listboxData[i].selected){ + temp.unshift($scope.listboxData[i]); + } + if(!$scope.listboxData[j].selected ){ + temp.push($scope.listboxData[j]); + } + } + $scope.listboxData=temp; + temp=[]; + for(var i=0;i<$scope.listboxData.length;i++){ + temp.push($scope.listData[$scope.listboxData[i].parentIndex]); + } + handleFilter(temp); + $scope.listData = temp; + $scope.init(); + if($scope.moveUp == false && $scope.moveDown == false){ + document.getElementById('resetLink').focus(); + }else if($scope.moveUp == false && $scope.moveDown){ + document.getElementById('moveDown').focus(); + } + }else if (to == 'bottom'){ + var temp=[]; + for(var i=$scope.listboxData.length-1,j=0;i>=0;i--,j++){ + if(!$scope.listboxData[i].selected ){ + temp.unshift($scope.listboxData[i]); + } + if($scope.listboxData[j].selected){ + temp.push($scope.listboxData[j]); + } + } + $scope.listboxData=temp; + temp=[]; + for(var i=0;i<$scope.listboxData.length;i++){ + temp.push($scope.listData[$scope.listboxData[i].parentIndex]); + } + handleFilter(temp); + $scope.listData = temp; + $scope.init(); + if($scope.moveDown == false){ + document.getElementById('resetLink').focus(); + } + } + }; + $scope.reset = function(){ + $scope.listboxData = []; + $scope.listData = angular.copy($scope.backup); + $scope.init(); + }; + + }] + }; + }]) + .directive('b2bReorderListItem',function(){ + return{ + restrict: 'A', + scope:false, + link : function(scope,elem,attr){ + // This directive stabilizes data if a filter is applied by the developers + function resetParentIndex(arr,parent){ + for(var i=0;i + * + * @usage + *
    + * + * @example +
    + + + + +
    + */ + +angular.module('b2b.att.searchField', ['b2b.att.utilities', 'b2b.att.position']) + .filter('b2bFilterInput', [function() { + return function(list, str, keyArray, displayListKey, isContainsSearch, searchSeperator) { + var res = []; + var searchLabel; + var searchCondition; + var conditionCheck = function(searchSeperator, listItem, displayListKey, splitString) { + var displayTitle = null; + if (splitString) { + for (var i = 0; i < displayListKey.length; i++) { + if (i <= 0) { + displayTitle = listItem[displayListKey[i]].toLowerCase().indexOf(splitString[i].toLowerCase()) > -1; + } else { + displayTitle = (splitString[i]) ? displayTitle && listItem[displayListKey[i]].toLowerCase().indexOf(splitString[i].toLowerCase().trim()) > -1 : displayTitle; + } + } + } else { + angular.forEach(displayListKey, function(value) { + if (!displayTitle) { + displayTitle = listItem[value]; + } else { + displayTitle = displayTitle + (listItem[value] ? searchSeperator + ' ' + listItem[value] : ''); + } + }); + } + return displayTitle; + } + angular.forEach(list, function(listItem) { + var splitString = str.indexOf(searchSeperator) > -1 ? str.split(searchSeperator) : false; + var displayList = conditionCheck(searchSeperator, listItem, displayListKey, splitString) + for (var i = 0; i < keyArray.length; i++) { + searchLabel = keyArray[i]; + if (listItem[searchLabel]) { + if (isContainsSearch) { + var displaySearchList = listItem[searchLabel].toLowerCase().indexOf(str.toLowerCase()) > -1; + if (splitString.length > 1) { + displaySearchList = (splitString.length <= keyArray.length) ? displayList : false; + } + searchCondition = displaySearchList; + } else { + searchCondition = listItem[searchLabel].match(new RegExp('^' + str, 'gi')); + } + if (searchCondition) { + res.push({ + 'title': conditionCheck(searchSeperator, listItem, displayListKey), + 'valueObj': listItem + }); + break; + } + } + } + }); + return res; + }; + }]).directive('b2bSearchField', ['$filter', 'b2bFilterInputFilter', 'keymap', '$documentBind', '$isElement', '$document', 'events', '$timeout', function($filter, b2bFilterInput, keymap, $documentBind, $isElement, $document, events, $timeout) { + return { + restrict: 'A', + scope: { + dataList: '=dropdownList', + onClickCallback: '&', + inputModel: '=', + configObj: '=', + objModel: '=', + inputDeny: '=?', + disabled: '=?' + }, + replace: true, + templateUrl: 'b2bTemplate/searchField/searchField.html', + controller: ['$scope', function($scope) { + this.searchKeyArray = []; + if ($scope.configObj.searchKeys) { + this.searchKeyArray = $scope.configObj.searchKeys; + } + if (angular.isUndefined($scope.disabled)) { + $scope.disabled = false; + } + this.triggerInput = function(searchString) { + $scope.originalInputModel = searchString; + if (searchString === '') { + $scope.currentIndex = -1; + $scope.filterList = []; + $scope.showListFlag = false; + } else if (searchString !== '' && !$scope.isFilterEnabled) { + $scope.filterList = $filter('b2bFilterInput')($scope.dataList, searchString, this.searchKeyArray, $scope.configObj.displayListDataKey, $scope.configObj.isContainsSearch, $scope.configObj.searchSeperator); + $scope.showListFlag = true; + } + }; + this.denyRegex = function() { + return $scope.inputDeny; + }; + }], + link: function(scope, elem) { + scope.isFilterEnabled = false; + scope.showListFlag = false; + scope.currentIndex = -1; + scope.setCurrentIdx = function(idx) { + scope.currentIndex = idx; + if (idx > -1) { + scope.inputModel = scope.filterList[idx].title; + scope.objModel = scope.filterList[idx]; + } + }; + scope.isActive = function(index, dropdownLength) { + scope.dropdownLength = dropdownLength; + return scope.currentIndex === index; + }; + scope.selectItem = function(idx) { + scope.setCurrentIdx(idx); + scope.onClickCallback({ + value: scope.inputModel, + objValue: scope.objModel + }); + scope.showListFlag = false; + $timeout(function() { + elem.find('div').find('input')[0].focus(); + }, 150); + }; + scope.startSearch = function() { + scope.onClickCallback({ + value: scope.inputModel, + objValue: scope.objModel + }); + }; + var maxItemsLength = 9; + scope.selectPrev = function() { + if (scope.currentIndex > 0 && scope.filterList.length > 0) { + // Scroll fix: Ensure we move down the ul's scrollTop by one element's pixels worth + // Checking if its less than 9 because in our suggestion list we only have height set to show max 10 elements + if (scope.currentIndex - 1 <= maxItemsLength) { + var ulElem = elem.find('ul'); + ulElem[0].scrollTop -= 40; // 40 px + ulElem[0].scrollTop = Math.max(ulElem[0].scrollTop, 0); + } + scope.currentIndex = scope.currentIndex - 1; + scope.setCurrentIdx(scope.currentIndex); + } else if (scope.currentIndex === 0) { + scope.currentIndex = scope.currentIndex - 1; + scope.inputModel = scope.originalInputModel; + scope.isFilterEnabled = true; + } + }; + scope.selectNext = function() { + if (scope.currentIndex < scope.configObj.noOfItemsDisplay - 1) { + if (scope.currentIndex < scope.filterList.length - 1) { + // Scroll fix: Ensure we move the ul's scrollTop by one element's pixels worth + // Checking if its greater than 9 because in our suggestion list we only have height set to show max 10 elements + if (scope.currentIndex + 1 >= maxItemsLength) { + var ulElem = elem.find('ul'); + ulElem[0].scrollTop += 40; // 40 px + } + scope.currentIndex = scope.currentIndex + 1; + scope.setCurrentIdx(scope.currentIndex); + } + } + }; + scope.selectCurrent = function() { + scope.selectItem(scope.currentIndex); + }; + scope.selectionIndex = function(e) { + switch (e.keyCode) { + case keymap.KEY.DOWN: + events.preventDefault(e); + scope.isFilterEnabled = true; + scope.selectNext(); + break; + case keymap.KEY.UP: + events.preventDefault(e); + scope.isFilterEnabled = true; + scope.selectPrev(); + break; + case keymap.KEY.ENTER: + events.preventDefault(e); + scope.isFilterEnabled = true; + scope.selectCurrent(); + break; + case keymap.KEY.ESC: + events.preventDefault(e); + scope.isFilterEnabled = false; + scope.showListFlag = false; + scope.inputModel = ''; + break; + default: + scope.isFilterEnabled = false; + break; + } + if (elem[0].querySelector('.filtercontainer')) { + elem[0].querySelector('.filtercontainer').scrollTop = (scope.currentIndex - 1) * 35; + } + }; + scope.$watch('filterList', function(newVal, oldVal) { + if (newVal !== oldVal) { + scope.currentIndex = -1; + } + }); + scope.blurInput = function() { + $timeout(function() { + scope.showListFlag = false; + }, 150); + }; + var outsideClick = function(e) { + var isElement = $isElement(angular.element(e.target), elem.find('ul').eq(0), $document); + if (!isElement && document.activeElement.tagName.toLowerCase() !== 'input') { + scope.showListFlag = false; + scope.$apply(); + } + }; + $documentBind.click('showListFlag', outsideClick, scope); + } + }; + }]) + .directive('b2bSearchInput', [function() { + return { + restrict: 'A', + require: ['ngModel', '^b2bSearchField'], + link: function(scope, elem, attr, ctrl) { + var ngModelCtrl = ctrl[0]; + var attSearchBarCtrl = ctrl[1]; + var REGEX = ctrl[1].denyRegex(); + var parser = function(viewValue) { + attSearchBarCtrl.triggerInput(viewValue); + return viewValue; + }; + ngModelCtrl.$parsers.push(parser); + + if (REGEX !== undefined || REGEX !== '') { + elem.bind('input', function() { + var inputString = ngModelCtrl.$viewValue && ngModelCtrl.$viewValue.replace(REGEX, ''); + if (inputString !== ngModelCtrl.$viewValue) { + ngModelCtrl.$setViewValue(inputString); + ngModelCtrl.$render(); + scope.$apply(); + } + }); + } + } + }; + }]) + .directive('b2bSearchFieldInput', ['$filter', 'b2bFilterInputFilter', 'keymap', '$documentBind', '$isElement', '$document', 'events', '$timeout', function($filter, b2bFilterInput, keymap, $documentBind, $isElement, $document, events, $timeout) { + return { + restrict: 'A', + require: ['ngModel'], + scope: { + dataList: '=dropdownList', + configObj: '=', + }, + controller: ['$scope', function($scope) { + + }], + link: function(scope, elem, attr, ctrl) { + this.searchKeyArray = []; + this.showAllOptions = false; + if (scope.configObj.searchKeys) { + this.searchKeyArray = scope.configObj.searchKeys; + } + if (!angular.isUndefined(scope.configObj.showAllOptions)) { + this.showAllOptions = scope.configObj.showAllOptions; + } + this.triggerInput = function(searchString) { + if (angular.isUndefined(searchString)) { + searchString = ''; + } + scope.configObj.originalInputModel = searchString; + if (searchString === '' && !scope.configObj.showAllOptions) { + scope.configObj.filterList = []; + scope.configObj.showListFlag = false; + } else if (searchString !== '' && !scope.isFilterEnabled || (scope.configObj.showAllOptions)) { + scope.configObj.filterList = $filter('b2bFilterInput')(scope.dataList, searchString, this.searchKeyArray, scope.configObj.displayListDataKey, scope.configObj.isContainsSearch, scope.configObj.searchSeperator); + scope.configObj.showListFlag = true; + } + }; + var ngModelCtrl = ctrl[0]; + if(this.showAllOptions){ + elem.bind('focus', function() { + viewValue = ngModelCtrl.$viewValue; + if (angular.isUndefined(viewValue)) { + viewValue = ''; + } + triggerInput(viewValue); + scope.$apply(); + }); + } + var parser = function(viewValue) { + triggerInput(viewValue); + return viewValue; + }; + ngModelCtrl.$parsers.push(parser); + } + }; + }]); + +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:Seek bar + * + * @description + * + * + * @usage + * Horizontal Seek Bar + * + + * Vertical Seek Bar + * + * + * @example +
    + HTML + AngularJS + + + + +
    + */ + +angular.module('b2b.att.seekBar', ['b2b.att.utilities','b2b.att.position']) + .constant('b2bSeekBarConfig', { + 'min': 0, + 'max': 100, + 'step': 1, + 'skipInterval': 1 + }) + .directive('b2bSeekBar', ['$documentBind', 'events', 'b2bSeekBarConfig', 'keymap', '$compile', function($documentBind, events, b2bSeekBarConfig, keymap, $compile) { + return { + restrict: 'AE', + replace: true, + require: 'ngModel', + templateUrl: 'b2bTemplate/seekBar/seekBar.html', + scope: { + onDragEnd: '&?', + onDragInit: '&?' + }, + link: function(scope, elm, attr, ngModelCtrl) { + scope.isDragging = false; + scope.verticalSeekBar = false; + var min; + var max; + var step = b2bSeekBarConfig.step; + var skipInterval = b2bSeekBarConfig.skipInterval; + var knob = angular.element(elm[0].querySelector('.b2b-seek-bar-knob-container')); + var seekBarKnob = angular.element(knob[0].querySelector('.b2b-seek-bar-knob')); + var trackContainer = angular.element(elm[0].querySelector('.b2b-seek-bar-track-container')); + var trackFill = angular.element(elm[0].querySelector('.b2b-seek-bar-track-fill')); + var trackContainerRect = {}; + var axisPosition; + var trackFillOrderPositioning; + + if (angular.isDefined(attr.vertical)) { + scope.verticalSeekBar = true; + axisPosition = "clientY"; + } + else { + scope.verticalSeekBar = false; + axisPosition = "clientX"; + } + var getValidStep = function(val) { + val = parseFloat(val); + // in case $modelValue came in string number + if (angular.isNumber(val)) { + val = Math.round((val - min) / step) * step + min; + return Math.round(val * 1000) / 1000; + } + }; + + var getPositionToPercent = function(x) { + if (scope.verticalSeekBar) { + return Math.max(0, Math.min(1, (trackContainerRect.bottom - x) / (trackFillOrderPositioning))); + } + else { + return Math.max(0, Math.min(1, (x - trackContainerRect.left) / (trackFillOrderPositioning))); + } + }; + + var getPercentToValue = function(percent) { + return (min + percent * (max - min)); + }; + + var getValueToPercent = function(val) { + return (val - min) / (max - min); + }; + + var getValidMinMax = function(val) { + return Math.max(min, Math.min(max, val)); + }; + + var updateTrackContainerRect = function() { + trackContainerRect = trackContainer[0].getBoundingClientRect(); + if (scope.verticalSeekBar) { + if (!trackContainerRect.height) { + trackFillOrderPositioning = trackContainer[0].scrollHeight; + } else { + trackFillOrderPositioning = trackContainerRect.height; + } + } + else { + if (!trackContainerRect.width) { + trackFillOrderPositioning = trackContainer[0].scrollWidth; + } else { + trackFillOrderPositioning = trackContainerRect.width; + } + + } + + }; + + var updateKnobPosition = function(percent) { + var percentStr = (percent * 100) + '%'; + if (scope.verticalSeekBar) { + knob.css('bottom', percentStr); + trackFill.css('height', percentStr); + } + else { + knob.css('left', percentStr); + trackFill.css('width', percentStr); + } + }; + + var modelRenderer = function() { + if (isNaN(ngModelCtrl.$viewValue)) { + ngModelCtrl.$viewValue = ngModelCtrl.$modelValue || min; + } + + var viewVal = ngModelCtrl.$viewValue; + scope.currentModelValue = viewVal; + + //wait for min, max and step to be set then only update UI to avoid NaN on percent calculation + if ((min || min === 0) && max && step) { + updateKnobPosition(getValueToPercent(viewVal)); + } + }; + + var setModelValue = function(val) { + scope.currentModelValue = getValidMinMax(getValidStep(val)); + ngModelCtrl.$setViewValue(scope.currentModelValue); + }; + + var updateMin = function(val) { + min = parseFloat(val); + if(isNaN(min)){ + min = b2bSeekBarConfig.min; + } + modelRenderer(); + }; + + var updateMax = function(val) { + max = parseFloat(val); + if(isNaN(max)){ + max = b2bSeekBarConfig.max; + } + modelRenderer(); + }; + + var updateStep = function(val) { + step = parseFloat(val); + if (!attr['skipInterval']) { + skipInterval = step; + } + }; + + var updateSkipInterval = function(val) { + skipInterval = step * Math.ceil(val / (step!==0?step:1)); + }; + + angular.isDefined(attr.min) ? attr.$observe('min', updateMin) : updateMin(b2bSeekBarConfig.min); + angular.isDefined(attr.max) ? attr.$observe('max', updateMax) : updateMax(b2bSeekBarConfig.max); + if (angular.isDefined(attr.step)) { + attr.$observe('step', updateStep); + } + if (angular.isDefined(attr.skipInterval)) { + attr.$observe('skipInterval', updateSkipInterval); + } + scope.currentModelValue = getValidMinMax(getValidStep(min)); + var onMouseDown = function(e) { + switch (e.which) { + case 1: + // left mouse button + break; + case 2: + case 3: + // right or middle mouse button + return; + } + ; + + scope.isDragging = true; + seekBarKnob[0].focus(); + updateTrackContainerRect(); + if (attr['onDragInit']) { + scope.onDragInit(); + } + events.stopPropagation(e); + events.preventDefault(e); + scope.$apply(function() { + setModelValue(getPercentToValue(getPositionToPercent(e[axisPosition]))); + }); + }; + + var onMouseUp = function() { + + if (attr['onDragEnd']) { + scope.onDragEnd(); + } + scope.isDragging = false; + scope.$digest(); + }; + + var onMouseMove = function(e) { + if (scope.isDragging) { + events.stopPropagation(e); + events.preventDefault(e); + + scope.$apply(function() { + setModelValue(getPercentToValue(getPositionToPercent(e[axisPosition]))); + }); + } + }; + + function onKeyDown(e) { + if (!(e.keyCode)) { + e.keyCode = e.which; + } + var updateStep; + switch (e.keyCode) { + case keymap.KEY.LEFT: + if (!scope.verticalSeekBar) { + updateStep = -skipInterval; + } + break; + case keymap.KEY.RIGHT: + if (!scope.verticalSeekBar) { + updateStep = skipInterval; + } + break; + case keymap.KEY.UP: + if (scope.verticalSeekBar) { + updateStep = skipInterval; + } + break; + case keymap.KEY.DOWN: + if (scope.verticalSeekBar) { + updateStep = -skipInterval; + } + break; + default: + return; + } + + if (updateStep) { + events.stopPropagation(e); + events.preventDefault(e); + scope.$apply(function() { + setModelValue(ngModelCtrl.$viewValue + updateStep); + }); + if (attr['onDragEnd']) { + scope.onDragEnd(); + } + } + } + + elm.on('keydown', onKeyDown); + elm.on('mousedown', onMouseDown); + + $documentBind.event('mousemove', 'isDragging', onMouseMove, scope, true, 0); + $documentBind.event('mouseup', 'isDragging', onMouseUp, scope, true, 0); + + ngModelCtrl.$render = function() { + if (!scope.isDragging) { + modelRenderer(); + } + }; + ngModelCtrl.$viewChangeListeners.push(modelRenderer); + ngModelCtrl.$formatters.push(getValidMinMax); + ngModelCtrl.$formatters.push(getValidStep); + } + }; + }]); +/** + * @ngdoc directive + * @name Layouts.att:separators + * + * @description + * + * + * @usage + + * + * @example + *
    + HTML + AngularJS + + + + +
    + * + */ + +angular.module('b2b.att.separators', []); +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:slider + * + * @description + * + * + * @usage + * + * + * @example +
    + HTML + AngularJS + + + + +
    + */ + +angular.module('b2b.att.slider', ['b2b.att.utilities']) + .constant('SliderConfig', { + 'min': 0, + 'max': 100, + 'step': 1, + 'skipInterval': 1 + }) + .directive('b2bSlider', ['$documentBind', 'SliderConfig', 'keymap', '$compile', '$log', function($documentBind, SliderConfig, keymap, $compile, $log) { + return { + restrict: 'AE', + replace: true, + require: 'ngModel', + templateUrl: 'b2bTemplate/slider/slider.html', + scope: { + onDragEnd: '&?', + onDragInit: '&?', + trackFillColor: '=?', + preAriaLabel: '=?', + postAriaLabel: '=?', + onRenderEnd: '&?', + sliderSnapPoints: '=?', + customAriaLabel: '=?', + labelId: '@?' + }, + link: function(scope, elm, attr, ngModelCtrl) { + scope.isDragging = false; + scope.verticalSlider = false; + scope.isSliderDisabled = true; + var min; + var max; + var step = SliderConfig.step; + var skipInterval = SliderConfig.skipInterval; + var knob = angular.element(elm[0].querySelector('.slider-knob-container')); + var sliderKnob = angular.element(knob[0].querySelector('.slider-knob')); + var trackContainer = angular.element(elm[0].querySelector('.slider-track-container')); + var trackFill = angular.element(elm[0].querySelector('.slider-track-fill')); + var trackContainerRect = {}; + var axisPosition = "clientX"; + var trackFillOrderPositioning; + + //Forcefully disabling the vertical Slider code. + if (angular.isDefined(attr.vertical)) { + scope.verticalSlider = true; + axisPosition = "clientY"; + } + + if (angular.isDefined(scope.noAriaLabel) && scope.noAriaLabel !== '') { + $log.warn('no-aria-label has been deprecated. This will be removed in v0.6.0.'); + } + if (angular.isDefined(scope.preAriaLabel) && scope.preAriaLabel !== '') { + $log.warn('pre-aria-label has been deprecated. Please use label-id instead. This will be removed in v0.6.0.'); + } + if (angular.isDefined(scope.customAriaLabel) && scope.customAriaLabel !== '') { + $log.warn('custom-aria-label has been deprecated. Please use label-id and post-aria-label instead. This will be removed in v0.6.0.'); + } + + var binarySearchNearest = function (num, arr) { + var mid; + var lo = 0; + var hi = arr.length - 1; + + while (hi - lo > 1) { + mid = Math.floor((lo + hi) / 2); + if (arr[mid] < num) { + lo = mid; + } else { + hi = mid; + } + } + if (num - arr[lo] < arr[hi] - num) { + return arr[lo]; + } + return arr[hi]; + }; + + var getValidStep = function(val) { + val = parseFloat(val); + // in case $modelValue came in string number + if (!isNaN(val)) { + + if(attr['sliderSnapPoints'] && scope.sliderSnapPoints.length > 0) { + val = binarySearchNearest(val, scope.sliderSnapPoints); + } + else { + val = Math.round((val - min) / step) * step + min; + } + + return Math.round(val * 1000) / 1000; + } + }; + + var getPositionToPercent = function(x) { + if (scope.verticalSlider) { + return Math.max(0, Math.min(1, (trackContainerRect.bottom - x) / (trackFillOrderPositioning))); + } + else { + return Math.max(0, Math.min(1, (x - trackContainerRect.left) / (trackFillOrderPositioning))); + } + }; + + var getPercentToValue = function(percent) { + return (min + percent * (max - min)); + }; + + var getValueToPercent = function(val) { + return (val - min) / (max - min); + }; + + var getValidMinMax = function(val) { + return Math.max(min, Math.min(max, val)); + }; + + var updateTrackContainerRect = function() { + trackContainerRect = trackContainer[0].getBoundingClientRect(); + if (scope.verticalSlider) { + if (!trackContainerRect.height) { + trackFillOrderPositioning = trackContainer[0].scrollHeight; + } else { + trackFillOrderPositioning = trackContainerRect.height; + } + } + else { + if (!trackContainerRect.width) { + trackFillOrderPositioning = trackContainer[0].scrollWidth; + } else { + trackFillOrderPositioning = trackContainerRect.width; + } + + } + + }; + + var updateKnobPosition = function(percent) { + var percentStr = (percent * 100) + '%'; + if (scope.verticalSlider) { + knob.css('bottom', percentStr); + trackFill.css('height', percentStr); + } + else { + knob.css('left', percentStr); + trackFill.css('width', percentStr); + } + }; + + var modelRenderer = function() { + + if(attr['disabled']){ + return; + } + + if (isNaN(ngModelCtrl.$viewValue)) { + ngModelCtrl.$viewValue = ngModelCtrl.$modelValue || min; + } + + var viewVal = ngModelCtrl.$viewValue; + scope.currentModelValue = viewVal; + + //wait for min, max and step to be set then only update UI to avoid NaN on percent calculation + if ((min || min === 0) && max && step) { + updateKnobPosition(getValueToPercent(viewVal)); + } + }; + + var setModelValue = function(val) { + scope.currentModelValue = getValidMinMax(getValidStep(val)); + ngModelCtrl.$setViewValue(scope.currentModelValue); + }; + + var updateMin = function(val) { + min = parseFloat(val); + if(isNaN(min)){ + min = SliderConfig.min; + } + scope.min = min; + modelRenderer(); + }; + + var updateMax = function(val) { + max = parseFloat(val); + if(isNaN(max)){ + max = SliderConfig.max; + } + scope.max = max; + modelRenderer(); + }; + + var updateStep = function(val) { + step = parseFloat(val); + if (!attr['skipInterval']) { + skipInterval = step; + } + }; + + var updateSkipInterval = function(val) { + skipInterval = step * Math.ceil(val / (step!==0?step:1)); + }; + + angular.isDefined(attr.min) ? attr.$observe('min', updateMin) : updateMin(SliderConfig.min); + angular.isDefined(attr.max) ? attr.$observe('max', updateMax) : updateMax(SliderConfig.max); + if (angular.isDefined(attr.step)) { + attr.$observe('step', updateStep); + } + if (angular.isDefined(attr.skipInterval)) { + attr.$observe('skipInterval', updateSkipInterval); + } + scope.currentModelValue = getValidMinMax(getValidStep(min)); + var onMouseDown = function(e) { + + if(attr['disabled']){ + return; + } + + switch (e.which) { + case 1: + // left mouse button + break; + case 2: + case 3: + // right or middle mouse button + return; + } + + scope.isDragging = true; + sliderKnob[0].focus(); + updateTrackContainerRect(); + if (attr['onDragInit']) { + scope.onDragInit(); + } + e.stopPropagation(); + e.preventDefault(); + scope.$apply(function() { + if(e.type === "touchmove" || e.type === "touchend"){ + setModelValue(getPercentToValue(getPositionToPercent(e.touches[0][axisPosition]))); + }else{ + setModelValue(getPercentToValue(getPositionToPercent(e[axisPosition]))); + } + + }); + }; + + var onKnobMouseDown = function(e) { + + if(attr['disabled']){ + return; + } + + switch (e.which) { + case 1: + // left mouse button + break; + case 2: + case 3: + // right or middle mouse button + return; + } + + scope.isDragging = true; + sliderKnob[0].focus(); + updateTrackContainerRect(); + if (attr['onDragInit']) { + scope.onDragInit(); + } + e.stopPropagation(); + e.preventDefault(); + scope.$apply(function() { + if(e.type === "touchmove" || e.type === "touchend"){ + setModelValue(getPercentToValue(getPositionToPercent(e.touches[0][axisPosition]))); + }else{ + setModelValue(getPercentToValue(getPositionToPercent(e[axisPosition]))); + } + + }); + }; + + var onMouseUp = function() { + + if (attr['onDragEnd']) { + scope.onDragEnd(); + } + scope.isDragging = false; + scope.$digest(); + }; + + var onMouseMove = function(e) { + if (scope.isDragging) { + e.stopPropagation(); + e.preventDefault(); + + scope.$apply(function() { + if(e.type === "touchmove"){ + setModelValue(getPercentToValue(getPositionToPercent(e.touches[0][axisPosition]))); + }else{ + setModelValue(getPercentToValue(getPositionToPercent(e[axisPosition]))); + } + }); + } + }; + + function onKeyDown(e) { + if (!(e.keyCode)) { + e.keyCode = e.which; + } + var updateStep; + switch (e.keyCode) { + case keymap.KEY.DOWN: + case keymap.KEY.LEFT: + if(attr['sliderSnapPoints'] && scope.sliderSnapPoints.length > 0) { + var currentIndex = scope.sliderSnapPoints.indexOf(ngModelCtrl.$viewValue); + if (currentIndex > 0) { + currentIndex--; + } + updateStep = scope.sliderSnapPoints[currentIndex]; + } + else { + updateStep = ngModelCtrl.$viewValue - skipInterval; + } + break; + case keymap.KEY.UP: + case keymap.KEY.RIGHT: + if(attr['sliderSnapPoints'] && scope.sliderSnapPoints.length > 0) { + var currentIndex = scope.sliderSnapPoints.indexOf(ngModelCtrl.$viewValue); + if (currentIndex < scope.sliderSnapPoints.length-1) { + currentIndex++; + } + updateStep = scope.sliderSnapPoints[currentIndex]; + } + else { + updateStep = ngModelCtrl.$viewValue + skipInterval; + } + break; + case keymap.KEY.END: + if(attr['sliderSnapPoints'] && scope.sliderSnapPoints.length > 0) { + currentIndex = scope.sliderSnapPoints.length-1; + updateStep = scope.sliderSnapPoints[currentIndex]; + } else { + setModelValue(scope.max); + } + e.preventDefault(); + e.stopPropagation(); + break; + case keymap.KEY.HOME: + if(attr['sliderSnapPoints'] && scope.sliderSnapPoints.length > 0) { + currentIndex = 0; + updateStep = scope.sliderSnapPoints[currentIndex]; + } else { + setModelValue(scope.min); + } + e.preventDefault(); + e.stopPropagation(); + break; + default: + return; + } + + if (angular.isNumber(updateStep) && !attr['disabled']) { + e.stopPropagation(); + e.preventDefault(); + scope.$apply(function() { + setModelValue(updateStep); + }); + if (attr['onDragEnd']) { + scope.onDragEnd(); + } + } + } + + scope.calculateLeft = function(snapPoint) { + var percentStr = (getValueToPercent(snapPoint) * 100) + '%'; + return {'left': percentStr}; + } + + elm.on('keydown', onKeyDown); + elm.on('mousedown', onMouseDown); + elm.on('click', onMouseUp); + elm.on('touchstart', onMouseDown); + sliderKnob.on('mousedown', onKnobMouseDown); + sliderKnob.on('touchstart', onKnobMouseDown); + $documentBind.event('mousemove', 'isDragging', onMouseMove, scope, true, 0); + $documentBind.event('mouseup', 'isDragging', onMouseUp, scope, true, 0); + $documentBind.event('touchmove', 'isDragging', onMouseMove, scope, true, 0); + $documentBind.event('touchend', 'isDragging', onMouseUp, scope, true, 0); + attr.$observe('disabled', function (disabled) { + if (disabled) { + sliderKnob.removeAttr('tabindex'); + } else { + sliderKnob.attr('tabindex', '0'); + disabled = false; + } + + elm.toggleClass("slider-disabled", disabled); + + scope.isSliderDisabled = disabled; + + if (angular.isDefined(attr.hideDisabledKnob)) { + scope.hideKnob = disabled; + } + }); + + ngModelCtrl.$render = function() { + if (!scope.isDragging) { + modelRenderer(); + if (attr['onRenderEnd'] && !attr['disabled']) { + scope.onRenderEnd({currentModelValue: scope.currentModelValue}); + } + } + }; + ngModelCtrl.$viewChangeListeners.push(modelRenderer); + ngModelCtrl.$formatters.push(getValidMinMax); + ngModelCtrl.$formatters.push(getValidStep); + } + }; + }]); +/** + * @ngdoc directive + * @name Forms.att:spinButton + * + * @param {String} spin-button-id - An ID for the input field + * @param {Integer} min - Minimum value for the input + * @param {Integer} max - Maximum value for the input + * @param {Integer} step - Value by which input field increments or decrements on up/down arrow keys + * @param {Integer} page-step - Value by which input field increments or decrements on page up/down keys + * @param {boolean} input-model-key - Default value for input field + * @param {boolean} disabled-flag - A boolean that triggers directive once the min or max value has reached + * + * @description + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.spinButton', ['b2b.att.utilities']) + .constant('b2bSpinButtonConfig', { + min: 1, + max: 10, + step: 1, + pageStep: 10, + inputModelKey: 'value', + disabledFlag: false + }) + .directive('b2bSpinButton', ['keymap', 'b2bSpinButtonConfig', 'b2bUserAgent', function (keymap, b2bSpinButtonConfig, userAgent) { + return { + restrict: 'EA', + require: '?ngModel', + transclude: false, + replace: true, + scope: { + min: '=min', + max: '=max', + step: '=step', + pageStep: '=pageStep', + spinButtonId: '@', + inputValue: '=ngModel', + inputModelKey: '@', + disabledFlag: "=?" + }, + templateUrl: 'b2bTemplate/spinButton/spinButton.html', + controller: ['$scope', '$element', '$attrs', function (scope, element, attrs) { + + scope.isMobile = userAgent.isMobile(); + scope.notMobile = userAgent.notMobile(); + + scope.min = attrs.min ? scope.min : b2bSpinButtonConfig.min; + scope.max = attrs.max ? scope.max : b2bSpinButtonConfig.max; + scope.step = attrs.step ? scope.step : b2bSpinButtonConfig.step; + scope.pageStep = attrs.pageStep ? scope.pageStep : b2bSpinButtonConfig.pageStep; + scope.inputModelKey = attrs.inputModelKey ? scope.inputModelKey : b2bSpinButtonConfig.inputModelKey; + scope.disabledFlag = attrs.disabledFlag ? scope.disabledFlag : b2bSpinButtonConfig.disabledFlag; + + if (scope.min < 0) { + scope.min = 0; + } + if (scope.max > 999) { + scope.max = 999; + } + + scope.isPlusDisabled = function () { + return (scope.disabledFlag || scope.inputValue[scope.inputModelKey] >= scope.max); + }; + scope.isMinusDisabled = function () { + return (scope.disabledFlag || scope.inputValue[scope.inputModelKey] <= scope.min); + }; + + scope.getValidateInputValue = function (value) { + if (value <= scope.min) { + return scope.min; + } else if (value >= scope.max) { + return scope.max; + } else { + return value; + } + }; + + scope.plus = function () { + scope.inputValue[scope.inputModelKey] = scope.getValidateInputValue(parseInt(scope.inputValue[scope.inputModelKey], 10) + scope.step); + }; + scope.minus = function () { + scope.inputValue[scope.inputModelKey] = scope.getValidateInputValue(parseInt(scope.inputValue[scope.inputModelKey], 10) - scope.step); + }; + scope.pagePlus = function () { + scope.inputValue[scope.inputModelKey] = scope.getValidateInputValue(parseInt(scope.inputValue[scope.inputModelKey], 10) + scope.pageStep); + }; + scope.pageMinus = function () { + scope.inputValue[scope.inputModelKey] = scope.getValidateInputValue(parseInt(scope.inputValue[scope.inputModelKey], 10) - scope.pageStep); + }; + + }], + link: function (scope, elem) { + + if (scope.notMobile) { + angular.element(elem).find('input').attr('aria-live', 'off'); + angular.element(elem).find('input').attr('role', 'spinbutton'); + } + + elem.find('input').bind('keydown', function (e) { + if (e.keyCode === keymap.KEY.UP) { + scope.plus(); + } else if (e.keyCode === keymap.KEY.DOWN){ + scope.minus(); + } else if (e.keyCode === keymap.KEY.HOME) { + scope.inputValue[scope.inputModelKey] = parseInt(scope.min); + } else if (e.keyCode === keymap.KEY.END) { + scope.inputValue[scope.inputModelKey] = parseInt(scope.max); + } else if (e.keyCode === keymap.KEY.PAGE_UP) { + scope.pagePlus(); + } else if (e.keyCode === keymap.KEY.PAGE_DOWN) { + scope.pageMinus(); + } + scope.$apply(); + }); + + elem.find('input').bind('keyup', function () { + if (scope.inputValue[scope.inputModelKey] === null || + scope.inputValue[scope.inputModelKey] === '' || + scope.inputValue[scope.inputModelKey] < scope.min) { + scope.inputValue[scope.inputModelKey] = scope.min; + scope.$apply(); + } else if (angular.isUndefined(scope.inputValue[scope.inputModelKey]) || + scope.inputValue[scope.inputModelKey] > scope.max) { + scope.inputValue[scope.inputModelKey] = scope.max; + scope.$apply(); + } + }); + + scope.focusInputSpinButton = function (evt) { + evt.preventDefault(); + if (scope.notMobile) { + elem[0].querySelector('input').focus(); + } + }; + + } + }; + }]); +/** + * @ngdoc directive + * @name Template.att:Static Route + * + * @description + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.staticRouteTemplate', ['b2b.att.utilities']) + +/** + * @ngdoc directive + * @name Progress & usage indicators.att:statusTracker + * + * @scope + * @param {array} statusObject - An array of status objects that accept heading, estimate, description and state + * @description + * + * + * @usage + * +
    + +
    + + * @example +
    + + + + +
    + */ + +angular.module('b2b.att.statusTracker', ['b2b.att.utilities']) +.constant('b2bStatusTrackerConfig', { + 'maxViewItems': 3, + 'icons': { + 'complete': 'icon-controls-approval', + 'current': 'icon-misc-time', + 'pending': 'icon-controls-statusokay', + 'actionRequired': 'icon-securityalerts-alert', + 'notAvailable': 'icon-controls-restricted' + } +}) +.directive('b2bStatusTracker', ['b2bStatusTrackerConfig', function(b2bStatusTrackerConfig) { + return { + restrict: 'EA', + transclude: false, + replace: true, + scope:{ + statuses: '=' + }, + templateUrl: function(scope) { + return 'b2bTemplate/statusTracker/statusTracker.html'; + }, + link: function(scope, element, attr) { + scope.currentViewIndex = 0; + scope.b2bStatusTrackerConfig = b2bStatusTrackerConfig; + + scope.nextStatus = function() { + if (scope.currentViewIndex+1 <= scope.statuses.length) { + scope.currentViewIndex++; + } + }; + scope.previousStatus = function() { + if (scope.currentViewIndex-1 >= 0) { + scope.currentViewIndex--; + } + }; + scope.isInViewport = function(index) { + return (index < scope.currentViewIndex+3 && index >= scope.currentViewIndex); // && index > scope.currentViewIndex-2 + }; + + scope.removeCamelCase = function(str) { + return str.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase(); + } + } + }; + }]); +/** + * @ngdoc directive + * @name Progress & usage indicators.att:stepTracker + * + * @scope + * @param {array} stepsItemsObject - An array of step objects + * @param {Integer} currenIindex - This indicates the current running step + * @param {Integer} viewportIndex - This is optional. This can used to start the view port rather than 1 item. + * @description + * + * + * @usage + * + * + * + + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.stepTracker', ['b2b.att.utilities']) + .constant('b2bStepTrackerConfig', { + 'maxViewItems': 5 + }) + .directive('b2bStepTracker', ['b2bStepTrackerConfig', function(b2bStepTrackerConfig) { + return { + restrict: 'EA', + transclude: true, + scope:{ + stepsItemsObject:"=", + currentIndex:"=", + viewportIndex:"=?" + }, + templateUrl: 'b2bTemplate/stepTracker/stepTracker.html', + link: function(scope, ele, attr) { + if (angular.isDefined(scope.viewportIndex)) { + scope.currentViewIndex = scope.viewportIndex - 1; + }else{ + scope.currentViewIndex = 0; + } + + scope.b2bStepTrackerConfig = b2bStepTrackerConfig; + scope.nextStatus = function() { + if (scope.currentViewIndex+1 <= scope.stepsItemsObject.length) { + scope.currentViewIndex++; + } + }; + scope.previousStatus = function() { + if (scope.currentViewIndex-1 >= 0) { + scope.currentViewIndex--; + } + }; + scope.isInViewport = function(index) { + return (index < scope.currentViewIndex+b2bStepTrackerConfig.maxViewItems && index >= scope.currentViewIndex); + }; + } + }; + }]); + +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:switches + * + * @description + * + * + * @usage + * + * + * + * + * + * + * + * + * @example + *
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.switches', ['b2b.att.utilities']) + .directive('b2bSwitches', ['$compile', '$templateCache', 'keymap', 'events', '$parse', '$timeout', function ($compile, $templateCache, keymap, events, $parse, $timeout) { + return { + restrict: 'EA', + require: ['ngModel'], + scope: { + options: "=", + ngModel: "=" + }, + link: function (scope, element, attrs, ctrl) { + var ngModelController = ctrl[0]; + if(!angular.isDefined(scope.options)){ + scope.options = { + "on":"On", + "off":"Off" + } + } + element.parent().bind("keydown mousedown", function (e) { + if (!attrs.disabled && (e.keyCode === keymap.KEY.ENTER || e.keyCode === keymap.KEY.SPACE || e.type === 'mousedown')) { + events.preventDefault(e); + ngModelController.$setViewValue(!ngModelController.$viewValue); + element.prop("checked", ngModelController.$viewValue); + if(ngModelController.$viewValue){ + element.addClass("checked"); + } + else{ + element.removeClass("checked"); + } + if(ngModelController.$viewValue){ + angular.element(switchElements[0]).css("left","10%"); + angular.element(switchElements[1]).css("left",rightOffSet+ "%"); + angular.element(switchElements[2]).css("right","100%"); + } + + if(!ngModelController.$viewValue){ + angular.element(switchElements[0]).css("left","100%"); + angular.element(switchElements[1]).css("left",leftOffSet+ "%"); + angular.element(switchElements[2]).css("right","10%"); + } + $timeout(function(){ + element.parent().addClass('focused'); + }, 100); + } + }); + + element.wrap('
    '); + + var widt = 0; + if(!angular.isDefined(attrs.typeSpanish) && scope.options != undefined){ + var offset = scope.options.on.length; + if(offset < scope.options.off.length) + offset = scope.options.off.length; + widt = ((offset) * 10) + 52; + } + if (angular.isDefined(attrs.typeSpanish)) { + widt = 80; + } + element.parent().css("width",widt+"px"); + var widthWithoutCircle = widt - 26; + var leftOffSet = ((3*100)/widt); + var rightOffSet = 100- ((28*100)/widt); + + + if (navigator.userAgent.match(/iphone/i)){ + element.attr("aria-live", "polite"); + } + else { + element.removeAttr('aria-live'); + } + + var templateSwitch = angular.element($templateCache.get("b2bTemplate/switches/switches.html")); + if (angular.isDefined(attrs.typeSpanish)) { + templateSwitch = angular.element($templateCache.get("b2bTemplate/switches/switches-spanish.html")); + } + + templateSwitch = $compile(templateSwitch)(scope); + element.parent().append(templateSwitch); + + var switchElements = angular.element(element.parent().children()[1]).children(); + angular.element(switchElements[0]).css("width","100%"); + angular.element(switchElements[2]).css("width","100%"); + + scope.$watch('ngModel', function () { + if(ngModelController.$viewValue){ + angular.element(switchElements[0]).css("left","10%"); + angular.element(switchElements[1]).css("left",rightOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[2]).css("right","100%"); + element.addClass("checked"); + } + + if(!ngModelController.$viewValue){ + angular.element(switchElements[0]).css("left","100%"); + angular.element(switchElements[1]).css("left",leftOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[2]).css("right","10%"); + element.removeClass("checked"); + } + }); + + element.bind("focus", function (e) { + element.parent().addClass('focused'); + }); + + element.bind("blur", function (e) { + element.parent().removeClass('focused'); + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Buttons, links & UI controls.att:switchesv2 + * + * @description + * + * + * @usage + * + *
    + * + *
    + * + * @example + *
    + HTML + AngularJS + + + + +
    + + */ +angular.module('b2b.att.switchesv2', ['b2b.att.utilities']) +.directive('b2bSwitchesV2', ['$compile', '$templateCache', 'keymap', 'events', '$parse', '$timeout', function ($compile, $templateCache, keymap, events, $parse, $timeout) { + +return { + restrict: 'EA', + require: ['ngModel'], + scope: { + options: "=", + ngModelSwitch: '=ngModel', + id: '=', + disabledFlag: '=ngDisabled' + }, + replace: true, + transclude: true, + templateUrl: function(element,attrs){ + return 'b2bTemplate/switches/switches-v2.html' + }, + link: function (scope, element, attrs, ctrl) { + var ngModelController = ctrl[0]; + + scope.model; + scope.switchId = scope.id; + + var externalLabelElement = angular.element(element.parent()[0]).children()[0]; + scope.ourLabel = angular.isDefined(attrs.labelText) ?attrs.labelText: '' ; + var switchOverlayElement = element.children()[1]; + var radioButtons = element.find('input'); + var switchElements = element.find('span'); + + angular.element(element.parent()).addClass('btn-swtich-label'); + externalLabelElement.classList.add('b2b-switch-span'); + switchOverlayElement.classList.add('switch-overlay-element'); + + var modelValue = false; + + if(!angular.isDefined(scope.options)){ + scope.options = { + "on":"On", + "off":"Off" + } + } + + if(scope.ngModelSwitch !== undefined && scope.ngModelSwitch) { + modelValue = true; + } else { + modelValue = false; + } + + var widt = 0; + + if(!angular.isDefined(attrs.typeSpanish) && scope.options != undefined){ + var offset = scope.options.on.length; + if(offset < scope.options.off.length) + offset = scope.options.off.length; + widt = ((offset) * 10) + 52; + } + if (angular.isDefined(attrs.typeSpanish)) { + widt = 80; + } + + element.css("width",widt+"px"); + var widthWithoutCircle = widt - 26; + var leftOffSet = ((3*100)/widt); + var rightOffSet = 100- ((28*100)/widt); + + angular.forEach(radioButtons, function(el) { + angular.element(el).bind('focus', function(e) { + element.addClass('focused'); + }); + + angular.element(el).bind('blur', function(e) { + element.removeClass('focused'); + }); + }); + + angular.element(switchElements[0]).css("width","100%"); + angular.element(switchElements[2]).css("width","100%"); + + + if(!modelValue){ + $timeout(function() { + radioButtons[1].checked = true; + }, 10); + angular.element(switchElements[0]).css("left","100%"); + angular.element(switchElements[1]).css("left",leftOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[2]).css("right","10%"); + + } else { + $timeout(function() { + radioButtons[0].checked = true; + }, 10); + angular.element(switchElements[0]).css("left","10%"); + angular.element(switchElements[1]).css("left",rightOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[1]).addClass("onstate"); + angular.element(switchElements[2]).css("right","100%"); + + } + + var toggleButton = function(){ + + modelValue = !modelValue; + + ngModelController.$setViewValue(modelValue); + + if (modelValue){ + scope.ngModelSwitch = true; + angular.element(switchElements[0]).css("left","10%"); + angular.element(switchElements[1]).css("left",rightOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[1]).addClass("onstate"); + angular.element(switchElements[2]).css("right","100%"); + + } else { + scope.ngModelSwitch = false; + angular.element(switchElements[0]).css("left","100%"); + angular.element(switchElements[1]).css("left",leftOffSet+ "%"); + angular.element(switchElements[1]).css("transition","all 0.3s linear 0s"); + angular.element(switchElements[1]).removeClass("onstate"); + angular.element(switchElements[2]).css("right","10%"); + } + } + + angular.element(externalLabelElement).bind("click", function (e) { + toggleButton(); + }) + + angular.element(radioButtons).bind("keydown", function (e) { + if ((e.keyCode === keymap.KEY.LEFT || e.keyCode === keymap.KEY.UP || e.keyCode === keymap.KEY.RIGHT || e.keyCode === keymap.KEY.DOWN || e.keyCode === keymap.KEY.SPACE)) { + toggleButton(); + } + }); + angular.element(switchOverlayElement).bind("click", function (e) { + toggleButton(); + }) + + + } +} +}]); +/** + * @ngdoc directive + * @name Template.att:Table with Drag and Drop + * + * @description + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.tableDragAndDrop', ['b2b.att.utilities','b2b.att.tables']) + +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:tableMessages + * + * @description + * + * + * @usage + + +

    No Matching Results

    +
    + + + + + + + + + + + + +

    The data is currently loading...

    +
    + + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.tableMessages', []) + .directive('b2bTableMessage', [function() { + return { + restrict: 'AE', + replace: true, + transclude: true, + scope: { + msgType: '=', + onRefreshClick: '&' + }, + templateUrl: 'b2bTemplate/tableMessages/tableMessage.html', + link: function(scope) { + scope.refreshAction = function(evt) { + scope.onRefreshClick(evt); + }; + } + }; + }]); + +/** + * @ngdoc directive + * @name Tabs, tables & accordions.att:tableScrollbar + * + * @description + * + * + * @usage + * + + + + + + ..... + + + + + + ..... + + +
    Id
    1002
    +
    + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.tableScrollbar', []) + .directive('b2bTableScrollbar', ['$timeout', function ($timeout) { + return { + restrict: 'E', + scope: true, + transclude: true, + templateUrl: 'b2bTemplate/tableScrollbar/tableScrollbar.html', + link: function (scope, element, attrs, ctrl) { + var firstThWidth, firstTdWidth, firstColumnWidth, firstColumnHeight, trHeight = 0; + var pxToScroll = ''; + var tableElement = element.find('table'); + var thElements = element.find('th'); + var tdElements = element.find('td'); + var innerContainer = angular.element(element[0].querySelector('.b2b-table-inner-container')); + var outerContainer = angular.element(element[0].querySelector('.b2b-table-scrollbar')); + + scope.disableLeft = true; + scope.disableRight = false; + + if (angular.isDefined(thElements[0])) { + firstThWidth = thElements[0].offsetWidth; + } + if (angular.isDefined(tdElements[0])) { + firstTdWidth = tdElements[0].offsetWidth; + } + firstColumnWidth = (firstThWidth > firstTdWidth) ? firstThWidth : firstTdWidth; + + innerContainer.css({ + 'padding-left': (firstColumnWidth + 2) + 'px' + }); + + angular.forEach(element.find('tr'), function (eachTr, index) { + trObject = angular.element(eachTr); + firstColumn = angular.element(trObject.children()[0]); + + angular.element(firstColumn).css({ + 'left': '0px', + 'width': (firstColumnWidth + 2) + 'px', + 'position': 'absolute' + }); + + trHeight = trObject[0].offsetHeight; + firstColumnHeight = firstColumn[0].offsetHeight; + if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { + firstColumnHeight += 1; + } + + if (trHeight !== firstColumnHeight - 1) { + if (trHeight > firstColumnHeight) { + if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { + trHeight -= 1; + } + angular.element(firstColumn).css({ + 'height': (trHeight + 1) + 'px' + }); + } else { + angular.element(trObject).css({ + 'height': (firstColumnHeight - 1) + 'px' + }); + } + } + + }); + + pxToScroll = outerContainer[0].offsetWidth - firstColumnWidth; + + scope.scrollLeft = function () { + innerContainer[0].scrollLeft = innerContainer[0].scrollLeft + 20 - pxToScroll; + }; + + scope.scrollRight = function () { + innerContainer[0].scrollLeft = innerContainer[0].scrollLeft + pxToScroll - 20; + }; + + scope.checkScrollArrows = function () { + if (innerContainer[0].scrollLeft == 0) { + scope.disableLeft = true; + } else { + scope.disableLeft = false; + } + + if (((innerContainer[0].offsetWidth - firstColumnWidth) + innerContainer[0].scrollLeft) >= tableElement[0].offsetWidth) { + scope.disableRight = true; + } else { + scope.disableRight = false; + } + }; + + + innerContainer.bind('scroll', function () { + $timeout(function () { + scope.checkScrollArrows(); + }, 1); + }); + + } + }; + }]); +/** + * @ngdoc directive + * @name Tabs, tables & accordions.att:tables + * + * @description + * + * + * @usage + * + Table + + + + + + + + + + + + + +
    Header 1Header 2
    + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.tables', ['b2b.att.utilities']) + .constant('b2bTableConfig', { + defaultSortPattern: false, // true for descending & false for ascending + highlightSearchStringClass: 'tablesorter-search-highlight', + zebraStripCutOff: 6, // > zebraStripCutOff + tableBreakpoints: [ // breakpoints are >= min and < max + { + min: 0, + max: 480, + columns: 2 + }, + { + min: 480, + max: 768, + columns: 3 + }, + { + min: 768, + max: 1025, + columns: 5 + }, + { + min: 1025, + max: 2050, + columns: 7 + } + ] + }) + .directive('b2bTable', ['$filter', '$window', 'b2bTableConfig', '$timeout', function ($filter, $window, b2bTableConfig, $timeout) { + return { + restrict: 'EA', + replace: true, + transclude: true, + scope: { + tableData: "=", + viewPerPage: "=", + currentPage: "=", + totalPage: "=", + searchCategory: "=", + searchString: "=", + nextSort: '=', + isOpen: '=' + }, + require: 'b2bTable', + templateUrl: 'b2bTemplate/tables/b2bTable.html', + controller: ['$scope', '$attrs', function ($scope, $attrs) { + this.headers = []; + this.currentSortIndex = null; + this.openResponsiveColumns = $scope.isOpen; + this.responsive = $scope.responsive = $attrs.responsive; + this.customHtml = $scope.customHtml = $attrs.customHtml; + this.maxTableColumns = -1; + this.totalTableColums = 0; + this.active = $scope.active = false; + this.responsiveRowScopes = []; + this.hideColumnPriority = []; + this.hiddenColumn = []; + this.setIndex = function (headerScope, priority) { + this.headers.push(headerScope); + if (this.responsive) { + this.totalTableColums++; + if (!isNaN(priority)) { + this.hideColumnPriority[priority] = this.totalTableColums - 1; + } else { + this.hideColumnPriority[this.totalTableColums - 1] = this.totalTableColums - 1; + } + } + return this.totalTableColums - 1; + }; + this.getIndex = function (headerName) { + for (var i = 0; i < this.headers.length; i++) { + if (this.headers[i].headerName === headerName) { + return this.headers[i].index; + } + } + return null; + }; + this.setResponsiveRow = function (responsiveRowScope) { + this.responsiveRowScopes.push(responsiveRowScope); + } + $scope.nextSort = ''; + this.sortData = function (columnIndex, reverse, externalSort) { + if ($scope.$parent && $scope.$parent !== undefined) { + $scope.$parent.columnIndex = columnIndex; + $scope.$parent.reverse = reverse; + } + this.currentSortIndex = columnIndex; + if (externalSort === true) { + if (!reverse) { + $scope.nextSort = 'd' + } else { + $scope.nextSort = 'a' + } + } + $scope.currentPage = 1; + this.resetSortPattern(); + }; + this.getSearchString = function () { + return $scope.searchString; + }; + this.resetSortPattern = function () { + for (var i = 0; i < this.headers.length; i++) { + var currentScope = this.headers[i]; + if (currentScope.index !== this.currentSortIndex) { + currentScope.resetSortPattern(); + } + } + }; + + $scope.$watch('nextSort', function (val) { + if ($scope.$parent && $scope.$parent !== undefined) { + $scope.$parent.nextSort = val; + } + + }); + }], + link: function (scope, elem, attr, ctrl) { + scope.searchCriteria = {}; + scope.tableBreakpoints = attr.tableConfig ? scope.$parent.$eval(attr.tableConfig) : angular.copy(b2bTableConfig.tableBreakpoints); + scope.$watchCollection('tableData', function (value) { + if (value && !isNaN(value.length)) { + scope.totalRows = value.length; + } + }); + scope.$watch('currentPage', function (val) { + if (scope.$parent && scope.$parent !== undefined) { + scope.$parent.currentPage = val; + } + + }); + scope.$watch('viewPerPage', function (val) { + if (scope.$parent && scope.$parent !== undefined) { + scope.$parent.viewPerPage = val; + } + }); + scope.$watch('totalRows', function (val) { + if (scope.$parent && scope.$parent !== undefined) { + if (val > b2bTableConfig.zebraStripCutOff) { + scope.$parent.zebraStripFlag = true; + } else { + scope.$parent.zebraStripFlag = false; + } + } + }); + scope.$watch(function () { + return scope.totalRows / scope.viewPerPage; + }, function (value) { + if (!isNaN(value)) { + scope.totalPage = Math.ceil(value); + scope.currentPage = 1; + } + }); + var searchValCheck = function (val) { + if (angular.isDefined(val) && val !== null && val !== "") { + return true; + } + }; + var setSearchCriteria = function (v1, v2) { + if (searchValCheck(v1) && searchValCheck(v2)) { + var index = ctrl.getIndex(v2); + scope.searchCriteria = {}; + if (index !== null) { + scope.searchCriteria[index] = v1; + } + } else if (searchValCheck(v1) && (!angular.isDefined(v2) || v2 === null || v2 === "")) { + scope.searchCriteria = { + $: v1 + }; + } else { + scope.searchCriteria = {}; + } + }; + scope.$watch('searchCategory', function (newVal, oldVal) { + if (newVal !== oldVal) { + setSearchCriteria(scope.searchString, newVal); + } + }); + scope.$watch('searchString', function (newVal, oldVal) { + if (newVal !== oldVal) { + setSearchCriteria(newVal, scope.searchCategory); + } + }); + scope.$watchCollection('searchCriteria', function (val) { + if (scope.$parent && scope.$parent !== undefined) { + scope.$parent.searchCriteria = val; + } + scope.totalRows = scope.tableData && ($filter('filter')(scope.tableData, val, false)).length || 0; + scope.currentPage = 1; + }); + var window = angular.element($window); + var findMaxTableColumns = function () { + var windowWidth; + windowWidth = $window.innerWidth; + ctrl.maxTableColumns = -1; + for (var i in scope.tableBreakpoints) { + if (windowWidth >= scope.tableBreakpoints[i].min && windowWidth < scope.tableBreakpoints[i].max) { + ctrl.maxTableColumns = scope.tableBreakpoints[i].columns; + break; + } + } + if (ctrl.maxTableColumns > -1 && ctrl.totalTableColums > ctrl.maxTableColumns) { + ctrl.active = true; + } else { + ctrl.active = false; + } + for (var i in ctrl.responsiveRowScopes) { + if(angular.isFunction(ctrl.responsiveRowScopes[i].setActive) ){ + ctrl.responsiveRowScopes[i].setActive(ctrl.active); + } + } + }; + var findHiddenColumn = function () { + var columnDiffenence = ctrl.maxTableColumns > -1 ? ctrl.totalTableColums - ctrl.maxTableColumns : 0; + ctrl.hiddenColumn = []; + if (columnDiffenence > 0) { + var tempHideColumnPriority = angular.copy(ctrl.hideColumnPriority); + for (var i = 0; i < columnDiffenence; i++) { + ctrl.hiddenColumn.push(tempHideColumnPriority.pop()); + } + } + }; + var resizeListener = function () { + findMaxTableColumns(); + findHiddenColumn(); + }; + if (ctrl.responsive) { + window.bind('resize', function () { + resizeListener(); + scope.$apply(); + }); + $timeout(function () { + resizeListener(); + }, 100); + } + } + }; + }]) + .directive('b2bTableRow', [function () { + return { + restrict: 'EA', + compile: function (elem, attr) { + if (attr.type === 'header') { + angular.noop(); + } else if (attr.type === 'body') { + var html = elem.children(); + if (attr.rowRepeat) { + html.attr('ng-repeat', attr.rowRepeat.concat(" | orderBy : (reverse?'-':'')+ columnIndex | filter : searchCriteria : false ")); + } + html.attr('ng-class', "{'odd': $odd && zebraStripFlag}"); + html.attr('b2b-responsive-row', '{{$index}}'); + html.attr('class', 'data-row'); + html.attr('is-open',attr.isOpen); + elem.append(html); + } + } + }; + }]) + .directive('b2bTableHeader', ['b2bTableConfig', function (b2bTableConfig) { + return { + restrict: 'EA', + replace: true, + transclude: true, + scope: { + sortable: '@', + defaultSort: '@', + index: '@key' + }, + require: '^b2bTable', + templateUrl: function (elem, attr) { + if (attr.sortable === 'false') { + return 'b2bTemplate/tables/b2bTableHeaderUnsortable.html'; + } else { + return 'b2bTemplate/tables/b2bTableHeaderSortable.html'; + } + }, + link: function (scope, elem, attr, ctrl) { + var reverse = b2bTableConfig.defaultSortPattern; + scope.headerName = elem.text(); + scope.headerId = elem.attr('id'); + scope.sortPattern = null; + var priority = parseInt(attr.priority, 10); + scope.columnIndex = ctrl.setIndex(scope, priority); + + scope.isHidden = function () { + return (ctrl.hiddenColumn.indexOf(scope.columnIndex) > -1); + }; + + scope.$watch(function () { + return elem.text(); + }, function (value) { + scope.headerName = value; + }); + scope.sort = function (sortType) { + if (typeof sortType === 'boolean') { + reverse = sortType; + } + ctrl.sortData(scope.index, reverse, false); + scope.sortPattern = reverse ? 'descending' : 'ascending'; + reverse = !reverse; + }; + scope.$watch(function () { + return ctrl.currentSortIndex; + }, function (value) { + if (value !== scope.index) { + scope.sortPattern = null; + } + }); + + if (scope.sortable === undefined || scope.sortable === 'true' || scope.sortable === true) { + scope.sortable = 'true'; + } else if (scope.sortable === false || scope.sortable === 'false') { + scope.sortable = 'false'; + } + + if (scope.sortable !== 'false') { + if (scope.defaultSort === 'A' || scope.defaultSort === 'a') { + scope.sort(false); + } else if (scope.defaultSort === 'D' || scope.defaultSort === 'd') { + scope.sort(true); + } + } + scope.resetSortPattern = function () { + reverse = b2bTableConfig.defaultSortPattern; + }; + } + }; + }]) + .directive('b2bResponsiveRow', ['$templateCache', '$timeout', '$compile', function ($templateCache, $timeout, $compile) { + return { + restrict: 'EA', + require: '^b2bTable', + controller: ['$scope', function ($scope) { + this.rowValues = $scope.rowValues = []; + $scope.headerClass = {}; + $scope.bodyClass = {}; + this.setRowValues = function (rowValue) + {this.rowValues.push(rowValue);}; + var columnIndexCounter = - 1; + this.getIndex = function () + { columnIndexCounter++; + return columnIndexCounter;}; + this.setHeaderClass = function (columnIndex, classNames) + { $scope.headerClass[columnIndex] = classNames;}; + this.setBodyClass = function (columnIndex, classNames) + { $scope.bodyClass[columnIndex] = classNames;}; + }], + link: function (scope, elem, attr, ctrl) { + if (ctrl.responsive) { + scope.rowIndex = attr.b2bResponsiveRow; + scope.active = false; + scope.expandFlag = ctrl.openResponsiveColumns; + scope.headerValues = ctrl.headers; + ctrl.setResponsiveRow(scope); + var firstTd = elem.find('td').eq(0); + if (scope.expandFlag) { + elem.addClass('opened'); + } + scope.setActive = function (activeFlag) { + scope.active = activeFlag; + if (scope.active) { + elem.addClass('has-button'); + firstTd.attr('role', 'rowheader'); + firstTd.parent().attr('role', 'row'); + } else { + elem.removeClass('has-button'); + firstTd.removeAttr('role'); + firstTd.parent().removeAttr('role'); + } + }; + scope.toggleExpandFlag = function (expandFlag) { + if (angular.isDefined(expandFlag)) { + scope.expandFlag = expandFlag; + } else { + scope.expandFlag = !scope.expandFlag; + } + if (scope.expandFlag) { + elem.addClass('opened'); + } else { + elem.removeClass('opened'); + } + }; + + firstTd.attr('scope', 'row'); + scope.$on('$destroy', function () { + elem.next().remove(); + }); + $timeout(function () { + /*if(ctrl.customHtml!=="true"){ + scope.firstTdId = firstTd.attr('id'); + var firstTdContent = firstTd.html(); + var toggleButtonTemplate = '' + firstTdContent + '' + firstTdContent + ''; + toggleButtonTemplate = $compile(toggleButtonTemplate)(scope); + firstTd.html(''); + firstTd.prepend(toggleButtonTemplate); + }*/ + var template = $templateCache.get('b2bTemplate/tables/b2bResponsiveRow.html'); + template = $compile(template)(scope); + elem.after(template); + }, 100); + } + } + }; + }]) + .directive('b2bResponsiveList', ['$templateCache', '$timeout', '$compile', function ($templateCache, $timeout, $compile) { + return { + restrict: 'EA', + require: '^b2bTable', + link: function (scope, elem, attr, ctrl) { + scope.columnIndex = parseInt(attr.b2bResponsiveList, 10); + scope.isVisible = function () { + return (ctrl.hiddenColumn.indexOf(scope.columnIndex) > -1); + }; + } + }; + }]) + .directive('b2bTableBody', ['$filter', '$timeout', 'b2bTableConfig', function ($filter, $timeout, b2bTableConfig) { + return { + restrict: 'EA', + require: ['^b2bTable', '?^b2bResponsiveRow'], + scope: true, + replace: true, + transclude: true, + templateUrl: 'b2bTemplate/tables/b2bTableBody.html', + link: function (scope, elem, attr, ctrl) { + var b2bTableCtrl = ctrl[0]; + var b2bResponsiveRowCtrl = ctrl[1]; + var highlightSearchStringClass = b2bTableConfig.highlightSearchStringClass; + var searchString = ""; + var responsiveTableHeaderClass = attr.b2bResponsiveTableHeaderClass || ''; + var responsiveTableBodyClass = attr.b2bResponsiveTableBodyClass || ''; + var wrapElement = function (elem) { + var text = elem.text(); + elem.html($filter('b2bHighlight')(text, searchString, highlightSearchStringClass)); + }; + var traverse = function (elem) { + var innerHtml = elem.children(); + if (innerHtml.length > 0) { + for (var i = 0; i < innerHtml.length; i++) { + traverse(innerHtml.eq(i)); + } + } else { + wrapElement(elem); + return; + } + }; + var clearWrap = function (elem) { + var elems = elem.find('*'); + for (var i = 0; i < elems.length; i++) { + if (elems.eq(i).attr('class') && elems.eq(i).attr('class').indexOf(highlightSearchStringClass) !== -1) { + var text = elems.eq(i).text(); + elems.eq(i).replaceWith(text); + } + } + }; + if (b2bResponsiveRowCtrl) { + scope.columnIndex = b2bResponsiveRowCtrl.getIndex(); + scope.isHidden = function () { + return (b2bTableCtrl.hiddenColumn.indexOf(scope.columnIndex) > -1); + }; + } + $timeout(function () { + var actualHtml = elem.children(); + scope.$watch(function () { + return b2bTableCtrl.getSearchString(); + }, function (val) { + searchString = val; + clearWrap(elem); + if (actualHtml.length > 0) { + traverse(elem); + } else { + wrapElement(elem); + } + }); + if (b2bResponsiveRowCtrl) { + b2bResponsiveRowCtrl.setRowValues(elem.html()); + } + }, 50); + } + }; + }]) + .directive('b2bTableSort', ['b2bTableConfig','$timeout', function (b2bTableConfig,$timeout) { + return { + restrict: 'EA', + replace: true, + require: '^b2bTable', + link: function (scope, elem, attr, ctrl) { + var initialSort = '', + nextSort = '', + tempsort = ''; + initialSort = attr.initialSort; + + scope.sortTable = function (msg,trigger) { + if(trigger == 'dropdown'){ + if(nextSort === '') { + ctrl.sortData(msg, false, false); + } + else if (nextSort === 'd' || nextSort === 'D') { + ctrl.sortData(msg, false, false); + }else{ + ctrl.sortData(msg, true, false); + } + return; + } + $timeout(function(){ + if (nextSort.length > 0) { + + if (nextSort === 'd' || nextSort === 'D') { + tempsort = nextSort + ctrl.sortData(msg, true, true); + nextSort = 'a'; + $timeout(function(){ + if(!angular.isUndefined(elem[0].querySelector('.sortButton')) || elem[0].querySelector('.sortButton') !== null ){ + angular.element(elem[0].querySelector('.sortButton'))[0].focus(); + } + },100); + + } else { + tempsort = nextSort + ctrl.sortData(msg, false, true); + nextSort = 'd'; + $timeout(function(){ + if(!angular.isUndefined(elem[0].querySelector('.sortButton')) || elem[0].querySelector('.sortButton') !== null ){ + angular.element(elem[0].querySelector('.sortButton'))[0].focus(); + } + },100); + } + } else if (initialSort.length > 0) { + + if (initialSort === 'd' || initialSort === 'D') { + tempsort = nextSort + ctrl.sortData(msg, true, true); + nextSort = 'a'; + $timeout(function(){ + if(!angular.isUndefined(elem[0].querySelector('.sortButton')) || elem[0].querySelector('.sortButton') !== null ){ + angular.element(elem[0].querySelector('.sortButton'))[0].focus(); + } + },100); + + } else { + tempsort = nextSort + ctrl.sortData(msg, false, true); + nextSort = 'd'; + $timeout(function(){ + if(!angular.isUndefined(elem[0].querySelector('.sortButton')) || elem[0].querySelector('.sortButton') !== null ){ + angular.element(elem[0].querySelector('.sortButton'))[0].focus(); + } + },100); + + + } + } + },10) + + }; + + scope.sortDropdown = function(msg) { + + if(tempsort==='') { + + tempsort='a' + } + if(tempsort === 'd' || tempsort === 'D' ) { + ctrl.sortData(msg, true, false); + } else { + ctrl.sortData(msg, false, false); + } + + }; + } + }; + }]); +/** + * @ngdoc directive + * @name Tabs, tables & accordions.att:tabs + * + * @description + * + * + * @usage + * + + {{tab.title}} + + + * + * @example + *
    + + + + +
    + * + */ + +angular.module('b2b.att.tabs', ['b2b.att.utilities']) + .directive('b2bTabset', function () { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + tabIdSelected: '=' + }, + templateUrl: 'b2bTemplate/tabs/b2bTabset.html', + controller: ['$scope', function ($scope) { + + this.setTabIdSelected = function (tab) { + $scope.tabIdSelected = tab.id; + }; + + this.getTabIdSelected = function () { + return $scope.tabIdSelected; + }; + }] + }; + }) + .directive('b2bTab', ['keymap', function (keymap) { + return { + restrict: 'EA', + transclude: true, + replace: true, + require: '^b2bTabset', + scope: { + tabItem: "=" + }, + templateUrl: 'b2bTemplate/tabs/b2bTab.html', + controller: [function(){}], + link: function (scope, element, attr, b2bTabsetCtrl) { + + if (scope.tabItem && !scope.tabItem.disabled) { + scope.tabItem.disabled = false; + } + + scope.isTabActive = function () { + return (scope.tabItem.id === b2bTabsetCtrl.getTabIdSelected()); + }; + + scope.clickTab = function () { + if (attr.disabled) { + return; + } + b2bTabsetCtrl.setTabIdSelected(scope.tabItem); + }; + + scope.nextKey = function () { + var el = angular.element(element[0])[0]; + var elementToFocus = null; + while (el && el.nextElementSibling) { + el = el.nextElementSibling; + if (!el.querySelector('a').disabled) { + elementToFocus = el.querySelector('a'); + break; + } + } + + if (!elementToFocus) { + var childTabs = element.parent().children(); + for (var i = 0; i < childTabs.length; i++) { + if (!childTabs[i].querySelector('a').disabled) { + elementToFocus = childTabs[i].querySelector('a'); + break; + } + } + } + + if (elementToFocus) { + elementToFocus.focus(); + } + }; + + scope.previousKey = function () { + var el = angular.element(element[0])[0]; + var elementToFocus = null; + + while (el && el.previousElementSibling) { + el = el.previousElementSibling; + if (!el.querySelector('a').disabled) { + elementToFocus = el.querySelector('a'); + break; + } + } + + if (!elementToFocus) { + var childTabs = element.parent().children(); + for (var i = childTabs.length - 1; i > 0; i--) { + if (!childTabs[i].querySelector('a').disabled) { + elementToFocus = childTabs[i].querySelector('a'); + break; + } + } + } + + if (elementToFocus) { + elementToFocus.focus(); + } + }; + + angular.element(element[0].querySelector('a')).bind('keydown', function (evt) { + + if (!(evt.keyCode)) { + evt.keyCode = evt.which; + } + + switch (evt.keyCode) { + case keymap.KEY.RIGHT: + evt.preventDefault(); + scope.nextKey(); + break; + + case keymap.KEY.LEFT: + evt.preventDefault(); + scope.previousKey(); + break; + + default:; + } + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Messages, modals & alerts.att:tagBadges + * + * @description + * + * + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.tagBadges', ['b2b.att.utilities']) + .directive('b2bTagBadge',['$timeout',function($timeout){ + return{ + restrict: 'EA', + link: function(scope,elem,attr,ctrl){ + elem.addClass('b2b-tags'); + if(angular.element(elem[0].querySelector('.icon-close')).length>0) { + var item = angular.element(elem[0].querySelector('.icon-close')); + item.bind('click',function(){ + elem.css({'height':'0','width':'0','padding':'0','border':'0'}); + elem.attr('tabindex','0'); + elem[0].focus(); + item.parent().remove(); + elem[0].bind('blur',function(){ + elem[0].remove(); + }); + }); + } + + + + + } + }; +}]); +/** + * @ngdoc directive + * @name Forms.att:textArea + * + * @description + * + * + * @usage + * + * + * @example +
    + HTML + AngularJS + + + + +
    + */ +angular.module('b2b.att.textArea', ['b2b.att.utilities']) + +.directive('b2bResetTextarea', [ function () { + return { + restrict: 'A', + require: 'b2bReset', + link: function (scope, element, attrs, ctrl) { + + var resetButton = ctrl.getResetButton(); + + var computeScrollbarAndAddClass = function () { + if (element.prop('scrollHeight') > element[0].clientHeight) { + element.addClass('hasScrollbar'); + } else { + element.removeClass('hasScrollbar'); + } + }; + + computeScrollbarAndAddClass(); + + element.on('focus keyup', function(){ + computeScrollbarAndAddClass(); + }); + } + }; +}]); + +/** + * @ngdoc directive + * @name Forms.att:timeInputField + * + * @description + * + * + + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.timeInputField',['ngMessages', 'b2b.att.utilities']).directive('b2bTimeFormat',function(){ + return{ + restrict : 'A', + require : '^ngModel', + link : function(scope,elem,attr,ctrl){ + elem.on('keyup',function(evt){ + var modelValue = ctrl.$modelValue; + var format = attr.b2bTimeFormat; + modelValue = modelValue.split(':'); + if(format == "12"){ + if(!(modelValue[0] <= 12 && modelValue[0] > 0 ) || !(modelValue[1] <= 59)){ + ctrl.$setValidity('inValidTime',false); + }else{ + ctrl.$setValidity('inValidTime',true); + } + }else if(format =="24"){ + if(!(modelValue[0] <= 23) || !(modelValue[1] <= 59)){ + ctrl.$setValidity('inValidTime',false); + }else{ + ctrl.$setValidity('inValidTime',true); + } + } + scope.$apply(); + }); + } + } +}); + +/** + * @ngdoc directive + * @name Forms.att:tooltipsForForms + * + * @description + * + * + * @example + + + + + */ +angular.module('b2b.att.tooltipsForForms', ['b2b.att.utilities']) + .directive('b2bTooltip', ['$document', '$window', '$isElement', function ($document, $window, $isElement) { + return { + restrict: 'A', + link: function (scope, elem, attr, ctrl) { + var icon = elem[0].querySelector('.tooltip-element'); + var btnIcon = elem[0].querySelector('.btn.tooltip-element'); + var tooltipText = elem[0].querySelector('.helpertext'); + var tooltipWrapper = elem[0].querySelector('.tooltip-size-control'); + if (elem.hasClass('tooltip-onfocus')) { + var inputElm = angular.element(elem[0].querySelector("input")); + var textAreaElm = angular.element(elem[0].querySelector("textarea")); + } + + angular.element(icon).attr({'aria-expanded': false}); + angular.element(btnIcon).attr({'aria-expanded': false}); + var calcTooltip = function () { + if (!elem.hasClass('tooltip active')) { + if (elem.hasClass('tooltip-onfocus')) { + angular.element(elem[0].querySelector("input")).triggerHandler('focusout'); + } + if (elem.hasClass('tooltip-onclick')) { + return false; + } + angular.element(icon).removeClass('active'); + angular.element(icon).attr({'aria-expanded': true}); + angular.element(icon).attr({'aria-describedby': angular.element(tooltipText).attr('id')}); + angular.element(tooltipText).attr({'aria-hidden': false}); + elem.addClass('active'); + + var tooltipIconPos = angular.element(icon).prop('offsetLeft'), + tooltipPosition = angular.element(tooltipText).prop('offsetWidth') / 2, + tipOffset = (tooltipIconPos - 30) - tooltipPosition, + maxRightPos = (($window.innerWidth - 72) - (tooltipPosition * 2)) - 14.5; + + if ($window.innerWidth >= '768') { + if (tipOffset < 0) {// if icon on far left side of page + tipOffset = 15; + } + else if (tooltipIconPos > maxRightPos) {// if icon is far right side of page + tipOffset = maxRightPos; + } + else {// if tooltip in the middle somewhere + tipOffset = tipOffset; + } + angular.element(tooltipWrapper).css({left: tipOffset + 'px'}); + } + } + }; + + // TOOLTIP LINK ONCLICK AND FOCUS + angular.element(icon).on('click mouseover mouseout focus blur', function (e) { + if (e.type == 'mouseover') { + calcTooltip(); + } + else if (e.type == 'mouseout' && elem.hasClass('active')) { + if (!elem.hasClass('activeClick')) { + angular.element(tooltipText).attr({ + 'aria-hidden': true, + 'tabindex': '-1' + }); + elem.removeClass('active'); + } else if (elem.hasClass('activeClick') && navigator.userAgent.match(/iphone/i)) { + elem.removeClass('active activeClick'); + } + } + + else { + if (elem.hasClass('activeClick')) { + angular.element(icon).attr({'aria-expanded': false}); + angular.element(tooltipText).attr({'aria-hidden': true}); + angular.element(icon).removeAttr('aria-describedby'); + elem.removeClass('activeClick active'); + e.preventDefault(); + } + else if (e.type == 'click') { + elem.addClass('activeClick'); + calcTooltip(); + e.preventDefault(); + } + else { + angular.element(icon).on('keydown', function (e) { + if (e.keyCode == '32') { + (elem.hasClass('active')) ? elem.removeClass('active') : elem.addClass('value'); + angular.element(icon).triggerHandler('click'); + e.preventDefault(); + } else if (e.keyCode == '27') { + (elem.hasClass('active')) ? elem.removeClass('active activeClick') : elem.addClass('value'); + } + }); + e.preventDefault(); + } + } + e.preventDefault(); + }); + + // TOOLTIP BUTTON INSIDE A TEXT FIELD + angular.element(btnIcon).on('click', function (e) { + var $this = angular.element(this); + if ($this.hasClass('active') && elem.hasClass('tooltip-onclick')) { + elem.removeClass('active'); + $this.removeClass('active'); + angular.element(tooltipText).removeAttr('aria-live'); + $this.attr({'aria-expanded': 'false'}); + $this.removeAttr('aria-describedby'); + } else { + elem.addClass('active'); + $this.addClass('active'); + $this.attr({'aria-expanded': 'true', 'aria-describedby': angular.element(tooltipText).attr('id')}); + angular.element(tooltipText).attr({'aria-live': 'polite'}); + } + }); + + angular.element(btnIcon).on('blur', function (e) { + var $this = angular.element(this); + if ($this.hasClass('active') && elem.hasClass('tooltip-onclick')) { + elem.removeClass('active'); + $this.removeClass('active'); + angular.element(tooltipText).removeAttr('aria-live'); + $this.attr({'aria-expanded': 'false'}); + $this.removeAttr('aria-describedby'); + } + }); + + angular.element(btnIcon).on('keydown', function (e) { + var $this = angular.element(this); + if (e.keyCode == '27') { + var $this = angular.element(this); + if ($this.hasClass('active') && elem.hasClass('tooltip-onclick')) { + elem.removeClass('active'); + $this.removeClass('active'); + angular.element(tooltipText).removeAttr('aria-live'); + $this.attr({'aria-expanded': 'false'}); + $this.removeAttr('aria-describedby'); + } + } + }); + + // close all tooltips if clicking something else + $document.bind('click', function (e) { + var isElement = $isElement(angular.element(e.target), elem, $document); + if (!isElement) { + elem.removeClass('active'); + angular.element(elem[0].querySelector('.tooltip-element')).removeClass('active'); + angular.element(tooltipText).removeAttr('aria-live'); + angular.element(elem[0].querySelector('.tooltip-element')).attr({'aria-expanded': 'false'}); + angular.element(elem[0].querySelector('.tooltip-element')).removeAttr('aria-describedby'); + }; + }); + + angular.element(inputElm).on('keydown', function (e) { + if (e.keyCode == '27'){ + elem.removeClass('active'); + angular.element(tooltipText).css('display', 'none'); + angular.element(tooltipText).removeAttr('aria-live'); + + if (angular.element(this).attr('aria-describedby') === undefined){ + + } + + else if ((spaceIndex = angular.element(this).attr('aria-describedby').lastIndexOf(' ')) >= 0){ + + var describedByValue = angular.element(this).attr('aria-describedby').slice(0, spaceIndex); + + angular.element(this).attr('aria-describedby', describedByValue); + + } + else { + angular.element(this).removeAttr('aria-describedby'); + } + } + }); + + angular.element(textAreaElm).on('keydown', function (e) { + if (e.keyCode == '27'){ + elem.removeClass('active'); + angular.element(tooltipText).css('display', 'none'); + angular.element(tooltipText).removeAttr('aria-live'); + if (angular.element(this).attr('aria-describedby') === undefined){ + + } + + else if ((spaceIndex = angular.element(this).attr('aria-describedby').lastIndexOf(' ')) >= 0){ + + var describedByValue = angular.element(this).attr('aria-describedby').slice(0, spaceIndex); + + angular.element(this).attr('aria-describedby', describedByValue); + + } + else { + angular.element(this).removeAttr('aria-describedby'); + } + } + }); + + // TOOLTIP TRIGGERED AUTOMATICALLY INSIDE A TEXT FIELD + angular.element(inputElm).on('focus', function (e) { + var allTooltip = $document[0].querySelectorAll('[class*="tooltip"]'); + for (var i = 0; i < allTooltip.length; i++) { + if (angular.element(allTooltip[i]).hasClass('active')) { + angular.element(allTooltip[i]).triggerHandler('click'); + } + }; + angular.element(this).attr({'aria-describedby': angular.element(tooltipText).attr('id')}); + angular.element(tooltipText).css('display', 'block'); + angular.element(tooltipText).attr({'aria-live': 'polite'}); + elem.addClass('active'); + }); + angular.element(inputElm).on('blur', function (e) { + elem.removeClass('active'); + angular.element(tooltipText).css('display', 'none'); + angular.element(tooltipText).removeAttr('aria-live'); + angular.element(this).removeAttr('aria-describedby'); + }); + + // TOOLTIP TRIGGERED AUTOMATICALLY INSIDE A TEXTAREA + angular.element(textAreaElm).on('focus', function (e) { + var allTooltip = $document[0].querySelectorAll('[class*="tooltip"]'); + for (var i = 0; i < allTooltip.length; i++) { + if (angular.element(allTooltip[i]).hasClass('active')) { + angular.element(allTooltip[i]).triggerHandler('click'); + } + }; + elem.addClass('active'); + angular.element(tooltipText).css('display', 'block'); + angular.element(tooltipText).attr({'aria-live': 'polite'}); + angular.element(this).attr({'aria-describedby': angular.element(tooltipText).attr('id')}); + }); + angular.element(textAreaElm).on('blur', function (e) { + elem.removeClass('active'); + angular.element(tooltipText).css('display', 'none'); + angular.element(tooltipText).removeAttr('aria-live'); + angular.element(this).removeAttr('aria-describedby'); + }); + + //TOOLTIP TRIGGERED AUTOMATICALLY INSIDE A element with trigger focus + if(elem.attr('trigger') == "focus"){ + angular.element(icon).on('focus', function (e) { + calcTooltip(); + }); + angular.element(icon).on('blur', function (e) { + if (elem.hasClass('active')) { + if (!elem.hasClass('activeClick')) { + angular.element(tooltipText).attr({ + 'aria-hidden': true, + 'tabindex': '-1' + }); + elem.removeClass('active'); + } else if (elem.hasClass('activeClick') && navigator.userAgent.match(/iphone/i)) { + elem.removeClass('active activeClick'); + } + } + }); + } + } + }; + }]); +/** + * @ngdoc directive + * @name Navigation.att:TreeNavigation + * + * + * @scope + * @param {String} setRole - This value needs to be "tree". This is required to incorporate CATO requirements. + * @param {Boolean} groupIt - This value needs to be "false" for top-level tree rendered. + * + * @description + * + * + * @usage + *
    + * + *
    + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.treeNav', ['b2b.att.utilities']) + .directive('b2bTreeNav', function () { + return { + restrict: "E", + replace: true, + scope: { + collection: '=', + groupIt: '=', + setRole: '@' + }, + templateUrl: function (element, attrs) { + if (attrs.groupIt === 'true') { + return "b2bTemplate/treeNav/groupedTree.html"; + } else { + return "b2bTemplate/treeNav/ungroupedTree.html"; + } + }, + link: function (scope) { + if (!(scope.setRole === 'tree')) { + scope.setRole = 'group'; + } + } + } + }) + .directive('b2bMember', ['$compile', '$timeout', 'keymap', function ($compile, $timeout, keymap) { + return { + restrict: "E", + replace: true, + scope: { + member: '=', + groupIt: '=' + }, + templateUrl: 'b2bTemplate/treeNav/treeMember.html', + link: function (scope, element, attrs) { + scope.elemArr = []; + var removeRootTabIndex = function (elem) { + if (elem.parent().parent().eq(0).hasClass('b2b-tree')) { + elem.attr('tabindex', -1); + return; + } + removeRootTabIndex(elem.parent()); + }; + scope.$watch('member.child', function(newVal, oldVal){ + if(newVal !== oldVal){ + scope.showChild(); + }; + }); + scope.showChild = function () { + if (!element.hasClass('grouped')) { + if (angular.isArray(scope.member.child) && scope.member.child.length > 0 && (scope.member.divide === undefined || scope.member.child.length < scope.member.divide)) { + scope.groupIt = false; + element.addClass('grouped'); + element.append(""); + $compile(element.contents())(scope); + if(scope.member.active && scope.member.active === true){ + element.find('i').eq(0).removeClass('icon-collapsed'); + }; + if(scope.member.selected && scope.member.selected === true){ + element.attr('aria-selected', true); + element.attr('tabindex', 0); + removeRootTabIndex(element); + }; + if(scope.member.active && scope.member.active == undefined){ + element.find('i').eq(0).addClass('icon-collapsed'); + }; + } else if (scope.member.child && scope.member.divide && scope.member.child.length > scope.member.divide) { + element.addClass('grouped'); + scope.groupIt = true; + // FILTER - GROUPBY - APPROACH + var j = 0; + var grpName = ''; + if(scope.member.child[0].groupName !== undefined){ + grpName = scope.member.child[0].groupName; + } + else{ + var toSlice = scope.member.child[0].name.search(' '); + grpName = scope.member.child[0].name.slice(0, toSlice); + } + + for (i = 0; i < scope.member.child.length; i += scope.member.divide) { + j = 0; + for (j = j + i; j < (i + scope.member.divide); j++) { + if (j === scope.member.child.length) { + scope.member.child[j - 1].grpChild = grpName + ' ' + (i + 1) + ' - ' + (scope.member.child.length); + break; + + if(scope.member.child[j-1].active && scope.member.child[j-1].active===true){ + scope.member.child[j-1].activeGrp = true; + }; + + } + if (i + scope.member.divide > scope.member.child.length) { + scope.member.child[j].grpChild = grpName + ' ' + (i + 1) + ' - ' + (scope.member.child.length); + if(scope.member.child[j].active && scope.member.child[j].active===true){ + scope.member.child[j].activeGrp = true; + }; + + } else { + scope.member.child[j].grpChild = grpName + ' ' + (i + 1) + ' - ' + (i + scope.member.divide); + if(scope.member.child[j].active && scope.member.child[j].active===true){ + scope.member.child[j].activeGrp = true; + }; + } + } + } + if(scope.member.divide){ + element.append(""); + } else { + element.append(""); + } + $compile(element.contents())(scope); + if(scope.member.active && scope.member.active === true){ + element.find('i').eq(0).removeClass('icon-collapsed'); + }; + if(scope.member.selected && scope.member.selected === true){ + element.attr('aria-selected', true); + }; + if( scope.member.active && scope.member.active == undefined){ + element.find('i').eq(0).addClass('icon-collapsed'); + }; + } + } + }; + //Below condition opens node for opening on json load. + if(scope.member.active && scope.member.active == true){ + scope.showChild(); + }; + if(scope.member.active == undefined && !element.find('a').eq(0).hasClass('active') && scope.member.child !== undefined){ + element.find('i').eq(0).addClass('icon-collapsed'); + } + else if(scope.member.child == undefined){ + element.find('i').eq(0).addClass('icon-circle'); + }; + element.bind('keydown', function (evt) { + switch (evt.keyCode) { + case keymap.KEY.ENTER: + if (element.hasClass('bg') && scope.member.onSelect !== undefined) { + scope.member.onSelect(scope.member); + } + evt.stopPropagation(); + break; + default: + break; + } + + }); + //else getting true in every case .. so better use switch case .. that makes more sense you dumb. + element.bind('click', function (evt) { + scope.showChild(); + var expandFunc = scope.member.onExpand; + + //onSelect + if (element.hasClass('bg') && scope.member.onSelect !== undefined) { + scope.member.onSelect(scope.member); + } + if (element.find('a').eq(0).hasClass('active') && scope.member.onExpand !== undefined) { + var eValue = scope.member.onExpand(scope.member); + } + if (!element.find('a').eq(0).hasClass('active') && scope.member.onCollapse !== undefined) { + scope.member.onCollapse(scope.member); + } + }); + } + } +}]) + .directive('b2bTreeLink', ['keymap', '$timeout', function (keymap, $timeout) { + return { + restrict: 'A', + link: function (scope, element, attr, ctrl) { + var rootE, parentE, upE, downE; + var closeOthersUp = function (elem,isKeyPress,passiveClose) { + //For accordion functionality on sibling nodes + if (elem.find('a').eq(0).hasClass('active')) { + activeToggle(elem,isKeyPress,passiveClose); + return; + } + if (elem.hasClass('bg') && !isKeyPress) { + elem.removeClass('bg'); + if (elem.attr('aria-selected')) { + elem.attr('aria-selected', 'false'); + } + } + if (elem[0].previousElementSibling !== null) { + closeOthersUp(angular.element(elem[0].previousElementSibling),isKeyPress); + } + }; + var closeOthersDown = function (elem,isKeyPress,passiveClose) { + //For accordion functionality on sibling nodes + if (elem.find('a').eq(0).hasClass('active')) { + activeToggle(elem,isKeyPress,passiveClose); + return; + } + if (elem.hasClass('bg') && !isKeyPress) { + elem.removeClass('bg'); + if (elem.attr('aria-selected')) { + elem.attr('aria-selected', 'false'); + } + } + if (elem[0].nextElementSibling !== null) { + closeOthersDown(angular.element(elem[0].nextElementSibling),isKeyPress); + } + }; + + + var removeBackground = function(elem){ + + if(elem.hasClass('b2b-tree')){ + angular.element(elem[0].getElementsByClassName('bg')).removeClass('bg'); + return; + }else{ + removeBackground(elem.parent().parent()); + } + + }; + +/** +* These two functions used for setting heights on parent nodes as the child node closes +* Retaining this code for future reference + + var addParentHeight = function(e, h) { + var parentLi = e.parent().parent(); + var parentUl = e.parent(); + if(!parentLi.hasClass('b2b-tree')) { + var addHeight = parentUl[0].offsetHeight + h; + parentLi.find('ul').eq(0).css({ + height: addHeight+'px' + }) + addParentHeight(parentLi, h); + } + }; + + var removeParentHeight = function(e, h) { + var parentLi = e.parent().parent(); + var parentUl = e.parent(); + if(!parentLi.hasClass('b2b-tree')) { + var addHeight = parentUl[0].offsetHeight - h; + parentLi.find('ul').eq(0).css({ + height: addHeight+'px' + }) + removeParentHeight(parentLi, h); + } + }; +*/ + + // isKeyPress - to notify that the function is called by Right Key press + // passiveClose - prevents firing of oncollapse events during the action + // of expand function(check the function definition) + + var activeToggle = function (elem,isKeyPress,passiveClose) { + var element = elem.find('a').eq(0); + if (element.hasClass('active')) { + if(!isKeyPress){ + elem.removeClass('bg'); + } + + if (elem.attr('aria-selected') && !isKeyPress) { + elem.attr('aria-selected', 'false'); + } + if (!element.find('i').eq(0).hasClass('icon-circle')) { + if(isKeyPress && scope.member){ + if (scope.member.onCollapse !== undefined && !passiveClose) { + scope.member.onCollapse(scope.member); + } + } + element.removeClass('active'); + elem.attr('aria-expanded', 'false'); + element.find('i').eq(0).removeClass('icon-expanded'); + element.find('i').eq(0).addClass('icon-collapsed'); + //For Animation: below commented code is used to manually set height of UL to zero + //retaining code for future reference + /* + var totalHeight = elem.find('ul')[0].scrollHeight; + removeParentHeight(elem, totalHeight); + elem.find('ul').eq(0).css({ + height: null + });*/ + } + } else { + if(!isKeyPress){ + elem.addClass('bg'); + elem.attr('aria-selected', 'true'); + } + + if (!element.find('i').eq(0).hasClass('icon-circle')) { + if(isKeyPress){ + if(typeof scope.showChild === 'function' ){ + scope.showChild(); + } + if(scope.member){ + if (scope.member.onExpand !== undefined) { + scope.member.onExpand(scope.member); + } + } + } + element.addClass('active'); + elem.attr('aria-expanded', 'true'); + element.find('i').eq(0).removeClass('icon-collapsed'); + element.find('i').eq(0).addClass('icon-expanded'); + //For Animation: below commented code is used to manually set height of the ul generatedon the click of parent LI. + //retaining code for future reference + /* + var totalHeight = elem.find('ul')[0].scrollHeight; + addParentHeight(elem, totalHeight); + elem.find('ul').eq(0).css({ + height: totalHeight+'px' + });*/ + + } + } + }; + element.bind('click', function (evt) { + //first we close others and then we open the clicked element + if (element[0].previousElementSibling) { + closeOthersUp(angular.element(element[0].previousElementSibling)); + } + if (element[0].nextElementSibling) { + closeOthersDown(angular.element(element[0].nextElementSibling)); + } + removeBackground(element); + activeToggle(element); + + evt.stopPropagation(); + }); + //default root tree element tabindex set zero + if (element.parent().parent().hasClass('b2b-tree') && (element.parent()[0].previousElementSibling === null)) { + element.attr('tabindex', 0); + } + //check root via class + var isRoot = function (elem) { + if (elem.parent().parent().eq(0).hasClass('b2b-tree')) { + return true; + } else { + return false; + } + }; + var findRoot = function (elem) { + if (isRoot(elem)) { + rootE = elem; + return; + } + findRoot(elem.parent()); + }; + + var findPreActive = function (elem) { + + if (!(elem.hasClass("active"))) { + return; + } else { + var childElems = angular.element(elem[0].nextElementSibling.children); + lastE = angular.element(childElems[childElems.length - 1]); + if (lastE.find('a').eq(0).hasClass('active')) { + findPreActive(lastE.find('a').eq(0)); + } + upE = lastE; + } + }; + + var findUp = function (elem) { + if (isRoot(elem)) { + upE = elem; + return; + } + if (elem[0].previousElementSibling !== null && !angular.element(elem[0].previousElementSibling).hasClass('tree-hide')) { + upE = angular.element(elem[0].previousElementSibling); + if (upE.find('a').eq(0).hasClass('active')) { + findPreActive(upE.find('a').eq(0)); + } + } else { + upE = elem.parent().parent(); + } + }; + + var downElement = function (elem) { + if (elem.next().hasClass('tree-hide')) { + downElement(elem.next()); + } else { + downE = elem.next(); + } + } + var isBottomElem = false; + var downParent = function(liElem){ + if(liElem.eq(0).parent().parent().eq(0).hasClass('b2b-tree')){ + isBottomElem = true; + return; + } + if(liElem.next().length !== 0){ + downE = liElem.next().eq(0); + return; + } + else { + downParent(liElem.parent().parent()); + } + } + + var findDown = function (elem) { + if (isRoot(elem.parent()) && !elem.hasClass('active')) { + downE = elem.parent(); + return; + } + if (elem.hasClass('active')) { + downE = elem.next().find('li').eq(0); + if (downE.hasClass('tree-hide')) { + downElement(downE); + } + + } else { + downParent(elem.parent()); + if(isBottomElem === true){ + downE = elem.parent(); + isBottomElem = false; + } + } + }; + + + var resetTabPosition = function(element){ + findRoot(element); + angular.element(rootE.parent().parent()[0].querySelector("li[tabindex='0']")).attr('tabindex','-1'); + var elemToFocus = rootE.parent().parent()[0].querySelector(".bg")|| rootE; + + angular.element(elemToFocus).attr('tabindex','0'); + }; + // Function to control the expansion of nodes when the user tabs into the tree and + // the slected node is not visible + var expand = function(elemArr){ + var elem= elemArr.pop(); + var element = elem.find('a').eq(0); + var selectedNode = elem.parent().parent()[0].querySelector(".bg"); + if(selectedNode != null){ + while(elem){ + element = elem.find('a').eq(0); + if(!element.hasClass('active') ){ + + + if (elem[0].previousElementSibling) { + closeOthersUp(angular.element(elem[0].previousElementSibling),true,true); + } + if (elem[0].nextElementSibling) { + closeOthersDown(angular.element(elem[0].nextElementSibling),true,true); + } + + if (!element.find('i').eq(0).hasClass('icon-circle')) { + if(typeof scope.showChild === 'function' ){ + scope.showChild(); + } + element.addClass('active'); + elem.attr('aria-expanded', 'true'); + element.find('i').eq(0).removeClass('icon-collapsed'); + element.find('i').eq(0).addClass('icon-expanded'); + } + + } + elem = elemArr.pop(); + } + + }else{ + return; + } + }; + + element.find('a').eq(0).bind('mouseenter', function (evt) { + angular.forEach(document.querySelectorAll('.activeTooltip'), function(value, key) { + angular.element(value).removeClass('activeTooltip') + }); + element.addClass('activeTooltip'); + }); + element.find('a').eq(0).bind('mouseleave', function (evt) { + element.removeClass('activeTooltip'); + }); + element.bind('focus', function (evt) { + angular.forEach(document.querySelectorAll('.activeTooltip'), function(value, key) { + angular.element(value).removeClass('activeTooltip') + }); + element.addClass('activeTooltip'); + }); + element.bind('blur', function (evt) { + element.removeClass('activeTooltip'); + }); + element.bind('keydown', function (evt) { + switch (evt.keyCode) { + case keymap.KEY.HOME: + evt.preventDefault(); + evt.stopPropagation(); + element.attr('tabindex', -1); + findRoot(element); + rootE.eq(0).attr('tabindex', 0); + rootE[0].focus(); + break; + case keymap.KEY.LEFT: + evt.preventDefault(); + evt.stopPropagation(); + + if(element.find('a').eq(0).hasClass('active')){ + if (element[0].previousElementSibling) { + closeOthersUp(angular.element(element[0].previousElementSibling),true); + } + if (element[0].nextElementSibling) { + closeOthersDown(angular.element(element[0].nextElementSibling),true); + } + activeToggle(element,true); + return; + } + element.attr('tabindex', -1); + parentE = element.parent().parent(); + parentE.attr('tabindex', 0); + parentE[0].focus(); + break; + case keymap.KEY.UP: + evt.preventDefault(); + evt.stopPropagation(); + element.attr('tabindex', -1); + findUp(element); + upE.eq(0).attr('tabindex', 0); + upE[0].focus(); + break; + case keymap.KEY.RIGHT: + evt.preventDefault(); + evt.stopPropagation(); + if(element.find('i').eq(0).hasClass('icon-circle')){ + break; + } + if (!element.find('a').eq(0).hasClass('active')) { + if (element[0].previousElementSibling) { + closeOthersUp(angular.element(element[0].previousElementSibling),true); + } + if (element[0].nextElementSibling) { + closeOthersDown(angular.element(element[0].nextElementSibling),true); + } + activeToggle(element,true); + + } + else { + element.attr('tabindex', -1); + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + } + break; + case keymap.KEY.DOWN: + evt.preventDefault(); + element.attr('tabindex', -1); + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + evt.stopPropagation(); + break; + case keymap.KEY.ENTER: + var isSelectedElem = element.hasClass('bg'); + var enterFunc = function(element){ + if (isSelectedElem) { + element.removeClass('bg'); + if (element.attr('aria-selected')) { + element.attr('aria-selected', 'false'); + } + } + else { + element.addClass('bg'); + element.attr('aria-selected', 'true'); + } + }; + if (element[0].previousElementSibling) { + closeOthersUp(angular.element(element[0].previousElementSibling)); + } + if (element[0].nextElementSibling) { + closeOthersDown(angular.element(element[0].nextElementSibling)); + } + + removeBackground(element); + enterFunc(element); + evt.stopPropagation(); + break; + case keymap.KEY.TAB: + $timeout(function(){ + resetTabPosition(element); + },0); + evt.stopPropagation(); + + break; + default: + break; + } + }); + element.bind('keyup',function(evt){ + if(evt.keyCode === keymap.KEY.TAB){ + + var tempElem = element; + var elemArr = []; + while(!tempElem.hasClass('b2b-tree')){ + elemArr.push(tempElem); + tempElem = tempElem.parent().parent(); + } + elemArr.push(tempElem); + + expand(elemArr); + } + evt.stopPropagation(); + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Navigation.att:Tree nodes with checkboxes + * + * @param {String} setRole - The value needs to be "tree". This is required to incorporate CATO requirements. + * @param {boolean} groupIt - The value needs to be "false" for top-level tree rendered. + * @param {Object} collection - The JSON object of tree to be rendered. + * @description + * + * + * @usage + *
    + * + *
    + * @example + *
    + + + + +
    + * + */ +angular.module('b2b.att.treeNodeCheckbox', ['b2b.att.utilities']) + .directive('b2bTreeNodeCheckbox', function () { + return { + restrict: "E", + replace: true, + scope: { + collection: '=', + groupIt: '=', + setRole: '@' + }, + templateUrl: function (element, attrs) { + if (attrs.groupIt === 'true') { + return "b2bTemplate/treeNodeCheckbox/groupedTree.html"; + } else { + return "b2bTemplate/treeNodeCheckbox/ungroupedTree.html"; + } + }, + link: function (scope) { + if (!(scope.setRole === 'tree')) { + scope.setRole = 'group'; + } + } + } + }) + .directive('b2bTreeMember', ['$compile', '$timeout', 'keymap', function ($compile, $timeout, keymap) { + return { + restrict: "E", + replace: true, + scope: { + member: '=', + groupIt: '=' + }, + templateUrl: 'b2bTemplate/treeNodeCheckbox/treeMember.html', + link: function (scope, element, attrs) { + scope.elemArr = []; + var removeRootTabIndex = function (elem) { + if (elem.parent().parent().eq(0).hasClass('b2b-tree-checkbox')) { + elem.attr('tabindex', -1); + return; + } + removeRootTabIndex(elem.parent()); + }; + scope.$watch('member.child', function(newVal, oldVal){ + if(newVal !== oldVal){ + scope.showChild(); + }; + }); + + var checkedCount = 0; + var nonCheckedCount = 0; + var checkBoxesCount = 0; + + if(element.find('a').eq(0).find('input')){ + if(scope.member.indeterminate){ + element.find('a').eq(0).find('input').prop('indeterminate', true); + element.attr('aria-checked',"mixed"); + } + element.attr('aria-checked',scope.member.isSelected); + } + + element.find('a').eq(0).find('input').bind('change',function(){ + scope.member.indeterminate = false; + downwardModalUpdate(scope.member); + downwardSelection(element); + upwardSelection(element); + element.attr('aria-checked',scope.member.isSelected); + if (scope.member.onSelect !== undefined) { + scope.member.onSelect(scope.member); + } + }); + + element.find('a').eq(0).find('input').bind('click',function(){ + var elem = angular.element(this); + if(scope.member.indeterminate){ + scope.member.indeterminate = false; + scope.member.isSelected = true; + elem.prop('indeterminate', false); + elem.prop('checked', true); + elem.triggerHandler('change'); + } + }); + + var groupNode = false; + var checkedTreeNode = false; + + var isCheckboxSelected = function(elem){ + checkedTreeNode = false; + checkedTreeNode = angular.element(angular.element(elem).find('a').eq(0))[0].querySelector('input.treeCheckBox').checked; + } + + var findCheckbox = function(elem){ + return angular.element(angular.element(elem).find('a').eq(0))[0].querySelector('input.treeCheckBox'); + } + + var updateGrpNodeCheckboxes = function(elem, checked){ + angular.element(angular.element(elem).find('a').eq(0))[0].querySelector('input.treeCheckBox').checked = checked; + } + + + var isGroupNode = function(elem){ + groupNode = false; + if(angular.element(angular.element(elem).find('a').eq(0))[0].querySelector('input.grpTreeCheckbox')){ + groupNode = true; + } + } + + var downwardModalUpdate = function(curMember){ + angular.forEach(curMember.child, function(childMember, key) { + childMember.isSelected = curMember.isSelected; + childMember.indeterminate = false; + if(angular.isArray(childMember.child) && scope.member.child.length > 0){ + downwardModalUpdate(childMember); + } + }); + } + + var downwardSelection = function(elem){ + if(findCheckbox(elem)){ + isCheckboxSelected(elem) + } + if(angular.element(elem).find('ul').length > 0){ + var childNodes = angular.element(elem).find('ul').eq(0).children('li'); + for(var i=0; i 0 && (scope.member.divide === undefined || scope.member.child.length < scope.member.divide)) { + scope.groupIt = false; + element.addClass('grouped'); + element.append(""); + $compile(element.contents())(scope); + if(scope.member.active && scope.member.active === true){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).removeClass('icon-collapsed'); + }; + if(scope.member.selected && scope.member.selected === true){ + element.attr('tabindex', 0); + removeRootTabIndex(element); + }; + if(scope.member.active && scope.member.active == undefined){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-collapsed'); + }; + } else if (scope.member.child && scope.member.divide && scope.member.child.length > scope.member.divide) { + element.addClass('grouped'); + scope.groupIt = true; + var j = 0; + var grpName = ''; + if(scope.member.child[0].groupName !== undefined){ + grpName = scope.member.child[0].groupName; + } + else{ + var toSlice = scope.member.child[0].name.search(' '); + grpName = scope.member.child[0].name.slice(0, toSlice); + } + + for (i = 0; i < scope.member.child.length; i += scope.member.divide) { + j = 0; + for (j = j + i; j < (i + scope.member.divide); j++) { + if (j === scope.member.child.length) { + scope.member.child[j - 1].grpChild = grpName + ' ' + (i + 1) + ' - ' + (scope.member.child.length); + break; + + if(scope.member.child[j-1].active && scope.member.child[j-1].active===true){ + scope.member.child[j-1].activeGrp = true; + }; + + } + if (i + scope.member.divide > scope.member.child.length) { + scope.member.child[j].grpChild = grpName + ' ' + (i + 1) + ' - ' + (scope.member.child.length); + if(scope.member.child[j].active && scope.member.child[j].active===true){ + scope.member.child[j].activeGrp = true; + }; + + } else { + scope.member.child[j].grpChild = grpName + ' ' + (i + 1) + ' - ' + (i + scope.member.divide); + if(scope.member.child[j].active && scope.member.child[j].active===true){ + scope.member.child[j].activeGrp = true; + }; + } + } + } + if(scope.member.divide){ + element.append(""); + } else { + element.append(""); + } + $compile(element.contents())(scope); + if(scope.member.active && scope.member.active === true){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).removeClass('icon-collapsed'); + }; + + if( scope.member.active && scope.member.active == undefined){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-collapsed'); + }; + } + } + $timeout(function () { + if(!scope.member.indeterminate){ + downwardSelection(element); + } + }); + + }; + + if(scope.member.active && scope.member.active == true){ + scope.showChild(); + }; + if(scope.member.active == undefined && !element.find('a').eq(0).hasClass('active') && scope.member.child !== undefined){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-collapsed'); + } + else if(scope.member.child == undefined){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-circle'); + if(scope.$parent.$index === 0) { + element.find('a').eq(0).append(''); + }; + }; + + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).bind('click', function (evt) { + scope.showChild(); + var expandFunc = scope.member.onExpand; + if (element.find('a').eq(0).hasClass('active') && scope.member.onExpand !== undefined) { + var eValue = scope.member.onExpand(scope.member); + } + if (!element.find('a').eq(0).hasClass('active') && scope.member.onCollapse !== undefined) { + scope.member.onCollapse(scope.member); + } + }); + + angular.element(element[0].querySelectorAll('.treeNodeName')).eq(0).bind('click', function (evt) { + + }); + + } + } +}]) + .directive('b2bTreeNodeLink', ['keymap', '$timeout', function (keymap, $timeout) { + return { + restrict: 'A', + link: function (scope, element, attr, ctrl) { + var rootE, parentE, upE, downE; + var closeOthersUp = function (elem) { + + if (elem.find('a').eq(0).hasClass('active')) { + activeToggle(elem); + return; + } + if (elem.hasClass('bg')) { + elem.removeClass('bg'); + } + if (elem[0].previousElementSibling !== null) { + closeOthersUp(angular.element(elem[0].previousElementSibling)); + } + }; + var closeOthersDown = function (elem) { + + if (elem.find('a').eq(0).hasClass('active')) { + activeToggle(elem); + return; + } + if (elem.hasClass('bg')) { + elem.removeClass('bg'); + } + if (elem[0].nextElementSibling !== null) { + closeOthersDown(angular.element(elem[0].nextElementSibling)); + } + }; + + var removeBackgroundUp = function (elem) { + + if (elem.hasClass('b2b-tree-checkbox')) { + return; + } else { + elem.parent().parent().removeClass('bg'); + removeBackgroundUp(elem.parent().parent()); + } + }; + + var removeBackgroundDown = function (elem) { + + angular.element(elem[0].querySelector('.bg')).removeClass('bg'); + }; + + + + var activeToggle = function (elem) { + var element = elem.find('a').eq(0); + if (element.hasClass('active')) { + elem.removeClass('bg'); + if (!angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).hasClass('icon-circle')) { + element.removeClass('active'); + elem.attr('aria-expanded', 'false'); + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).removeClass('icon-expanded'); + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-collapsed'); + } + } else { + elem.addClass('bg'); + if (!angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).hasClass('icon-circle')) { + element.addClass('active'); + elem.attr('aria-expanded', 'true'); + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).removeClass('icon-collapsed'); + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).addClass('icon-expanded'); + } + } + }; + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).bind('click', function (evt) { + + if (element[0].previousElementSibling) { + closeOthersUp(angular.element(element[0].previousElementSibling)); + } + if (element[0].nextElementSibling) { + closeOthersDown(angular.element(element[0].nextElementSibling)); + } + + activeToggle(element); + + removeBackgroundDown(element); + removeBackgroundUp(element); + evt.stopPropagation(); + }); + + if (element.parent().parent().hasClass('b2b-tree-checkbox') && (element.parent()[0].previousElementSibling === null)) { + element.attr('tabindex', 0); + } + + var isRoot = function (elem) { + if (elem.parent().parent().eq(0).hasClass('b2b-tree-checkbox')) { + return true; + } else { + return false; + } + }; + var findRoot = function (elem) { + if (isRoot(elem)) { + rootE = elem; + return; + } + findRoot(elem.parent()); + }; + + var findPreActive = function (elem) { + + if (!(elem.hasClass("active"))) { + return; + } else { + var childElems = angular.element(elem[0].nextElementSibling.children); + lastE = angular.element(childElems[childElems.length - 1]); + if (lastE.find('a').eq(0).hasClass('active')) { + findPreActive(lastE.find('a').eq(0)); + } + upE = lastE; + } + }; + + var findUp = function (elem) { + if (isRoot(elem)) { + upE = elem; + return; + } + if (elem[0].previousElementSibling !== null && !angular.element(elem[0].previousElementSibling).hasClass('tree-hide')) { + upE = angular.element(elem[0].previousElementSibling); + if (upE.find('a').eq(0).hasClass('active')) { + findPreActive(upE.find('a').eq(0)); + } + } else { + upE = elem.parent().parent(); + } + }; + + var downElement = function (elem) { + if (elem.next().hasClass('tree-hide')) { + downElement(elem.next()); + } else { + downE = elem.next(); + } + } + var isBottomElem = false; + var downParent = function(liElem){ + if(liElem.eq(0).parent().parent().eq(0).hasClass('b2b-tree-checkbox')){ + isBottomElem = true; + return; + } + if(liElem.next().length !== 0){ + downE = liElem.next().eq(0); + return; + } + else { + downParent(liElem.parent().parent()); + } + } + + var findDown = function (elem) { + if (isRoot(elem.parent()) && !elem.hasClass('active')) { + downE = elem.parent(); + return; + } + if (elem.hasClass('active')) { + downE = elem.next().find('li').eq(0); + if (downE.hasClass('tree-hide')) { + downElement(downE); + } + + } else { + downParent(elem.parent()); + if(isBottomElem === true){ + downE = elem.parent(); + isBottomElem = false; + } + } + }; + element.bind('keydown', function (evt) { + switch (evt.keyCode) { + case keymap.KEY.HOME: + evt.preventDefault(); + evt.stopPropagation(); + element.attr('tabindex', -1); + findRoot(element); + rootE.eq(0).attr('tabindex', 0); + rootE[0].focus(); + break; + case keymap.KEY.LEFT: + evt.preventDefault(); + evt.stopPropagation(); + if (!isRoot(element)) { + if(element.find('a').eq(0).hasClass('active')){ + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).triggerHandler('click'); + return; + } + element.attr('tabindex', -1); + parentE = element.parent().parent(); + parentE.attr('tabindex', 0); + parentE[0].focus(); + } else { + if (element.find('a').eq(0).hasClass('active')) { + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).triggerHandler('click'); + } + }; + break; + case keymap.KEY.UP: + evt.preventDefault(); + evt.stopPropagation(); + element.attr('tabindex', -1); + findUp(element); + upE.eq(0).attr('tabindex', 0); + upE[0].focus(); + break; + case keymap.KEY.RIGHT: + evt.preventDefault(); + evt.stopPropagation(); + if(angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).hasClass('icon-circle')){ + break; + } + if (!element.find('a').eq(0).hasClass('active')) { + angular.element(element[0].querySelectorAll('i.expandCollapseIcon')).eq(0).triggerHandler('click'); + } + else { + element.attr('tabindex', -1); + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + } + break; + case keymap.KEY.DOWN: + evt.preventDefault(); + element.attr('tabindex', -1); + findDown(element.find('a').eq(0)); + downE.eq(0).attr('tabindex', 0); + downE[0].focus(); + evt.stopPropagation(); + break; + case keymap.KEY.SPACE: + case keymap.KEY.ENTER: + evt.preventDefault(); + evt.stopPropagation(); + if(angular.isDefined(element.scope().member.isSelected)){ + element.scope().member.isSelected = !element.scope().member.isSelected; + element.scope().member.indeterminate = false; + element.scope().$apply(); + element.find('a').eq(0).find('input').prop('indeterminate', false); + element.find('a').eq(0).find('input').triggerHandler('change'); + } + break; + default: + break; + } + }); + } + }; + }]); +/** + * @ngdoc directive + * @name Progress & usage indicators.att:usageBar + * + * @description + * + * + * @usage + *
    + * +
    + 20% usage with animation + +
    +
    1/2 increments
    +
    {{usageBarIncrementedVal1}}% used
    +
    +
    +
    +
    Additional description text
    +
    + + * @example + *
    + HTML + AngularJS + + + + +
    + * + */ +angular.module('b2b.att.usageBar', ['b2b.att.utilities']) + .directive('b2bUsageBar', ['$window', '$timeout', function($window, $timeout) { + return { + restrict: 'A', + transclude: true, + scope: { + noOfSegments: '=', + barTypeClass: '@?', + msDelay: '=?' + }, + templateUrl: 'b2bTemplate/usageBar/usageBar.html', + link: function(scope, ele, attr) { + scope.changesBarValue = function(){ + if (!(angular.isNumber(scope.noOfSegments) && scope.noOfSegments > 0)) { + scope.noOfSegments = 1; + } + scope.barsArray = []; + for (var i=0; i < scope.noOfSegments; i++) { + scope.barsArray.push({showItem : true}); + } + + if (!angular.isNumber(scope.msDelay)) { + scope.msDelay = 5000; + } + + var transition = 'width ' + scope.msDelay + 'ms'; + + var animateStyle = { + '-webkit-transition': transition, + '-moz-transition': transition, + '-ms-transition': transition, + '-o-transition': transition, + transition: transition + }; + + if (attr.isAnimated) { + for (var i = 0; i < scope.barsArray.length; i++) { + angular.forEach(animateStyle, function(value, key) { + scope.barsArray[i][key] = value; + }); + } + } + + $timeout(function() { + var percentDivEach = 100/scope.noOfSegments; + + var fullBars = Math.floor(attr.b2bUsageBar / percentDivEach); + var cutOffBarWidth = attr.b2bUsageBar % percentDivEach; + var i=0; + while(i < fullBars) { + scope.barsArray[i].width = percentDivEach + '%'; + scope.barsArray[i].showItem = true; + i++; + } + if(cutOffBarWidth > 0) { + scope.barsArray[i].width = cutOffBarWidth + '%'; + scope.barsArray[i].showItem = true; + i++; + } + while(i < scope.barsArray.length) { + scope.barsArray[i].showItem = false; + i++; + } + }); + + } + attr.$observe('b2bUsageBar',function(newValue){ + scope.changesBarValue(); + }); + scope.$watch('[noOfSegments,msDelay]',function(newValue){ + scope.changesBarValue(); + }); + scope.changesBarValue(); + } + }; + + }]); +/*! + * VERSION: 1.7.3 + * DATE: 2014-01-14 + * UPDATES AND DOCS AT: http://www.greensock.com + * + * @license Copyright (c) 2008-2014, GreenSock. All rights reserved. + * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for + * Club GreenSock members, the software agreement that was issued with your membership. + * + * @author: Jack Doyle, jack@greensock.com + **/ +(window._gsQueue || (window._gsQueue = [])).push( function() { + + "use strict"; + + var _doc = document.documentElement, + _window = window, + _max = function(element, axis) { + var dim = (axis === "x") ? "Width" : "Height", + scroll = "scroll" + dim, + client = "client" + dim, + body = document.body; + return (element === _window || element === _doc || element === body) ? Math.max(_doc[scroll], body[scroll]) - (_window["inner" + dim] || Math.max(_doc[client], body[client])) : element[scroll] - element["offset" + dim]; + }, + + ScrollToPlugin = window._gsDefine.plugin({ + propName: "scrollTo", + API: 2, + version:"1.7.3", + + //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. + init: function(target, value, tween) { + this._wdw = (target === _window); + this._target = target; + this._tween = tween; + if (typeof(value) !== "object") { + value = {y:value}; //if we don't receive an object as the parameter, assume the user intends "y". + } + this._autoKill = (value.autoKill !== false); + this.x = this.xPrev = this.getX(); + this.y = this.yPrev = this.getY(); + if (value.x != null) { + this._addTween(this, "x", this.x, (value.x === "max") ? _max(target, "x") : value.x, "scrollTo_x", true); + this._overwriteProps.push("scrollTo_x"); + } else { + this.skipX = true; + } + if (value.y != null) { + this._addTween(this, "y", this.y, (value.y === "max") ? _max(target, "y") : value.y, "scrollTo_y", true); + this._overwriteProps.push("scrollTo_y"); + } else { + this.skipY = true; + } + return true; + }, + + //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) + set: function(v) { + this._super.setRatio.call(this, v); + + var x = (this._wdw || !this.skipX) ? this.getX() : this.xPrev, + y = (this._wdw || !this.skipY) ? this.getY() : this.yPrev, + yDif = y - this.yPrev, + xDif = x - this.xPrev; + + if (this._autoKill) { + //note: iOS has a bug that throws off the scroll by several pixels, so we need to check if it's within 7 pixels of the previous one that we set instead of just looking for an exact match. + if (!this.skipX && (xDif > 7 || xDif < -7) && x < _max(this._target, "x")) { + this.skipX = true; //if the user scrolls separately, we should stop tweening! + } + if (!this.skipY && (yDif > 7 || yDif < -7) && y < _max(this._target, "y")) { + this.skipY = true; //if the user scrolls separately, we should stop tweening! + } + if (this.skipX && this.skipY) { + this._tween.kill(); + } + } + if (this._wdw) { + _window.scrollTo((!this.skipX) ? this.x : x, (!this.skipY) ? this.y : y); + } else { + if (!this.skipY) { + this._target.scrollTop = this.y; + } + if (!this.skipX) { + this._target.scrollLeft = this.x; + } + } + this.xPrev = this.x; + this.yPrev = this.y; + } + + }), + p = ScrollToPlugin.prototype; + + ScrollToPlugin.max = _max; + + p.getX = function() { + return (!this._wdw) ? this._target.scrollLeft : (_window.pageXOffset != null) ? _window.pageXOffset : (_doc.scrollLeft != null) ? _doc.scrollLeft : document.body.scrollLeft; + }; + + p.getY = function() { + return (!this._wdw) ? this._target.scrollTop : (_window.pageYOffset != null) ? _window.pageYOffset : (_doc.scrollTop != null) ? _doc.scrollTop : document.body.scrollTop; + }; + + p._kill = function(lookup) { + if (lookup.scrollTo_x) { + this.skipX = true; + } + if (lookup.scrollTo_y) { + this.skipY = true; + } + return this._super._kill.call(this, lookup); + }; + +}); if (window._gsDefine) { window._gsQueue.pop()(); } +/*! + * VERSION: 1.12.1 + * DATE: 2014-06-26 + * UPDATES AND DOCS AT: http://www.greensock.com + * + * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin + * + * @license Copyright (c) 2008-2014, GreenSock. All rights reserved. + * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for + * Club GreenSock members, the software agreement that was issued with your membership. + * + * @author: Jack Doyle, jack@greensock.com + **/ + +(window._gsQueue || (window._gsQueue = [])).push( function() { + + "use strict"; + + window._gsDefine("TweenMax", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) { + + var _slice = [].slice, + TweenMax = function(target, duration, vars) { + TweenLite.call(this, target, duration, vars); + this._cycle = 0; + this._yoyo = (this.vars.yoyo === true); + this._repeat = this.vars.repeat || 0; + this._repeatDelay = this.vars.repeatDelay || 0; + this._dirty = true; //ensures that if there is any repeat, the totalDuration will get recalculated to accurately report it. + this.render = TweenMax.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method) + }, + _tinyNum = 0.0000000001, + TweenLiteInternals = TweenLite._internals, + _isSelector = TweenLiteInternals.isSelector, + _isArray = TweenLiteInternals.isArray, + p = TweenMax.prototype = TweenLite.to({}, 0.1, {}), + _blankArray = []; + + TweenMax.version = "1.12.1"; + p.constructor = TweenMax; + p.kill()._gc = false; + TweenMax.killTweensOf = TweenMax.killDelayedCallsTo = TweenLite.killTweensOf; + TweenMax.getTweensOf = TweenLite.getTweensOf; + TweenMax.lagSmoothing = TweenLite.lagSmoothing; + TweenMax.ticker = TweenLite.ticker; + TweenMax.render = TweenLite.render; + + p.invalidate = function() { + this._yoyo = (this.vars.yoyo === true); + this._repeat = this.vars.repeat || 0; + this._repeatDelay = this.vars.repeatDelay || 0; + this._uncache(true); + return TweenLite.prototype.invalidate.call(this); + }; + + p.updateTo = function(vars, resetDuration) { + var curRatio = this.ratio, p; + if (resetDuration && this._startTime < this._timeline._time) { + this._startTime = this._timeline._time; + this._uncache(false); + if (this._gc) { + this._enabled(true, false); + } else { + this._timeline.insert(this, this._startTime - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct. + } + } + for (p in vars) { + this.vars[p] = vars[p]; + } + if (this._initted) { + if (resetDuration) { + this._initted = false; + } else { + if (this._gc) { + this._enabled(true, false); + } + if (this._notifyPluginsOfEnabled && this._firstPT) { + TweenLite._onPluginEvent("_onDisable", this); //in case a plugin like MotionBlur must perform some cleanup tasks + } + if (this._time / this._duration > 0.998) { //if the tween has finished (or come extremely close to finishing), we just need to rewind it to 0 and then render it again at the end which forces it to re-initialize (parsing the new vars). We allow tweens that are close to finishing (but haven't quite finished) to work this way too because otherwise, the values are so small when determining where to project the starting values that binary math issues creep in and can make the tween appear to render incorrectly when run backwards. + var prevTime = this._time; + this.render(0, true, false); + this._initted = false; + this.render(prevTime, true, false); + } else if (this._time > 0) { + this._initted = false; + this._init(); + var inv = 1 / (1 - curRatio), + pt = this._firstPT, endValue; + while (pt) { + endValue = pt.s + pt.c; + pt.c *= inv; + pt.s = endValue - pt.c; + pt = pt._next; + } + } + } + } + return this; + }; + + p.render = function(time, suppressEvents, force) { + if (!this._initted) if (this._duration === 0 && this.vars.repeat) { //zero duration tweens that render immediately have render() called from TweenLite's constructor, before TweenMax's constructor has finished setting _repeat, _repeatDelay, and _yoyo which are critical in determining totalDuration() so we need to call invalidate() which is a low-kb way to get those set properly. + this.invalidate(); + } + var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), + prevTime = this._time, + prevTotalTime = this._totalTime, + prevCycle = this._cycle, + duration = this._duration, + prevRawPrevTime = this._rawPrevTime, + isComplete, callback, pt, cycleDuration, r, type, pow, rawPrevTime, i; + if (time >= totalDur) { + this._totalTime = totalDur; + this._cycle = this._repeat; + if (this._yoyo && (this._cycle & 1) !== 0) { + this._time = 0; + this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0; + } else { + this._time = duration; + this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1; + } + if (!this._reversed) { + isComplete = true; + callback = "onComplete"; + } + if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. + if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate. + time = 0; + } + if (time === 0 || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time) { + force = true; + if (prevRawPrevTime > _tinyNum) { + callback = "onReverseComplete"; + } + } + this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + } + + } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. + this._totalTime = this._time = this._cycle = 0; + this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0; + if (prevTotalTime !== 0 || (duration === 0 && prevRawPrevTime > 0 && prevRawPrevTime !== _tinyNum)) { + callback = "onReverseComplete"; + isComplete = this._reversed; + } + if (time < 0) { + this._active = false; + if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. + if (prevRawPrevTime >= 0) { + force = true; + } + this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + } + } else if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. + force = true; + } + } else { + this._totalTime = this._time = time; + + if (this._repeat !== 0) { + cycleDuration = duration + this._repeatDelay; + this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) + if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration) { + this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) + } + this._time = this._totalTime - (this._cycle * cycleDuration); + if (this._yoyo) if ((this._cycle & 1) !== 0) { + this._time = duration - this._time; + } + if (this._time > duration) { + this._time = duration; + } else if (this._time < 0) { + this._time = 0; + } + } + + if (this._easeType) { + r = this._time / duration; + type = this._easeType; + pow = this._easePower; + if (type === 1 || (type === 3 && r >= 0.5)) { + r = 1 - r; + } + if (type === 3) { + r *= 2; + } + if (pow === 1) { + r *= r; + } else if (pow === 2) { + r *= r * r; + } else if (pow === 3) { + r *= r * r * r; + } else if (pow === 4) { + r *= r * r * r * r; + } + + if (type === 1) { + this.ratio = 1 - r; + } else if (type === 2) { + this.ratio = r; + } else if (this._time / duration < 0.5) { + this.ratio = r / 2; + } else { + this.ratio = 1 - (r / 2); + } + + } else { + this.ratio = this._ease.getRatio(this._time / duration); + } + + } + + if (prevTime === this._time && !force && prevCycle === this._cycle) { + if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate. + this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray); + } + return; + } else if (!this._initted) { + this._init(); + if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example. + return; + } else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) { //we stick it in the queue for rendering at the very end of the tick - this is a performance optimization because browsers invalidate styles and force a recalculation if you read, write, and then read style data (so it's better to read/read/read/write/write/write than read/write/read/write/read/write). The down side, of course, is that usually you WANT things to render immediately because you may have code running right after that which depends on the change. Like imagine running TweenLite.set(...) and then immediately after that, creating a nother tween that animates the same property to another value; the starting values of that 2nd tween wouldn't be accurate if lazy is true. + this._time = prevTime; + this._totalTime = prevTotalTime; + this._rawPrevTime = prevRawPrevTime; + this._cycle = prevCycle; + TweenLiteInternals.lazyTweens.push(this); + this._lazy = time; + return; + } + //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently. + if (this._time && !isComplete) { + this.ratio = this._ease.getRatio(this._time / duration); + } else if (isComplete && this._ease._calcEnd) { + this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1); + } + } + if (this._lazy !== false) { + this._lazy = false; + } + + if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) { + this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. + } + if (prevTotalTime === 0) { + if (this._initted === 2 && time > 0) { + //this.invalidate(); + this._init(); //will just apply overwriting since _initted of (2) means it was a from() tween that had immediateRender:true + } + if (this._startAt) { + if (time >= 0) { + this._startAt.render(time, suppressEvents, force); + } else if (!callback) { + callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area. + } + } + if (this.vars.onStart) if (this._totalTime !== 0 || duration === 0) if (!suppressEvents) { + this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || _blankArray); + } + } + + pt = this._firstPT; + while (pt) { + if (pt.f) { + pt.t[pt.p](pt.c * this.ratio + pt.s); + } else { + pt.t[pt.p] = pt.c * this.ratio + pt.s; + } + pt = pt._next; + } + + if (this._onUpdate) { + if (time < 0) if (this._startAt && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values. + this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete. + } + if (!suppressEvents) if (this._totalTime !== prevTotalTime || isComplete) { + this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray); + } + } + if (this._cycle !== prevCycle) if (!suppressEvents) if (!this._gc) if (this.vars.onRepeat) { + this.vars.onRepeat.apply(this.vars.onRepeatScope || this, this.vars.onRepeatParams || _blankArray); + } + if (callback) if (!this._gc) { //check gc because there's a chance that kill() could be called in an onUpdate + if (time < 0 && this._startAt && !this._onUpdate && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values. + this._startAt.render(time, suppressEvents, force); + } + if (isComplete) { + if (this._timeline.autoRemoveChildren) { + this._enabled(false, false); + } + this._active = false; + } + if (!suppressEvents && this.vars[callback]) { + this.vars[callback].apply(this.vars[callback + "Scope"] || this, this.vars[callback + "Params"] || _blankArray); + } + if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless. + this._rawPrevTime = 0; + } + } + }; + +//---- STATIC FUNCTIONS ----------------------------------------------------------------------------------------------------------- + + TweenMax.to = function(target, duration, vars) { + return new TweenMax(target, duration, vars); + }; + + TweenMax.from = function(target, duration, vars) { + vars.runBackwards = true; + vars.immediateRender = (vars.immediateRender != false); + return new TweenMax(target, duration, vars); + }; + + TweenMax.fromTo = function(target, duration, fromVars, toVars) { + toVars.startAt = fromVars; + toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); + return new TweenMax(target, duration, toVars); + }; + + TweenMax.staggerTo = TweenMax.allTo = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + stagger = stagger || 0; + var delay = vars.delay || 0, + a = [], + finalComplete = function() { + if (vars.onComplete) { + vars.onComplete.apply(vars.onCompleteScope || this, arguments); + } + onCompleteAll.apply(onCompleteAllScope || this, onCompleteAllParams || _blankArray); + }, + l, copy, i, p; + if (!_isArray(targets)) { + if (typeof(targets) === "string") { + targets = TweenLite.selector(targets) || targets; + } + if (_isSelector(targets)) { + targets = _slice.call(targets, 0); + } + } + l = targets.length; + for (i = 0; i < l; i++) { + copy = {}; + for (p in vars) { + copy[p] = vars[p]; + } + copy.delay = delay; + if (i === l - 1 && onCompleteAll) { + copy.onComplete = finalComplete; + } + a[i] = new TweenMax(targets[i], duration, copy); + delay += stagger; + } + return a; + }; + + TweenMax.staggerFrom = TweenMax.allFrom = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + vars.runBackwards = true; + vars.immediateRender = (vars.immediateRender != false); + return TweenMax.staggerTo(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope); + }; + + TweenMax.staggerFromTo = TweenMax.allFromTo = function(targets, duration, fromVars, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + toVars.startAt = fromVars; + toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); + return TweenMax.staggerTo(targets, duration, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope); + }; + + TweenMax.delayedCall = function(delay, callback, params, scope, useFrames) { + return new TweenMax(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, onCompleteScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, onReverseCompleteScope:scope, immediateRender:false, useFrames:useFrames, overwrite:0}); + }; + + TweenMax.set = function(target, vars) { + return new TweenMax(target, 0, vars); + }; + + TweenMax.isTweening = function(target) { + return (TweenLite.getTweensOf(target, true).length > 0); + }; + + var _getChildrenOf = function(timeline, includeTimelines) { + var a = [], + cnt = 0, + tween = timeline._first; + while (tween) { + if (tween instanceof TweenLite) { + a[cnt++] = tween; + } else { + if (includeTimelines) { + a[cnt++] = tween; + } + a = a.concat(_getChildrenOf(tween, includeTimelines)); + cnt = a.length; + } + tween = tween._next; + } + return a; + }, + getAllTweens = TweenMax.getAllTweens = function(includeTimelines) { + return _getChildrenOf(Animation._rootTimeline, includeTimelines).concat( _getChildrenOf(Animation._rootFramesTimeline, includeTimelines) ); + }; + + TweenMax.killAll = function(complete, tweens, delayedCalls, timelines) { + if (tweens == null) { + tweens = true; + } + if (delayedCalls == null) { + delayedCalls = true; + } + var a = getAllTweens((timelines != false)), + l = a.length, + allTrue = (tweens && delayedCalls && timelines), + isDC, tween, i; + for (i = 0; i < l; i++) { + tween = a[i]; + if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) { + if (complete) { + tween.totalTime(tween._reversed ? 0 : tween.totalDuration()); + } else { + tween._enabled(false, false); + } + } + } + }; + + TweenMax.killChildTweensOf = function(parent, complete) { + if (parent == null) { + return; + } + var tl = TweenLiteInternals.tweenLookup, + a, curParent, p, i, l; + if (typeof(parent) === "string") { + parent = TweenLite.selector(parent) || parent; + } + if (_isSelector(parent)) { + parent = _slice.call(parent, 0); + } + if (_isArray(parent)) { + i = parent.length; + while (--i > -1) { + TweenMax.killChildTweensOf(parent[i], complete); + } + return; + } + a = []; + for (p in tl) { + curParent = tl[p].target.parentNode; + while (curParent) { + if (curParent === parent) { + a = a.concat(tl[p].tweens); + } + curParent = curParent.parentNode; + } + } + l = a.length; + for (i = 0; i < l; i++) { + if (complete) { + a[i].totalTime(a[i].totalDuration()); + } + a[i]._enabled(false, false); + } + }; + + var _changePause = function(pause, tweens, delayedCalls, timelines) { + tweens = (tweens !== false); + delayedCalls = (delayedCalls !== false); + timelines = (timelines !== false); + var a = getAllTweens(timelines), + allTrue = (tweens && delayedCalls && timelines), + i = a.length, + isDC, tween; + while (--i > -1) { + tween = a[i]; + if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) { + tween.paused(pause); + } + } + }; + + TweenMax.pauseAll = function(tweens, delayedCalls, timelines) { + _changePause(true, tweens, delayedCalls, timelines); + }; + + TweenMax.resumeAll = function(tweens, delayedCalls, timelines) { + _changePause(false, tweens, delayedCalls, timelines); + }; + + TweenMax.globalTimeScale = function(value) { + var tl = Animation._rootTimeline, + t = TweenLite.ticker.time; + if (!arguments.length) { + return tl._timeScale; + } + value = value || _tinyNum; //can't allow zero because it'll throw the math off + tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value); + tl = Animation._rootFramesTimeline; + t = TweenLite.ticker.frame; + tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value); + tl._timeScale = Animation._rootTimeline._timeScale = value; + return value; + }; + + +//---- GETTERS / SETTERS ---------------------------------------------------------------------------------------------------------- + + p.progress = function(value) { + return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), false); + }; + + p.totalProgress = function(value) { + return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, false); + }; + + p.time = function(value, suppressEvents) { + if (!arguments.length) { + return this._time; + } + if (this._dirty) { + this.totalDuration(); + } + if (value > this._duration) { + value = this._duration; + } + if (this._yoyo && (this._cycle & 1) !== 0) { + value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay)); + } else if (this._repeat !== 0) { + value += this._cycle * (this._duration + this._repeatDelay); + } + return this.totalTime(value, suppressEvents); + }; + + p.duration = function(value) { + if (!arguments.length) { + return this._duration; //don't set _dirty = false because there could be repeats that haven't been factored into the _totalDuration yet. Otherwise, if you create a repeated TweenMax and then immediately check its duration(), it would cache the value and the totalDuration would not be correct, thus repeats wouldn't take effect. + } + return Animation.prototype.duration.call(this, value); + }; + + p.totalDuration = function(value) { + if (!arguments.length) { + if (this._dirty) { + //instead of Infinity, we use 999999999999 so that we can accommodate reverses + this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat); + this._dirty = false; + } + return this._totalDuration; + } + return (this._repeat === -1) ? this : this.duration( (value - (this._repeat * this._repeatDelay)) / (this._repeat + 1) ); + }; + + p.repeat = function(value) { + if (!arguments.length) { + return this._repeat; + } + this._repeat = value; + return this._uncache(true); + }; + + p.repeatDelay = function(value) { + if (!arguments.length) { + return this._repeatDelay; + } + this._repeatDelay = value; + return this._uncache(true); + }; + + p.yoyo = function(value) { + if (!arguments.length) { + return this._yoyo; + } + this._yoyo = value; + return this; + }; + + + return TweenMax; + + }, true); + + + + + + + + +/* + * ---------------------------------------------------------------- + * TimelineLite + * ---------------------------------------------------------------- + */ + window._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) { + + var TimelineLite = function(vars) { + SimpleTimeline.call(this, vars); + this._labels = {}; + this.autoRemoveChildren = (this.vars.autoRemoveChildren === true); + this.smoothChildTiming = (this.vars.smoothChildTiming === true); + this._sortChildren = true; + this._onUpdate = this.vars.onUpdate; + var v = this.vars, + val, p; + for (p in v) { + val = v[p]; + if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) { + v[p] = this._swapSelfInParams(val); + } + } + if (_isArray(v.tweens)) { + this.add(v.tweens, 0, v.align, v.stagger); + } + }, + _tinyNum = 0.0000000001, + _isSelector = TweenLite._internals.isSelector, + _isArray = TweenLite._internals.isArray, + _blankArray = [], + _globals = window._gsDefine.globals, + _copy = function(vars) { + var copy = {}, p; + for (p in vars) { + copy[p] = vars[p]; + } + return copy; + }, + _pauseCallback = function(tween, callback, params, scope) { + tween._timeline.pause(tween._startTime); + if (callback) { + callback.apply(scope || tween._timeline, params || _blankArray); + } + }, + _slice = _blankArray.slice, + p = TimelineLite.prototype = new SimpleTimeline(); + + TimelineLite.version = "1.12.1"; + p.constructor = TimelineLite; + p.kill()._gc = false; + + p.to = function(target, duration, vars, position) { + var Engine = (vars.repeat && _globals.TweenMax) || TweenLite; + return duration ? this.add( new Engine(target, duration, vars), position) : this.set(target, vars, position); + }; + + p.from = function(target, duration, vars, position) { + return this.add( ((vars.repeat && _globals.TweenMax) || TweenLite).from(target, duration, vars), position); + }; + + p.fromTo = function(target, duration, fromVars, toVars, position) { + var Engine = (toVars.repeat && _globals.TweenMax) || TweenLite; + return duration ? this.add( Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position); + }; + + p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, onCompleteScope:onCompleteAllScope, smoothChildTiming:this.smoothChildTiming}), + i; + if (typeof(targets) === "string") { + targets = TweenLite.selector(targets) || targets; + } + if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array. + targets = _slice.call(targets, 0); + } + stagger = stagger || 0; + for (i = 0; i < targets.length; i++) { + if (vars.startAt) { + vars.startAt = _copy(vars.startAt); + } + tl.to(targets[i], duration, _copy(vars), i * stagger); + } + return this.add(tl, position); + }; + + p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + vars.immediateRender = (vars.immediateRender != false); + vars.runBackwards = true; + return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope); + }; + + p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { + toVars.startAt = fromVars; + toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); + return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope); + }; + + p.call = function(callback, params, scope, position) { + return this.add( TweenLite.delayedCall(0, callback, params, scope), position); + }; + + p.set = function(target, vars, position) { + position = this._parseTimeOrLabel(position, 0, true); + if (vars.immediateRender == null) { + vars.immediateRender = (position === this._time && !this._paused); + } + return this.add( new TweenLite(target, 0, vars), position); + }; + + TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) { + vars = vars || {}; + if (vars.smoothChildTiming == null) { + vars.smoothChildTiming = true; + } + var tl = new TimelineLite(vars), + root = tl._timeline, + tween, next; + if (ignoreDelayedCalls == null) { + ignoreDelayedCalls = true; + } + root._remove(tl, true); + tl._startTime = 0; + tl._rawPrevTime = tl._time = tl._totalTime = root._time; + tween = root._first; + while (tween) { + next = tween._next; + if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) { + tl.add(tween, tween._startTime - tween._delay); + } + tween = next; + } + root.add(tl, 0); + return tl; + }; + + p.add = function(value, position, align, stagger) { + var curTime, l, i, child, tl, beforeRawTime; + if (typeof(position) !== "number") { + position = this._parseTimeOrLabel(position, 0, true, value); + } + if (!(value instanceof Animation)) { + if ((value instanceof Array) || (value && value.push && _isArray(value))) { + align = align || "normal"; + stagger = stagger || 0; + curTime = position; + l = value.length; + for (i = 0; i < l; i++) { + if (_isArray(child = value[i])) { + child = new TimelineLite({tweens:child}); + } + this.add(child, curTime); + if (typeof(child) !== "string" && typeof(child) !== "function") { + if (align === "sequence") { + curTime = child._startTime + (child.totalDuration() / child._timeScale); + } else if (align === "start") { + child._startTime -= child.delay(); + } + } + curTime += stagger; + } + return this._uncache(true); + } else if (typeof(value) === "string") { + return this.addLabel(value, position); + } else if (typeof(value) === "function") { + value = TweenLite.delayedCall(0, value); + } else { + throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string."); + } + } + + SimpleTimeline.prototype.add.call(this, value, position); + + //if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate. + if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) { + //in case any of the ancestors had completed but should now be enabled... + tl = this; + beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect. + while (tl._timeline) { + if (beforeRawTime && tl._timeline.smoothChildTiming) { + tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it. + } else if (tl._gc) { + tl._enabled(true, false); + } + tl = tl._timeline; + } + } + + return this; + }; + + p.remove = function(value) { + if (value instanceof Animation) { + return this._remove(value, false); + } else if (value instanceof Array || (value && value.push && _isArray(value))) { + var i = value.length; + while (--i > -1) { + this.remove(value[i]); + } + return this; + } else if (typeof(value) === "string") { + return this.removeLabel(value); + } + return this.kill(null, value); + }; + + p._remove = function(tween, skipDisable) { + SimpleTimeline.prototype._remove.call(this, tween, skipDisable); + var last = this._last; + if (!last) { + this._time = this._totalTime = this._duration = this._totalDuration = 0; + } else if (this._time > last._startTime + last._totalDuration / last._timeScale) { + this._time = this.duration(); + this._totalTime = this._totalDuration; + } + return this; + }; + + p.append = function(value, offsetOrLabel) { + return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value)); + }; + + p.insert = p.insertMultiple = function(value, position, align, stagger) { + return this.add(value, position || 0, align, stagger); + }; + + p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) { + return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger); + }; + + p.addLabel = function(label, position) { + this._labels[label] = this._parseTimeOrLabel(position); + return this; + }; + + p.addPause = function(position, callback, params, scope) { + return this.call(_pauseCallback, ["{self}", callback, params, scope], this, position); + }; + + p.removeLabel = function(label) { + delete this._labels[label]; + return this; + }; + + p.getLabelTime = function(label) { + return (this._labels[label] != null) ? this._labels[label] : -1; + }; + + p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) { + var i; + //if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration(). + if (ignore instanceof Animation && ignore.timeline === this) { + this.remove(ignore); + } else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) { + i = ignore.length; + while (--i > -1) { + if (ignore[i] instanceof Animation && ignore[i].timeline === this) { + this.remove(ignore[i]); + } + } + } + if (typeof(offsetOrLabel) === "string") { + return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - this.duration() : 0, appendIfAbsent); + } + offsetOrLabel = offsetOrLabel || 0; + if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value). + i = timeOrLabel.indexOf("="); + if (i === -1) { + if (this._labels[timeOrLabel] == null) { + return appendIfAbsent ? (this._labels[timeOrLabel] = this.duration() + offsetOrLabel) : offsetOrLabel; + } + return this._labels[timeOrLabel] + offsetOrLabel; + } + offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1)); + timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : this.duration(); + } else if (timeOrLabel == null) { + timeOrLabel = this.duration(); + } + return Number(timeOrLabel) + offsetOrLabel; + }; + + p.seek = function(position, suppressEvents) { + return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false)); + }; + + p.stop = function() { + return this.paused(true); + }; + + p.gotoAndPlay = function(position, suppressEvents) { + return this.play(position, suppressEvents); + }; + + p.gotoAndStop = function(position, suppressEvents) { + return this.pause(position, suppressEvents); + }; + + p.render = function(time, suppressEvents, force) { + if (this._gc) { + this._enabled(true, false); + } + var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), + prevTime = this._time, + prevStart = this._startTime, + prevTimeScale = this._timeScale, + prevPaused = this._paused, + tween, isComplete, next, callback, internalForce; + if (time >= totalDur) { + this._totalTime = this._time = totalDur; + if (!this._reversed) if (!this._hasPausedChild()) { + isComplete = true; + callback = "onComplete"; + if (this._duration === 0) if (time === 0 || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) { + internalForce = true; + if (this._rawPrevTime > _tinyNum) { + callback = "onReverseComplete"; + } + } + } + this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. + + } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. + this._totalTime = this._time = 0; + if (prevTime !== 0 || (this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || (time < 0 && this._rawPrevTime >= 0)))) { + callback = "onReverseComplete"; + isComplete = this._reversed; + } + if (time < 0) { + this._active = false; + if (this._duration === 0) if (this._rawPrevTime >= 0 && this._first) { //zero-duration timelines are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. + internalForce = true; + } + this._rawPrevTime = time; + } else { + this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + + time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline) + if (!this._initted) { + internalForce = true; + } + } + + } else { + this._totalTime = this._time = this._rawPrevTime = time; + } + if ((this._time === prevTime || !this._first) && !force && !internalForce) { + return; + } else if (!this._initted) { + this._initted = true; + } + + if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) { + this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example. + } + + if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0) if (!suppressEvents) { + this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || _blankArray); + } + + if (this._time >= prevTime) { + tween = this._first; + while (tween) { + next = tween._next; //record it here because the value could change after rendering... + if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering + break; + } else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) { + if (!tween._reversed) { + tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); + } else { + tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); + } + } + tween = next; + } + } else { + tween = this._last; + while (tween) { + next = tween._prev; //record it here because the value could change after rendering... + if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering + break; + } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) { + if (!tween._reversed) { + tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); + } else { + tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); + } + } + tween = next; + } + } + + if (this._onUpdate) if (!suppressEvents) { + this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray); + } + + if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate + if (isComplete) { + if (this._timeline.autoRemoveChildren) { + this._enabled(false, false); + } + this._active = false; + } + if (!suppressEvents && this.vars[callback]) { + this.vars[callback].apply(this.vars[callback + "Scope"] || this, this.vars[callback + "Params"] || _blankArray); + } + } + }; + + p._hasPausedChild = function() { + var tween = this._first; + while (tween) { + if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) { + return true; + } + tween = tween._next; + } + return false; + }; + + p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) { + ignoreBeforeTime = ignoreBeforeTime || -9999999999; + var a = [], + tween = this._first, + cnt = 0; + while (tween) { + if (tween._startTime < ignoreBeforeTime) { + //do nothing + } else if (tween instanceof TweenLite) { + if (tweens !== false) { + a[cnt++] = tween; + } + } else { + if (timelines !== false) { + a[cnt++] = tween; + } + if (nested !== false) { + a = a.concat(tween.getChildren(true, tweens, timelines)); + cnt = a.length; + } + } + tween = tween._next; + } + return a; + }; + + p.getTweensOf = function(target, nested) { + var disabled = this._gc, + a = [], + cnt = 0, + tweens, i; + if (disabled) { + this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here. + } + tweens = TweenLite.getTweensOf(target); + i = tweens.length; + while (--i > -1) { + if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) { + a[cnt++] = tweens[i]; + } + } + if (disabled) { + this._enabled(false, true); + } + return a; + }; + + p._contains = function(tween) { + var tl = tween.timeline; + while (tl) { + if (tl === this) { + return true; + } + tl = tl.timeline; + } + return false; + }; + + p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) { + ignoreBeforeTime = ignoreBeforeTime || 0; + var tween = this._first, + labels = this._labels, + p; + while (tween) { + if (tween._startTime >= ignoreBeforeTime) { + tween._startTime += amount; + } + tween = tween._next; + } + if (adjustLabels) { + for (p in labels) { + if (labels[p] >= ignoreBeforeTime) { + labels[p] += amount; + } + } + } + return this._uncache(true); + }; + + p._kill = function(vars, target) { + if (!vars && !target) { + return this._enabled(false, false); + } + var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target), + i = tweens.length, + changed = false; + while (--i > -1) { + if (tweens[i]._kill(vars, target)) { + changed = true; + } + } + return changed; + }; + + p.clear = function(labels) { + var tweens = this.getChildren(false, true, true), + i = tweens.length; + this._time = this._totalTime = 0; + while (--i > -1) { + tweens[i]._enabled(false, false); + } + if (labels !== false) { + this._labels = {}; + } + return this._uncache(true); + }; + + p.invalidate = function() { + var tween = this._first; + while (tween) { + tween.invalidate(); + tween = tween._next; + } + return this; + }; + + p._enabled = function(enabled, ignoreTimeline) { + if (enabled === this._gc) { + var tween = this._first; + while (tween) { + tween._enabled(enabled, true); + tween = tween._next; + } + } + return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline); + }; + + p.duration = function(value) { + if (!arguments.length) { + if (this._dirty) { + this.totalDuration(); //just triggers recalculation + } + return this._duration; + } + if (this.duration() !== 0 && value !== 0) { + this.timeScale(this._duration / value); + } + return this; + }; + + p.totalDuration = function(value) { + if (!arguments.length) { + if (this._dirty) { + var max = 0, + tween = this._last, + prevStart = 999999999999, + prev, end; + while (tween) { + prev = tween._prev; //record it here in case the tween changes position in the sequence... + if (tween._dirty) { + tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it. + } + if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence + this.add(tween, tween._startTime - tween._delay); + } else { + prevStart = tween._startTime; + } + if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found. + max -= tween._startTime; + if (this._timeline.smoothChildTiming) { + this._startTime += tween._startTime / this._timeScale; + } + this.shiftChildren(-tween._startTime, false, -9999999999); + prevStart = 0; + } + end = tween._startTime + (tween._totalDuration / tween._timeScale); + if (end > max) { + max = end; + } + tween = prev; + } + this._duration = this._totalDuration = max; + this._dirty = false; + } + return this._totalDuration; + } + if (this.totalDuration() !== 0) if (value !== 0) { + this.timeScale(this._totalDuration / value); + } + return this; + }; + + p.usesFrames = function() { + var tl = this._timeline; + while (tl._timeline) { + tl = tl._timeline; + } + return (tl === Animation._rootFramesTimeline); + }; + + p.rawTime = function() { + return this._paused ? this._totalTime : (this._timeline.rawTime() - this._startTime) * this._timeScale; + }; + + return TimelineLite; + + }, true); + + + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * TimelineMax + * ---------------------------------------------------------------- + */ + window._gsDefine("TimelineMax", ["TimelineLite","TweenLite","easing.Ease"], function(TimelineLite, TweenLite, Ease) { + + var TimelineMax = function(vars) { + TimelineLite.call(this, vars); + this._repeat = this.vars.repeat || 0; + this._repeatDelay = this.vars.repeatDelay || 0; + this._cycle = 0; + this._yoyo = (this.vars.yoyo === true); + this._dirty = true; + }, + _tinyNum = 0.0000000001, + _blankArray = [], + _easeNone = new Ease(null, null, 1, 0), + p = TimelineMax.prototype = new TimelineLite(); + + p.constructor = TimelineMax; + p.kill()._gc = false; + TimelineMax.version = "1.12.1"; + + p.invalidate = function() { + this._yoyo = (this.vars.yoyo === true); + this._repeat = this.vars.repeat || 0; + this._repeatDelay = this.vars.repeatDelay || 0; + this._uncache(true); + return TimelineLite.prototype.invalidate.call(this); + }; + + p.addCallback = function(callback, position, params, scope) { + return this.add( TweenLite.delayedCall(0, callback, params, scope), position); + }; + + p.removeCallback = function(callback, position) { + if (callback) { + if (position == null) { + this._kill(null, callback); + } else { + var a = this.getTweensOf(callback, false), + i = a.length, + time = this._parseTimeOrLabel(position); + while (--i > -1) { + if (a[i]._startTime === time) { + a[i]._enabled(false, false); + } + } + } + } + return this; + }; + + p.tweenTo = function(position, vars) { + vars = vars || {}; + var copy = {ease:_easeNone, overwrite:(vars.delay ? 2 : 1), useFrames:this.usesFrames(), immediateRender:false},//note: set overwrite to 1 (true/all) by default unless there's a delay so that we avoid a racing situation that could happen if, for example, an onmousemove creates the same tweenTo() over and over again. + duration, p, t; + for (p in vars) { + copy[p] = vars[p]; + } + copy.time = this._parseTimeOrLabel(position); + duration = (Math.abs(Number(copy.time) - this._time) / this._timeScale) || 0.001; + t = new TweenLite(this, duration, copy); + copy.onStart = function() { + t.target.paused(true); + if (t.vars.time !== t.target.time() && duration === t.duration()) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. + t.duration( Math.abs( t.vars.time - t.target.time()) / t.target._timeScale ); + } + if (vars.onStart) { //in case the user had an onStart in the vars - we don't want to overwrite it. + vars.onStart.apply(vars.onStartScope || t, vars.onStartParams || _blankArray); + } + }; + return t; + }; + + p.tweenFromTo = function(fromPosition, toPosition, vars) { + vars = vars || {}; + fromPosition = this._parseTimeOrLabel(fromPosition); + vars.startAt = {onComplete:this.seek, onCompleteParams:[fromPosition], onCompleteScope:this}; + vars.immediateRender = (vars.immediateRender !== false); + var t = this.tweenTo(toPosition, vars); + return t.duration((Math.abs( t.vars.time - fromPosition) / this._timeScale) || 0.001); + }; + + p.render = function(time, suppressEvents, force) { + if (this._gc) { + this._enabled(true, false); + } + var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), + dur = this._duration, + prevTime = this._time, + prevTotalTime = this._totalTime, + prevStart = this._startTime, + prevTimeScale = this._timeScale, + prevRawPrevTime = this._rawPrevTime, + prevPaused = this._paused, + prevCycle = this._cycle, + tween, isComplete, next, callback, internalForce, cycleDuration; + if (time >= totalDur) { + if (!this._locked) { + this._totalTime = totalDur; + this._cycle = this._repeat; + } + if (!this._reversed) if (!this._hasPausedChild()) { + isComplete = true; + callback = "onComplete"; + if (this._duration === 0) if (time === 0 || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) { + internalForce = true; + if (prevRawPrevTime > _tinyNum) { + callback = "onReverseComplete"; + } + } + } + this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + if (this._yoyo && (this._cycle & 1) !== 0) { + this._time = time = 0; + } else { + this._time = dur; + time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added. + } + + } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. + if (!this._locked) { + this._totalTime = this._cycle = 0; + } + this._time = 0; + if (prevTime !== 0 || (dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || (time < 0 && prevRawPrevTime >= 0)) && !this._locked)) { //edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare) + callback = "onReverseComplete"; + isComplete = this._reversed; + } + if (time < 0) { + this._active = false; + if (dur === 0) if (prevRawPrevTime >= 0 && this._first) { //zero-duration timelines are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. + internalForce = true; + } + this._rawPrevTime = time; + } else { + this._rawPrevTime = (dur || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. + time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline) + if (!this._initted) { + internalForce = true; + } + } + + } else { + if (dur === 0 && prevRawPrevTime < 0) { //without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through. + internalForce = true; + } + this._time = this._rawPrevTime = time; + if (!this._locked) { + this._totalTime = time; + if (this._repeat !== 0) { + cycleDuration = dur + this._repeatDelay; + this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!) + if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration) { + this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) + } + this._time = this._totalTime - (this._cycle * cycleDuration); + if (this._yoyo) if ((this._cycle & 1) !== 0) { + this._time = dur - this._time; + } + if (this._time > dur) { + this._time = dur; + time = dur + 0.0001; //to avoid occasional floating point rounding error + } else if (this._time < 0) { + this._time = time = 0; + } else { + time = this._time; + } + } + } + } + + if (this._cycle !== prevCycle) if (!this._locked) { + /* + make sure children at the end/beginning of the timeline are rendered properly. If, for example, + a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which + would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there + could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So + we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must + ensure that zero-duration tweens at the very beginning or end of the TimelineMax work. + */ + var backwards = (this._yoyo && (prevCycle & 1) !== 0), + wrap = (backwards === (this._yoyo && (this._cycle & 1) !== 0)), + recTotalTime = this._totalTime, + recCycle = this._cycle, + recRawPrevTime = this._rawPrevTime, + recTime = this._time; + + this._totalTime = prevCycle * dur; + if (this._cycle < prevCycle) { + backwards = !backwards; + } else { + this._totalTime += dur; + } + this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method. + + this._rawPrevTime = (dur === 0) ? prevRawPrevTime - 0.0001 : prevRawPrevTime; + this._cycle = prevCycle; + this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render() + prevTime = (backwards) ? 0 : dur; + this.render(prevTime, suppressEvents, (dur === 0)); + if (!suppressEvents) if (!this._gc) { + if (this.vars.onRepeat) { + this.vars.onRepeat.apply(this.vars.onRepeatScope || this, this.vars.onRepeatParams || _blankArray); + } + } + if (wrap) { + prevTime = (backwards) ? dur + 0.0001 : -0.0001; + this.render(prevTime, true, false); + } + this._locked = false; + if (this._paused && !prevPaused) { //if the render() triggered callback that paused this timeline, we should abort (very rare, but possible) + return; + } + this._time = recTime; + this._totalTime = recTotalTime; + this._cycle = recCycle; + this._rawPrevTime = recRawPrevTime; + } + + if ((this._time === prevTime || !this._first) && !force && !internalForce) { + if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate. + this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray); + } + return; + } else if (!this._initted) { + this._initted = true; + } + + if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) { + this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example. + } + + if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0) if (!suppressEvents) { + this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || _blankArray); + } + + if (this._time >= prevTime) { + tween = this._first; + while (tween) { + next = tween._next; //record it here because the value could change after rendering... + if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering + break; + } else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) { + if (!tween._reversed) { + tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); + } else { + tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); + } + + } + tween = next; + } + } else { + tween = this._last; + while (tween) { + next = tween._prev; //record it here because the value could change after rendering... + if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering + break; + } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) { + if (!tween._reversed) { + tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); + } else { + tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); + } + } + tween = next; + } + } + + if (this._onUpdate) if (!suppressEvents) { + this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray); + } + if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate + if (isComplete) { + if (this._timeline.autoRemoveChildren) { + this._enabled(false, false); + } + this._active = false; + } + if (!suppressEvents && this.vars[callback]) { + this.vars[callback].apply(this.vars[callback + "Scope"] || this, this.vars[callback + "Params"] || _blankArray); + } + } + }; + + p.getActive = function(nested, tweens, timelines) { + if (nested == null) { + nested = true; + } + if (tweens == null) { + tweens = true; + } + if (timelines == null) { + timelines = false; + } + var a = [], + all = this.getChildren(nested, tweens, timelines), + cnt = 0, + l = all.length, + i, tween; + for (i = 0; i < l; i++) { + tween = all[i]; + if (tween.isActive()) { + a[cnt++] = tween; + } + } + return a; + }; + + + p.getLabelAfter = function(time) { + if (!time) if (time !== 0) { //faster than isNan() + time = this._time; + } + var labels = this.getLabelsArray(), + l = labels.length, + i; + for (i = 0; i < l; i++) { + if (labels[i].time > time) { + return labels[i].name; + } + } + return null; + }; + + p.getLabelBefore = function(time) { + if (time == null) { + time = this._time; + } + var labels = this.getLabelsArray(), + i = labels.length; + while (--i > -1) { + if (labels[i].time < time) { + return labels[i].name; + } + } + return null; + }; + + p.getLabelsArray = function() { + var a = [], + cnt = 0, + p; + for (p in this._labels) { + a[cnt++] = {time:this._labels[p], name:p}; + } + a.sort(function(a,b) { + return a.time - b.time; + }); + return a; + }; + + +//---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- + + p.progress = function(value) { + return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), false); + }; + + p.totalProgress = function(value) { + return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, false); + }; + + p.totalDuration = function(value) { + if (!arguments.length) { + if (this._dirty) { + TimelineLite.prototype.totalDuration.call(this); //just forces refresh + //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. + this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat); + } + return this._totalDuration; + } + return (this._repeat === -1) ? this : this.duration( (value - (this._repeat * this._repeatDelay)) / (this._repeat + 1) ); + }; + + p.time = function(value, suppressEvents) { + if (!arguments.length) { + return this._time; + } + if (this._dirty) { + this.totalDuration(); + } + if (value > this._duration) { + value = this._duration; + } + if (this._yoyo && (this._cycle & 1) !== 0) { + value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay)); + } else if (this._repeat !== 0) { + value += this._cycle * (this._duration + this._repeatDelay); + } + return this.totalTime(value, suppressEvents); + }; + + p.repeat = function(value) { + if (!arguments.length) { + return this._repeat; + } + this._repeat = value; + return this._uncache(true); + }; + + p.repeatDelay = function(value) { + if (!arguments.length) { + return this._repeatDelay; + } + this._repeatDelay = value; + return this._uncache(true); + }; + + p.yoyo = function(value) { + if (!arguments.length) { + return this._yoyo; + } + this._yoyo = value; + return this; + }; + + p.currentLabel = function(value) { + if (!arguments.length) { + return this.getLabelBefore(this._time + 0.00000001); + } + return this.seek(value, true); + }; + + return TimelineMax; + + }, true); + + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * BezierPlugin + * ---------------------------------------------------------------- + */ + (function() { + + var _RAD2DEG = 180 / Math.PI, + _r1 = [], + _r2 = [], + _r3 = [], + _corProps = {}, + Segment = function(a, b, c, d) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.da = d - a; + this.ca = c - a; + this.ba = b - a; + }, + _correlate = ",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,", + cubicToQuadratic = function(a, b, c, d) { + var q1 = {a:a}, + q2 = {}, + q3 = {}, + q4 = {c:d}, + mab = (a + b) / 2, + mbc = (b + c) / 2, + mcd = (c + d) / 2, + mabc = (mab + mbc) / 2, + mbcd = (mbc + mcd) / 2, + m8 = (mbcd - mabc) / 8; + q1.b = mab + (a - mab) / 4; + q2.b = mabc + m8; + q1.c = q2.a = (q1.b + q2.b) / 2; + q2.c = q3.a = (mabc + mbcd) / 2; + q3.b = mbcd - m8; + q4.b = mcd + (d - mcd) / 4; + q3.c = q4.a = (q3.b + q4.b) / 2; + return [q1, q2, q3, q4]; + }, + _calculateControlPoints = function(a, curviness, quad, basic, correlate) { + var l = a.length - 1, + ii = 0, + cp1 = a[0].a, + i, p1, p2, p3, seg, m1, m2, mm, cp2, qb, r1, r2, tl; + for (i = 0; i < l; i++) { + seg = a[ii]; + p1 = seg.a; + p2 = seg.d; + p3 = a[ii+1].d; + + if (correlate) { + r1 = _r1[i]; + r2 = _r2[i]; + tl = ((r2 + r1) * curviness * 0.25) / (basic ? 0.5 : _r3[i] || 0.5); + m1 = p2 - (p2 - p1) * (basic ? curviness * 0.5 : (r1 !== 0 ? tl / r1 : 0)); + m2 = p2 + (p3 - p2) * (basic ? curviness * 0.5 : (r2 !== 0 ? tl / r2 : 0)); + mm = p2 - (m1 + (((m2 - m1) * ((r1 * 3 / (r1 + r2)) + 0.5) / 4) || 0)); + } else { + m1 = p2 - (p2 - p1) * curviness * 0.5; + m2 = p2 + (p3 - p2) * curviness * 0.5; + mm = p2 - (m1 + m2) / 2; + } + m1 += mm; + m2 += mm; + + seg.c = cp2 = m1; + if (i !== 0) { + seg.b = cp1; + } else { + seg.b = cp1 = seg.a + (seg.c - seg.a) * 0.6; //instead of placing b on a exactly, we move it inline with c so that if the user specifies an ease like Back.easeIn or Elastic.easeIn which goes BEYOND the beginning, it will do so smoothly. + } + + seg.da = p2 - p1; + seg.ca = cp2 - p1; + seg.ba = cp1 - p1; + + if (quad) { + qb = cubicToQuadratic(p1, cp1, cp2, p2); + a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]); + ii += 4; + } else { + ii++; + } + + cp1 = m2; + } + seg = a[ii]; + seg.b = cp1; + seg.c = cp1 + (seg.d - cp1) * 0.4; //instead of placing c on d exactly, we move it inline with b so that if the user specifies an ease like Back.easeOut or Elastic.easeOut which goes BEYOND the end, it will do so smoothly. + seg.da = seg.d - seg.a; + seg.ca = seg.c - seg.a; + seg.ba = cp1 - seg.a; + if (quad) { + qb = cubicToQuadratic(seg.a, cp1, seg.c, seg.d); + a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]); + } + }, + _parseAnchors = function(values, p, correlate, prepend) { + var a = [], + l, i, p1, p2, p3, tmp; + if (prepend) { + values = [prepend].concat(values); + i = values.length; + while (--i > -1) { + if (typeof( (tmp = values[i][p]) ) === "string") if (tmp.charAt(1) === "=") { + values[i][p] = prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)); //accommodate relative values. Do it inline instead of breaking it out into a function for speed reasons + } + } + } + l = values.length - 2; + if (l < 0) { + a[0] = new Segment(values[0][p], 0, 0, values[(l < -1) ? 0 : 1][p]); + return a; + } + for (i = 0; i < l; i++) { + p1 = values[i][p]; + p2 = values[i+1][p]; + a[i] = new Segment(p1, 0, 0, p2); + if (correlate) { + p3 = values[i+2][p]; + _r1[i] = (_r1[i] || 0) + (p2 - p1) * (p2 - p1); + _r2[i] = (_r2[i] || 0) + (p3 - p2) * (p3 - p2); + } + } + a[i] = new Segment(values[i][p], 0, 0, values[i+1][p]); + return a; + }, + bezierThrough = function(values, curviness, quadratic, basic, correlate, prepend) { + var obj = {}, + props = [], + first = prepend || values[0], + i, p, a, j, r, l, seamless, last; + correlate = (typeof(correlate) === "string") ? ","+correlate+"," : _correlate; + if (curviness == null) { + curviness = 1; + } + for (p in values[0]) { + props.push(p); + } + //check to see if the last and first values are identical (well, within 0.05). If so, make seamless by appending the second element to the very end of the values array and the 2nd-to-last element to the very beginning (we'll remove those segments later) + if (values.length > 1) { + last = values[values.length - 1]; + seamless = true; + i = props.length; + while (--i > -1) { + p = props[i]; + if (Math.abs(first[p] - last[p]) > 0.05) { //build in a tolerance of +/-0.05 to accommodate rounding errors. For example, if you set an object's position to 4.945, Flash will make it 4.9 + seamless = false; + break; + } + } + if (seamless) { + values = values.concat(); //duplicate the array to avoid contaminating the original which the user may be reusing for other tweens + if (prepend) { + values.unshift(prepend); + } + values.push(values[1]); + prepend = values[values.length - 3]; + } + } + _r1.length = _r2.length = _r3.length = 0; + i = props.length; + while (--i > -1) { + p = props[i]; + _corProps[p] = (correlate.indexOf(","+p+",") !== -1); + obj[p] = _parseAnchors(values, p, _corProps[p], prepend); + } + i = _r1.length; + while (--i > -1) { + _r1[i] = Math.sqrt(_r1[i]); + _r2[i] = Math.sqrt(_r2[i]); + } + if (!basic) { + i = props.length; + while (--i > -1) { + if (_corProps[p]) { + a = obj[props[i]]; + l = a.length - 1; + for (j = 0; j < l; j++) { + r = a[j+1].da / _r2[j] + a[j].da / _r1[j]; + _r3[j] = (_r3[j] || 0) + r * r; + } + } + } + i = _r3.length; + while (--i > -1) { + _r3[i] = Math.sqrt(_r3[i]); + } + } + i = props.length; + j = quadratic ? 4 : 1; + while (--i > -1) { + p = props[i]; + a = obj[p]; + _calculateControlPoints(a, curviness, quadratic, basic, _corProps[p]); //this method requires that _parseAnchors() and _setSegmentRatios() ran first so that _r1, _r2, and _r3 values are populated for all properties + if (seamless) { + a.splice(0, j); + a.splice(a.length - j, j); + } + } + return obj; + }, + _parseBezierData = function(values, type, prepend) { + type = type || "soft"; + var obj = {}, + inc = (type === "cubic") ? 3 : 2, + soft = (type === "soft"), + props = [], + a, b, c, d, cur, i, j, l, p, cnt, tmp; + if (soft && prepend) { + values = [prepend].concat(values); + } + if (values == null || values.length < inc + 1) { throw "invalid Bezier data"; } + for (p in values[0]) { + props.push(p); + } + i = props.length; + while (--i > -1) { + p = props[i]; + obj[p] = cur = []; + cnt = 0; + l = values.length; + for (j = 0; j < l; j++) { + a = (prepend == null) ? values[j][p] : (typeof( (tmp = values[j][p]) ) === "string" && tmp.charAt(1) === "=") ? prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)) : Number(tmp); + if (soft) if (j > 1) if (j < l - 1) { + cur[cnt++] = (a + cur[cnt-2]) / 2; + } + cur[cnt++] = a; + } + l = cnt - inc + 1; + cnt = 0; + for (j = 0; j < l; j += inc) { + a = cur[j]; + b = cur[j+1]; + c = cur[j+2]; + d = (inc === 2) ? 0 : cur[j+3]; + cur[cnt++] = tmp = (inc === 3) ? new Segment(a, b, c, d) : new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c); + } + cur.length = cnt; + } + return obj; + }, + _addCubicLengths = function(a, steps, resolution) { + var inc = 1 / resolution, + j = a.length, + d, d1, s, da, ca, ba, p, i, inv, bez, index; + while (--j > -1) { + bez = a[j]; + s = bez.a; + da = bez.d - s; + ca = bez.c - s; + ba = bez.b - s; + d = d1 = 0; + for (i = 1; i <= resolution; i++) { + p = inc * i; + inv = 1 - p; + d = d1 - (d1 = (p * p * da + 3 * inv * (p * ca + inv * ba)) * p); + index = j * resolution + i - 1; + steps[index] = (steps[index] || 0) + d * d; + } + } + }, + _parseLengthData = function(obj, resolution) { + resolution = resolution >> 0 || 6; + var a = [], + lengths = [], + d = 0, + total = 0, + threshold = resolution - 1, + segments = [], + curLS = [], //current length segments array + p, i, l, index; + for (p in obj) { + _addCubicLengths(obj[p], a, resolution); + } + l = a.length; + for (i = 0; i < l; i++) { + d += Math.sqrt(a[i]); + index = i % resolution; + curLS[index] = d; + if (index === threshold) { + total += d; + index = (i / resolution) >> 0; + segments[index] = curLS; + lengths[index] = total; + d = 0; + curLS = []; + } + } + return {length:total, lengths:lengths, segments:segments}; + }, + + + + BezierPlugin = window._gsDefine.plugin({ + propName: "bezier", + priority: -1, + version: "1.3.2", + API: 2, + global:true, + + //gets called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. + init: function(target, vars, tween) { + this._target = target; + if (vars instanceof Array) { + vars = {values:vars}; + } + this._func = {}; + this._round = {}; + this._props = []; + this._timeRes = (vars.timeResolution == null) ? 6 : parseInt(vars.timeResolution, 10); + var values = vars.values || [], + first = {}, + second = values[0], + autoRotate = vars.autoRotate || tween.vars.orientToBezier, + p, isFunc, i, j, prepend; + + this._autoRotate = autoRotate ? (autoRotate instanceof Array) ? autoRotate : [["x","y","rotation",((autoRotate === true) ? 0 : Number(autoRotate) || 0)]] : null; + for (p in second) { + this._props.push(p); + } + + i = this._props.length; + while (--i > -1) { + p = this._props[i]; + + this._overwriteProps.push(p); + isFunc = this._func[p] = (typeof(target[p]) === "function"); + first[p] = (!isFunc) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ](); + if (!prepend) if (first[p] !== values[0][p]) { + prepend = first; + } + } + this._beziers = (vars.type !== "cubic" && vars.type !== "quadratic" && vars.type !== "soft") ? bezierThrough(values, isNaN(vars.curviness) ? 1 : vars.curviness, false, (vars.type === "thruBasic"), vars.correlate, prepend) : _parseBezierData(values, vars.type, first); + this._segCount = this._beziers[p].length; + + if (this._timeRes) { + var ld = _parseLengthData(this._beziers, this._timeRes); + this._length = ld.length; + this._lengths = ld.lengths; + this._segments = ld.segments; + this._l1 = this._li = this._s1 = this._si = 0; + this._l2 = this._lengths[0]; + this._curSeg = this._segments[0]; + this._s2 = this._curSeg[0]; + this._prec = 1 / this._curSeg.length; + } + + if ((autoRotate = this._autoRotate)) { + this._initialRotations = []; + if (!(autoRotate[0] instanceof Array)) { + this._autoRotate = autoRotate = [autoRotate]; + } + i = autoRotate.length; + while (--i > -1) { + for (j = 0; j < 3; j++) { + p = autoRotate[i][j]; + this._func[p] = (typeof(target[p]) === "function") ? target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ] : false; + } + p = autoRotate[i][2]; + this._initialRotations[i] = this._func[p] ? this._func[p].call(this._target) : this._target[p]; + } + } + this._startRatio = tween.vars.runBackwards ? 1 : 0; //we determine the starting ratio when the tween inits which is always 0 unless the tween has runBackwards:true (indicating it's a from() tween) in which case it's 1. + return true; + }, + + //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) + set: function(v) { + var segments = this._segCount, + func = this._func, + target = this._target, + notStart = (v !== this._startRatio), + curIndex, inv, i, p, b, t, val, l, lengths, curSeg; + if (!this._timeRes) { + curIndex = (v < 0) ? 0 : (v >= 1) ? segments - 1 : (segments * v) >> 0; + t = (v - (curIndex * (1 / segments))) * segments; + } else { + lengths = this._lengths; + curSeg = this._curSeg; + v *= this._length; + i = this._li; + //find the appropriate segment (if the currently cached one isn't correct) + if (v > this._l2 && i < segments - 1) { + l = segments - 1; + while (i < l && (this._l2 = lengths[++i]) <= v) { } + this._l1 = lengths[i-1]; + this._li = i; + this._curSeg = curSeg = this._segments[i]; + this._s2 = curSeg[(this._s1 = this._si = 0)]; + } else if (v < this._l1 && i > 0) { + while (i > 0 && (this._l1 = lengths[--i]) >= v) { } + if (i === 0 && v < this._l1) { + this._l1 = 0; + } else { + i++; + } + this._l2 = lengths[i]; + this._li = i; + this._curSeg = curSeg = this._segments[i]; + this._s1 = curSeg[(this._si = curSeg.length - 1) - 1] || 0; + this._s2 = curSeg[this._si]; + } + curIndex = i; + //now find the appropriate sub-segment (we split it into the number of pieces that was defined by "precision" and measured each one) + v -= this._l1; + i = this._si; + if (v > this._s2 && i < curSeg.length - 1) { + l = curSeg.length - 1; + while (i < l && (this._s2 = curSeg[++i]) <= v) { } + this._s1 = curSeg[i-1]; + this._si = i; + } else if (v < this._s1 && i > 0) { + while (i > 0 && (this._s1 = curSeg[--i]) >= v) { } + if (i === 0 && v < this._s1) { + this._s1 = 0; + } else { + i++; + } + this._s2 = curSeg[i]; + this._si = i; + } + t = (i + (v - this._s1) / (this._s2 - this._s1)) * this._prec; + } + inv = 1 - t; + + i = this._props.length; + while (--i > -1) { + p = this._props[i]; + b = this._beziers[p][curIndex]; + val = (t * t * b.da + 3 * inv * (t * b.ca + inv * b.ba)) * t + b.a; + if (this._round[p]) { + val = Math.round(val); + } + if (func[p]) { + target[p](val); + } else { + target[p] = val; + } + } + + if (this._autoRotate) { + var ar = this._autoRotate, + b2, x1, y1, x2, y2, add, conv; + i = ar.length; + while (--i > -1) { + p = ar[i][2]; + add = ar[i][3] || 0; + conv = (ar[i][4] === true) ? 1 : _RAD2DEG; + b = this._beziers[ar[i][0]]; + b2 = this._beziers[ar[i][1]]; + + if (b && b2) { //in case one of the properties got overwritten. + b = b[curIndex]; + b2 = b2[curIndex]; + + x1 = b.a + (b.b - b.a) * t; + x2 = b.b + (b.c - b.b) * t; + x1 += (x2 - x1) * t; + x2 += ((b.c + (b.d - b.c) * t) - x2) * t; + + y1 = b2.a + (b2.b - b2.a) * t; + y2 = b2.b + (b2.c - b2.b) * t; + y1 += (y2 - y1) * t; + y2 += ((b2.c + (b2.d - b2.c) * t) - y2) * t; + + val = notStart ? Math.atan2(y2 - y1, x2 - x1) * conv + add : this._initialRotations[i]; + + if (func[p]) { + target[p](val); + } else { + target[p] = val; + } + } + } + } + } + }), + p = BezierPlugin.prototype; + + + BezierPlugin.bezierThrough = bezierThrough; + BezierPlugin.cubicToQuadratic = cubicToQuadratic; + BezierPlugin._autoCSS = true; //indicates that this plugin can be inserted into the "css" object using the autoCSS feature of TweenLite + BezierPlugin.quadraticToCubic = function(a, b, c) { + return new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c); + }; + + BezierPlugin._cssRegister = function() { + var CSSPlugin = window._gsDefine.globals.CSSPlugin; + if (!CSSPlugin) { + return; + } + var _internals = CSSPlugin._internals, + _parseToProxy = _internals._parseToProxy, + _setPluginRatio = _internals._setPluginRatio, + CSSPropTween = _internals.CSSPropTween; + _internals._registerComplexSpecialProp("bezier", {parser:function(t, e, prop, cssp, pt, plugin) { + if (e instanceof Array) { + e = {values:e}; + } + plugin = new BezierPlugin(); + var values = e.values, + l = values.length - 1, + pluginValues = [], + v = {}, + i, p, data; + if (l < 0) { + return pt; + } + for (i = 0; i <= l; i++) { + data = _parseToProxy(t, values[i], cssp, pt, plugin, (l !== i)); + pluginValues[i] = data.end; + } + for (p in e) { + v[p] = e[p]; //duplicate the vars object because we need to alter some things which would cause problems if the user plans to reuse the same vars object for another tween. + } + v.values = pluginValues; + pt = new CSSPropTween(t, "bezier", 0, 0, data.pt, 2); + pt.data = data; + pt.plugin = plugin; + pt.setRatio = _setPluginRatio; + if (v.autoRotate === 0) { + v.autoRotate = true; + } + if (v.autoRotate && !(v.autoRotate instanceof Array)) { + i = (v.autoRotate === true) ? 0 : Number(v.autoRotate); + v.autoRotate = (data.end.left != null) ? [["left","top","rotation",i,false]] : (data.end.x != null) ? [["x","y","rotation",i,false]] : false; + } + if (v.autoRotate) { + if (!cssp._transform) { + cssp._enableTransforms(false); + } + data.autoRotate = cssp._target._gsTransform; + } + plugin._onInitTween(data.proxy, v, cssp._tween); + return pt; + }}); + }; + + p._roundProps = function(lookup, value) { + var op = this._overwriteProps, + i = op.length; + while (--i > -1) { + if (lookup[op[i]] || lookup.bezier || lookup.bezierThrough) { + this._round[op[i]] = value; + } + } + }; + + p._kill = function(lookup) { + var a = this._props, + p, i; + for (p in this._beziers) { + if (p in lookup) { + delete this._beziers[p]; + delete this._func[p]; + i = a.length; + while (--i > -1) { + if (a[i] === p) { + a.splice(i, 1); + } + } + } + } + return this._super._kill.call(this, lookup); + }; + + }()); + + + + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * CSSPlugin + * ---------------------------------------------------------------- + */ + window._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin","TweenLite"], function(TweenPlugin, TweenLite) { + + /** @constructor **/ + var CSSPlugin = function() { + TweenPlugin.call(this, "css"); + this._overwriteProps.length = 0; + this.setRatio = CSSPlugin.prototype.setRatio; //speed optimization (avoid prototype lookup on this "hot" method) + }, + _hasPriority, //turns true whenever a CSSPropTween instance is created that has a priority other than 0. This helps us discern whether or not we should spend the time organizing the linked list or not after a CSSPlugin's _onInitTween() method is called. + _suffixMap, //we set this in _onInitTween() each time as a way to have a persistent variable we can use in other methods like _parse() without having to pass it around as a parameter and we keep _parse() decoupled from a particular CSSPlugin instance + _cs, //computed style (we store this in a shared variable to conserve memory and make minification tighter + _overwriteProps, //alias to the currently instantiating CSSPlugin's _overwriteProps array. We use this closure in order to avoid having to pass a reference around from method to method and aid in minification. + _specialProps = {}, + p = CSSPlugin.prototype = new TweenPlugin("css"); + + p.constructor = CSSPlugin; + CSSPlugin.version = "1.12.1"; + CSSPlugin.API = 2; + CSSPlugin.defaultTransformPerspective = 0; + CSSPlugin.defaultSkewType = "compensated"; + p = "px"; //we'll reuse the "p" variable to keep file size down + CSSPlugin.suffixMap = {top:p, right:p, bottom:p, left:p, width:p, height:p, fontSize:p, padding:p, margin:p, perspective:p, lineHeight:""}; + + + var _numExp = /(?:\d|\-\d|\.\d|\-\.\d)+/g, + _relNumExp = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g, + _valuesExp = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, //finds all the values that begin with numbers or += or -= and then a number. Includes suffixes. We use this to split complex values apart like "1px 5px 20px rgb(255,102,51)" + _NaNExp = /[^\d\-\.]/g, + _suffixExp = /(?:\d|\-|\+|=|#|\.)*/g, + _opacityExp = /opacity *= *([^)]*)/i, + _opacityValExp = /opacity:([^;]*)/i, + _alphaFilterExp = /alpha\(opacity *=.+?\)/i, + _rgbhslExp = /^(rgb|hsl)/, + _capsExp = /([A-Z])/g, + _camelExp = /-([a-z])/gi, + _urlExp = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, //for pulling out urls from url(...) or url("...") strings (some browsers wrap urls in quotes, some don't when reporting things like backgroundImage) + _camelFunc = function(s, g) { return g.toUpperCase(); }, + _horizExp = /(?:Left|Right|Width)/i, + _ieGetMatrixExp = /(M11|M12|M21|M22)=[\d\-\.e]+/gi, + _ieSetMatrixExp = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i, + _commasOutsideParenExp = /,(?=[^\)]*(?:\(|$))/gi, //finds any commas that are not within parenthesis + _DEG2RAD = Math.PI / 180, + _RAD2DEG = 180 / Math.PI, + _forcePT = {}, + _doc = document, + _tempDiv = _doc.createElement("div"), + _tempImg = _doc.createElement("img"), + _internals = CSSPlugin._internals = {_specialProps:_specialProps}, //provides a hook to a few internal methods that we need to access from inside other plugins + _agent = navigator.userAgent, + _autoRound, + _reqSafariFix, //we won't apply the Safari transform fix until we actually come across a tween that affects a transform property (to maintain best performance). + + _isSafari, + _isFirefox, //Firefox has a bug that causes 3D transformed elements to randomly disappear unless a repaint is forced after each update on each element. + _isSafariLT6, //Safari (and Android 4 which uses a flavor of Safari) has a bug that prevents changes to "top" and "left" properties from rendering properly if changed on the same frame as a transform UNLESS we set the element's WebkitBackfaceVisibility to hidden (weird, I know). Doing this for Android 3 and earlier seems to actually cause other problems, though (fun!) + _ieVers, + _supportsOpacity = (function() { //we set _isSafari, _ieVers, _isFirefox, and _supportsOpacity all in one function here to reduce file size slightly, especially in the minified version. + var i = _agent.indexOf("Android"), + d = _doc.createElement("div"), a; + + _isSafari = (_agent.indexOf("Safari") !== -1 && _agent.indexOf("Chrome") === -1 && (i === -1 || Number(_agent.substr(i+8, 1)) > 3)); + _isSafariLT6 = (_isSafari && (Number(_agent.substr(_agent.indexOf("Version/")+8, 1)) < 6)); + _isFirefox = (_agent.indexOf("Firefox") !== -1); + + if ((/MSIE ([0-9]{1,}[\.0-9]{0,})/).exec(_agent)) { + _ieVers = parseFloat( RegExp.$1 ); + } + + d.innerHTML = "a"; + a = d.getElementsByTagName("a")[0]; + return a ? /^0.55/.test(a.style.opacity) : false; + }()), + _getIEOpacity = function(v) { + return (_opacityExp.test( ((typeof(v) === "string") ? v : (v.currentStyle ? v.currentStyle.filter : v.style.filter) || "") ) ? ( parseFloat( RegExp.$1 ) / 100 ) : 1); + }, + _log = function(s) {//for logging messages, but in a way that won't throw errors in old versions of IE. + if (window.console) { + //console.log(s); + } + }, + _prefixCSS = "", //the non-camelCase vendor prefix like "-o-", "-moz-", "-ms-", or "-webkit-" + _prefix = "", //camelCase vendor prefix like "O", "ms", "Webkit", or "Moz". + + // @private feed in a camelCase property name like "transform" and it will check to see if it is valid as-is or if it needs a vendor prefix. It returns the corrected camelCase property name (i.e. "WebkitTransform" or "MozTransform" or "transform" or null if no such property is found, like if the browser is IE8 or before, "transform" won't be found at all) + _checkPropPrefix = function(p, e) { + e = e || _tempDiv; + var s = e.style, + a, i; + if (s[p] !== undefined) { + return p; + } + p = p.charAt(0).toUpperCase() + p.substr(1); + a = ["O","Moz","ms","Ms","Webkit"]; + i = 5; + while (--i > -1 && s[a[i]+p] === undefined) { } + if (i >= 0) { + _prefix = (i === 3) ? "ms" : a[i]; + _prefixCSS = "-" + _prefix.toLowerCase() + "-"; + return _prefix + p; + } + return null; + }, + + _getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : function() {}, + + /** + * @private Returns the css style for a particular property of an element. For example, to get whatever the current "left" css value for an element with an ID of "myElement", you could do: + * var currentLeft = CSSPlugin.getStyle( document.getElementById("myElement"), "left"); + * + * @param {!Object} t Target element whose style property you want to query + * @param {!string} p Property name (like "left" or "top" or "marginTop", etc.) + * @param {Object=} cs Computed style object. This just provides a way to speed processing if you're going to get several properties on the same element in quick succession - you can reuse the result of the getComputedStyle() call. + * @param {boolean=} calc If true, the value will not be read directly from the element's "style" property (if it exists there), but instead the getComputedStyle() result will be used. This can be useful when you want to ensure that the browser itself is interpreting the value. + * @param {string=} dflt Default value that should be returned in the place of null, "none", "auto" or "auto auto". + * @return {?string} The current property value + */ + _getStyle = CSSPlugin.getStyle = function(t, p, cs, calc, dflt) { + var rv; + if (!_supportsOpacity) if (p === "opacity") { //several versions of IE don't use the standard "opacity" property - they use things like filter:alpha(opacity=50), so we parse that here. + return _getIEOpacity(t); + } + if (!calc && t.style[p]) { + rv = t.style[p]; + } else if ((cs = cs || _getComputedStyle(t))) { + rv = cs[p] || cs.getPropertyValue(p) || cs.getPropertyValue(p.replace(_capsExp, "-$1").toLowerCase()); + } else if (t.currentStyle) { + rv = t.currentStyle[p]; + } + return (dflt != null && (!rv || rv === "none" || rv === "auto" || rv === "auto auto")) ? dflt : rv; + }, + + /** + * @private Pass the target element, the property name, the numeric value, and the suffix (like "%", "em", "px", etc.) and it will spit back the equivalent pixel number. + * @param {!Object} t Target element + * @param {!string} p Property name (like "left", "top", "marginLeft", etc.) + * @param {!number} v Value + * @param {string=} sfx Suffix (like "px" or "%" or "em") + * @param {boolean=} recurse If true, the call is a recursive one. In some browsers (like IE7/8), occasionally the value isn't accurately reported initially, but if we run the function again it will take effect. + * @return {number} value in pixels + */ + _convertToPixels = _internals.convertToPixels = function(t, p, v, sfx, recurse) { + if (sfx === "px" || !sfx) { return v; } + if (sfx === "auto" || !v) { return 0; } + var horiz = _horizExp.test(p), + node = t, + style = _tempDiv.style, + neg = (v < 0), + pix, cache, time; + if (neg) { + v = -v; + } + if (sfx === "%" && p.indexOf("border") !== -1) { + pix = (v / 100) * (horiz ? t.clientWidth : t.clientHeight); + } else { + style.cssText = "border:0 solid red;position:" + _getStyle(t, "position") + ";line-height:0;"; + if (sfx === "%" || !node.appendChild) { + node = t.parentNode || _doc.body; + cache = node._gsCache; + time = TweenLite.ticker.frame; + if (cache && horiz && cache.time === time) { //performance optimization: we record the width of elements along with the ticker frame so that we can quickly get it again on the same tick (seems relatively safe to assume it wouldn't change on the same tick) + return cache.width * v / 100; + } + style[(horiz ? "width" : "height")] = v + sfx; + } else { + style[(horiz ? "borderLeftWidth" : "borderTopWidth")] = v + sfx; + } + node.appendChild(_tempDiv); + pix = parseFloat(_tempDiv[(horiz ? "offsetWidth" : "offsetHeight")]); + node.removeChild(_tempDiv); + if (horiz && sfx === "%" && CSSPlugin.cacheWidths !== false) { + cache = node._gsCache = node._gsCache || {}; + cache.time = time; + cache.width = pix / v * 100; + } + if (pix === 0 && !recurse) { + pix = _convertToPixels(t, p, v, sfx, true); + } + } + return neg ? -pix : pix; + }, + _calculateOffset = _internals.calculateOffset = function(t, p, cs) { //for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop + if (_getStyle(t, "position", cs) !== "absolute") { return 0; } + var dim = ((p === "left") ? "Left" : "Top"), + v = _getStyle(t, "margin" + dim, cs); + return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0); + }, + + // @private returns at object containing ALL of the style properties in camelCase and their associated values. + _getAllStyles = function(t, cs) { + var s = {}, + i, tr; + if ((cs = cs || _getComputedStyle(t, null))) { + if ((i = cs.length)) { + while (--i > -1) { + s[cs[i].replace(_camelExp, _camelFunc)] = cs.getPropertyValue(cs[i]); + } + } else { //Opera behaves differently - cs.length is always 0, so we must do a for...in loop. + for (i in cs) { + s[i] = cs[i]; + } + } + } else if ((cs = t.currentStyle || t.style)) { + for (i in cs) { + if (typeof(i) === "string" && s[i] === undefined) { + s[i.replace(_camelExp, _camelFunc)] = cs[i]; + } + } + } + if (!_supportsOpacity) { + s.opacity = _getIEOpacity(t); + } + tr = _getTransform(t, cs, false); + s.rotation = tr.rotation; + s.skewX = tr.skewX; + s.scaleX = tr.scaleX; + s.scaleY = tr.scaleY; + s.x = tr.x; + s.y = tr.y; + if (_supports3D) { + s.z = tr.z; + s.rotationX = tr.rotationX; + s.rotationY = tr.rotationY; + s.scaleZ = tr.scaleZ; + } + if (s.filters) { + delete s.filters; + } + return s; + }, + + // @private analyzes two style objects (as returned by _getAllStyles()) and only looks for differences between them that contain tweenable values (like a number or color). It returns an object with a "difs" property which refers to an object containing only those isolated properties and values for tweening, and a "firstMPT" property which refers to the first MiniPropTween instance in a linked list that recorded all the starting values of the different properties so that we can revert to them at the end or beginning of the tween - we don't want the cascading to get messed up. The forceLookup parameter is an optional generic object with properties that should be forced into the results - this is necessary for className tweens that are overwriting others because imagine a scenario where a rollover/rollout adds/removes a class and the user swipes the mouse over the target SUPER fast, thus nothing actually changed yet and the subsequent comparison of the properties would indicate they match (especially when px rounding is taken into consideration), thus no tweening is necessary even though it SHOULD tween and remove those properties after the tween (otherwise the inline styles will contaminate things). See the className SpecialProp code for details. + _cssDif = function(t, s1, s2, vars, forceLookup) { + var difs = {}, + style = t.style, + val, p, mpt; + for (p in s2) { + if (p !== "cssText") if (p !== "length") if (isNaN(p)) if (s1[p] !== (val = s2[p]) || (forceLookup && forceLookup[p])) if (p.indexOf("Origin") === -1) if (typeof(val) === "number" || typeof(val) === "string") { + difs[p] = (val === "auto" && (p === "left" || p === "top")) ? _calculateOffset(t, p) : ((val === "" || val === "auto" || val === "none") && typeof(s1[p]) === "string" && s1[p].replace(_NaNExp, "") !== "") ? 0 : val; //if the ending value is defaulting ("" or "auto"), we check the starting value and if it can be parsed into a number (a string which could have a suffix too, like 700px), then we swap in 0 for "" or "auto" so that things actually tween. + if (style[p] !== undefined) { //for className tweens, we must remember which properties already existed inline - the ones that didn't should be removed when the tween isn't in progress because they were only introduced to facilitate the transition between classes. + mpt = new MiniPropTween(style, p, style[p], mpt); + } + } + } + if (vars) { + for (p in vars) { //copy properties (except className) + if (p !== "className") { + difs[p] = vars[p]; + } + } + } + return {difs:difs, firstMPT:mpt}; + }, + _dimensions = {width:["Left","Right"], height:["Top","Bottom"]}, + _margins = ["marginLeft","marginRight","marginTop","marginBottom"], + + /** + * @private Gets the width or height of an element + * @param {!Object} t Target element + * @param {!string} p Property name ("width" or "height") + * @param {Object=} cs Computed style object (if one exists). Just a speed optimization. + * @return {number} Dimension (in pixels) + */ + _getDimension = function(t, p, cs) { + var v = parseFloat((p === "width") ? t.offsetWidth : t.offsetHeight), + a = _dimensions[p], + i = a.length; + cs = cs || _getComputedStyle(t, null); + while (--i > -1) { + v -= parseFloat( _getStyle(t, "padding" + a[i], cs, true) ) || 0; + v -= parseFloat( _getStyle(t, "border" + a[i] + "Width", cs, true) ) || 0; + } + return v; + }, + + // @private Parses position-related complex strings like "top left" or "50px 10px" or "70% 20%", etc. which are used for things like transformOrigin or backgroundPosition. Optionally decorates a supplied object (recObj) with the following properties: "ox" (offsetX), "oy" (offsetY), "oxp" (if true, "ox" is a percentage not a pixel value), and "oxy" (if true, "oy" is a percentage not a pixel value) + _parsePosition = function(v, recObj) { + if (v == null || v === "" || v === "auto" || v === "auto auto") { //note: Firefox uses "auto auto" as default whereas Chrome uses "auto". + v = "0 0"; + } + var a = v.split(" "), + x = (v.indexOf("left") !== -1) ? "0%" : (v.indexOf("right") !== -1) ? "100%" : a[0], + y = (v.indexOf("top") !== -1) ? "0%" : (v.indexOf("bottom") !== -1) ? "100%" : a[1]; + if (y == null) { + y = "0"; + } else if (y === "center") { + y = "50%"; + } + if (x === "center" || (isNaN(parseFloat(x)) && (x + "").indexOf("=") === -1)) { //remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative. + x = "50%"; + } + if (recObj) { + recObj.oxp = (x.indexOf("%") !== -1); + recObj.oyp = (y.indexOf("%") !== -1); + recObj.oxr = (x.charAt(1) === "="); + recObj.oyr = (y.charAt(1) === "="); + recObj.ox = parseFloat(x.replace(_NaNExp, "")); + recObj.oy = parseFloat(y.replace(_NaNExp, "")); + } + return x + " " + y + ((a.length > 2) ? " " + a[2] : ""); + }, + + /** + * @private Takes an ending value (typically a string, but can be a number) and a starting value and returns the change between the two, looking for relative value indicators like += and -= and it also ignores suffixes (but make sure the ending value starts with a number or +=/-= and that the starting value is a NUMBER!) + * @param {(number|string)} e End value which is typically a string, but could be a number + * @param {(number|string)} b Beginning value which is typically a string but could be a number + * @return {number} Amount of change between the beginning and ending values (relative values that have a "+=" or "-=" are recognized) + */ + _parseChange = function(e, b) { + return (typeof(e) === "string" && e.charAt(1) === "=") ? parseInt(e.charAt(0) + "1", 10) * parseFloat(e.substr(2)) : parseFloat(e) - parseFloat(b); + }, + + /** + * @private Takes a value and a default number, checks if the value is relative, null, or numeric and spits back a normalized number accordingly. Primarily used in the _parseTransform() function. + * @param {Object} v Value to be parsed + * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter) + * @return {number} Parsed value + */ + _parseVal = function(v, d) { + return (v == null) ? d : (typeof(v) === "string" && v.charAt(1) === "=") ? parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) + d : parseFloat(v); + }, + + /** + * @private Translates strings like "40deg" or "40" or 40rad" or "+=40deg" or "270_short" or "-90_cw" or "+=45_ccw" to a numeric radian angle. Of course a starting/default value must be fed in too so that relative values can be calculated properly. + * @param {Object} v Value to be parsed + * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter) + * @param {string=} p property name for directionalEnd (optional - only used when the parsed value is directional ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation). Property name would be "rotation", "rotationX", or "rotationY" + * @param {Object=} directionalEnd An object that will store the raw end values for directional angles ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation. + * @return {number} parsed angle in radians + */ + _parseAngle = function(v, d, p, directionalEnd) { + var min = 0.000001, + cap, split, dif, result; + if (v == null) { + result = d; + } else if (typeof(v) === "number") { + result = v; + } else { + cap = 360; + split = v.split("_"); + dif = Number(split[0].replace(_NaNExp, "")) * ((v.indexOf("rad") === -1) ? 1 : _RAD2DEG) - ((v.charAt(1) === "=") ? 0 : d); + if (split.length) { + if (directionalEnd) { + directionalEnd[p] = d + dif; + } + if (v.indexOf("short") !== -1) { + dif = dif % cap; + if (dif !== dif % (cap / 2)) { + dif = (dif < 0) ? dif + cap : dif - cap; + } + } + if (v.indexOf("_cw") !== -1 && dif < 0) { + dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; + } else if (v.indexOf("ccw") !== -1 && dif > 0) { + dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; + } + } + result = d + dif; + } + if (result < min && result > -min) { + result = 0; + } + return result; + }, + + _colorLookup = {aqua:[0,255,255], + lime:[0,255,0], + silver:[192,192,192], + black:[0,0,0], + maroon:[128,0,0], + teal:[0,128,128], + blue:[0,0,255], + navy:[0,0,128], + white:[255,255,255], + fuchsia:[255,0,255], + olive:[128,128,0], + yellow:[255,255,0], + orange:[255,165,0], + gray:[128,128,128], + purple:[128,0,128], + green:[0,128,0], + red:[255,0,0], + pink:[255,192,203], + cyan:[0,255,255], + transparent:[255,255,255,0]}, + + _hue = function(h, m1, m2) { + h = (h < 0) ? h + 1 : (h > 1) ? h - 1 : h; + return ((((h * 6 < 1) ? m1 + (m2 - m1) * h * 6 : (h < 0.5) ? m2 : (h * 3 < 2) ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255) + 0.5) | 0; + }, + + /** + * @private Parses a color (like #9F0, #FF9900, or rgb(255,51,153)) into an array with 3 elements for red, green, and blue. Also handles rgba() values (splits into array of 4 elements of course) + * @param {(string|number)} v The value the should be parsed which could be a string like #9F0 or rgb(255,102,51) or rgba(255,0,0,0.5) or it could be a number like 0xFF00CC or even a named color like red, blue, purple, etc. + * @return {Array.} An array containing red, green, and blue (and optionally alpha) in that order. + */ + _parseColor = function(v) { + var c1, c2, c3, h, s, l; + if (!v || v === "") { + return _colorLookup.black; + } + if (typeof(v) === "number") { + return [v >> 16, (v >> 8) & 255, v & 255]; + } + if (v.charAt(v.length - 1) === ",") { //sometimes a trailing commma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value. + v = v.substr(0, v.length - 1); + } + if (_colorLookup[v]) { + return _colorLookup[v]; + } + if (v.charAt(0) === "#") { + if (v.length === 4) { //for shorthand like #9F0 + c1 = v.charAt(1), + c2 = v.charAt(2), + c3 = v.charAt(3); + v = "#" + c1 + c1 + c2 + c2 + c3 + c3; + } + v = parseInt(v.substr(1), 16); + return [v >> 16, (v >> 8) & 255, v & 255]; + } + if (v.substr(0, 3) === "hsl") { + v = v.match(_numExp); + h = (Number(v[0]) % 360) / 360; + s = Number(v[1]) / 100; + l = Number(v[2]) / 100; + c2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + c1 = l * 2 - c2; + if (v.length > 3) { + v[3] = Number(v[3]); + } + v[0] = _hue(h + 1 / 3, c1, c2); + v[1] = _hue(h, c1, c2); + v[2] = _hue(h - 1 / 3, c1, c2); + return v; + } + v = v.match(_numExp) || _colorLookup.transparent; + v[0] = Number(v[0]); + v[1] = Number(v[1]); + v[2] = Number(v[2]); + if (v.length > 3) { + v[3] = Number(v[3]); + } + return v; + }, + _colorExp = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#.+?\\b"; //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc. + + for (p in _colorLookup) { + _colorExp += "|" + p + "\\b"; + } + _colorExp = new RegExp(_colorExp+")", "gi"); + + /** + * @private Returns a formatter function that handles taking a string (or number in some cases) and returning a consistently formatted one in terms of delimiters, quantity of values, etc. For example, we may get boxShadow values defined as "0px red" or "0px 0px 10px rgb(255,0,0)" or "0px 0px 20px 20px #F00" and we need to ensure that what we get back is described with 4 numbers and a color. This allows us to feed it into the _parseComplex() method and split the values up appropriately. The neat thing about this _getFormatter() function is that the dflt defines a pattern as well as a default, so for example, _getFormatter("0px 0px 0px 0px #777", true) not only sets the default as 0px for all distances and #777 for the color, but also sets the pattern such that 4 numbers and a color will always get returned. + * @param {!string} dflt The default value and pattern to follow. So "0px 0px 0px 0px #777" will ensure that 4 numbers and a color will always get returned. + * @param {boolean=} clr If true, the values should be searched for color-related data. For example, boxShadow values typically contain a color whereas borderRadius don't. + * @param {boolean=} collapsible If true, the value is a top/left/right/bottom style one that acts like margin or padding, where if only one value is received, it's used for all 4; if 2 are received, the first is duplicated for 3rd (bottom) and the 2nd is duplicated for the 4th spot (left), etc. + * @return {Function} formatter function + */ + var _getFormatter = function(dflt, clr, collapsible, multi) { + if (dflt == null) { + return function(v) {return v;}; + } + var dColor = clr ? (dflt.match(_colorExp) || [""])[0] : "", + dVals = dflt.split(dColor).join("").match(_valuesExp) || [], + pfx = dflt.substr(0, dflt.indexOf(dVals[0])), + sfx = (dflt.charAt(dflt.length - 1) === ")") ? ")" : "", + delim = (dflt.indexOf(" ") !== -1) ? " " : ",", + numVals = dVals.length, + dSfx = (numVals > 0) ? dVals[0].replace(_numExp, "") : "", + formatter; + if (!numVals) { + return function(v) {return v;}; + } + if (clr) { + formatter = function(v) { + var color, vals, i, a; + if (typeof(v) === "number") { + v += dSfx; + } else if (multi && _commasOutsideParenExp.test(v)) { + a = v.replace(_commasOutsideParenExp, "|").split("|"); + for (i = 0; i < a.length; i++) { + a[i] = formatter(a[i]); + } + return a.join(","); + } + color = (v.match(_colorExp) || [dColor])[0]; + vals = v.split(color).join("").match(_valuesExp) || []; + i = vals.length; + if (numVals > i--) { + while (++i < numVals) { + vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i]; + } + } + return pfx + vals.join(delim) + delim + color + sfx + (v.indexOf("inset") !== -1 ? " inset" : ""); + }; + return formatter; + + } + formatter = function(v) { + var vals, a, i; + if (typeof(v) === "number") { + v += dSfx; + } else if (multi && _commasOutsideParenExp.test(v)) { + a = v.replace(_commasOutsideParenExp, "|").split("|"); + for (i = 0; i < a.length; i++) { + a[i] = formatter(a[i]); + } + return a.join(","); + } + vals = v.match(_valuesExp) || []; + i = vals.length; + if (numVals > i--) { + while (++i < numVals) { + vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i]; + } + } + return pfx + vals.join(delim) + sfx; + }; + return formatter; + }, + + /** + * @private returns a formatter function that's used for edge-related values like marginTop, marginLeft, paddingBottom, paddingRight, etc. Just pass a comma-delimited list of property names related to the edges. + * @param {!string} props a comma-delimited list of property names in order from top to left, like "marginTop,marginRight,marginBottom,marginLeft" + * @return {Function} a formatter function + */ + _getEdgeParser = function(props) { + props = props.split(","); + return function(t, e, p, cssp, pt, plugin, vars) { + var a = (e + "").split(" "), + i; + vars = {}; + for (i = 0; i < 4; i++) { + vars[props[i]] = a[i] = a[i] || a[(((i - 1) / 2) >> 0)]; + } + return cssp.parse(t, vars, pt, plugin); + }; + }, + + // @private used when other plugins must tween values first, like BezierPlugin or ThrowPropsPlugin, etc. That plugin's setRatio() gets called first so that the values are updated, and then we loop through the MiniPropTweens which handle copying the values into their appropriate slots so that they can then be applied correctly in the main CSSPlugin setRatio() method. Remember, we typically create a proxy object that has a bunch of uniquely-named properties that we feed to the sub-plugin and it does its magic normally, and then we must interpret those values and apply them to the css because often numbers must get combined/concatenated, suffixes added, etc. to work with css, like boxShadow could have 4 values plus a color. + _setPluginRatio = _internals._setPluginRatio = function(v) { + this.plugin.setRatio(v); + var d = this.data, + proxy = d.proxy, + mpt = d.firstMPT, + min = 0.000001, + val, pt, i, str; + while (mpt) { + val = proxy[mpt.v]; + if (mpt.r) { + val = Math.round(val); + } else if (val < min && val > -min) { + val = 0; + } + mpt.t[mpt.p] = val; + mpt = mpt._next; + } + if (d.autoRotate) { + d.autoRotate.rotation = proxy.rotation; + } + //at the end, we must set the CSSPropTween's "e" (end) value dynamically here because that's what is used in the final setRatio() method. + if (v === 1) { + mpt = d.firstMPT; + while (mpt) { + pt = mpt.t; + if (!pt.type) { + pt.e = pt.s + pt.xs0; + } else if (pt.type === 1) { + str = pt.xs0 + pt.s + pt.xs1; + for (i = 1; i < pt.l; i++) { + str += pt["xn"+i] + pt["xs"+(i+1)]; + } + pt.e = str; + } + mpt = mpt._next; + } + } + }, + + /** + * @private @constructor Used by a few SpecialProps to hold important values for proxies. For example, _parseToProxy() creates a MiniPropTween instance for each property that must get tweened on the proxy, and we record the original property name as well as the unique one we create for the proxy, plus whether or not the value needs to be rounded plus the original value. + * @param {!Object} t target object whose property we're tweening (often a CSSPropTween) + * @param {!string} p property name + * @param {(number|string|object)} v value + * @param {MiniPropTween=} next next MiniPropTween in the linked list + * @param {boolean=} r if true, the tweened value should be rounded to the nearest integer + */ + MiniPropTween = function(t, p, v, next, r) { + this.t = t; + this.p = p; + this.v = v; + this.r = r; + if (next) { + next._prev = this; + this._next = next; + } + }, + + /** + * @private Most other plugins (like BezierPlugin and ThrowPropsPlugin and others) can only tween numeric values, but CSSPlugin must accommodate special values that have a bunch of extra data (like a suffix or strings between numeric values, etc.). For example, boxShadow has values like "10px 10px 20px 30px rgb(255,0,0)" which would utterly confuse other plugins. This method allows us to split that data apart and grab only the numeric data and attach it to uniquely-named properties of a generic proxy object ({}) so that we can feed that to virtually any plugin to have the numbers tweened. However, we must also keep track of which properties from the proxy go with which CSSPropTween values and instances. So we create a linked list of MiniPropTweens. Each one records a target (the original CSSPropTween), property (like "s" or "xn1" or "xn2") that we're tweening and the unique property name that was used for the proxy (like "boxShadow_xn1" and "boxShadow_xn2") and whether or not they need to be rounded. That way, in the _setPluginRatio() method we can simply copy the values over from the proxy to the CSSPropTween instance(s). Then, when the main CSSPlugin setRatio() method runs and applies the CSSPropTween values accordingly, they're updated nicely. So the external plugin tweens the numbers, _setPluginRatio() copies them over, and setRatio() acts normally, applying css-specific values to the element. + * This method returns an object that has the following properties: + * - proxy: a generic object containing the starting values for all the properties that will be tweened by the external plugin. This is what we feed to the external _onInitTween() as the target + * - end: a generic object containing the ending values for all the properties that will be tweened by the external plugin. This is what we feed to the external plugin's _onInitTween() as the destination values + * - firstMPT: the first MiniPropTween in the linked list + * - pt: the first CSSPropTween in the linked list that was created when parsing. If shallow is true, this linked list will NOT attach to the one passed into the _parseToProxy() as the "pt" (4th) parameter. + * @param {!Object} t target object to be tweened + * @param {!(Object|string)} vars the object containing the information about the tweening values (typically the end/destination values) that should be parsed + * @param {!CSSPlugin} cssp The CSSPlugin instance + * @param {CSSPropTween=} pt the next CSSPropTween in the linked list + * @param {TweenPlugin=} plugin the external TweenPlugin instance that will be handling tweening the numeric values + * @param {boolean=} shallow if true, the resulting linked list from the parse will NOT be attached to the CSSPropTween that was passed in as the "pt" (4th) parameter. + * @return An object containing the following properties: proxy, end, firstMPT, and pt (see above for descriptions) + */ + _parseToProxy = _internals._parseToProxy = function(t, vars, cssp, pt, plugin, shallow) { + var bpt = pt, + start = {}, + end = {}, + transform = cssp._transform, + oldForce = _forcePT, + i, p, xp, mpt, firstPT; + cssp._transform = null; + _forcePT = vars; + pt = firstPT = cssp.parse(t, vars, pt, plugin); + _forcePT = oldForce; + //break off from the linked list so the new ones are isolated. + if (shallow) { + cssp._transform = transform; + if (bpt) { + bpt._prev = null; + if (bpt._prev) { + bpt._prev._next = null; + } + } + } + while (pt && pt !== bpt) { + if (pt.type <= 1) { + p = pt.p; + end[p] = pt.s + pt.c; + start[p] = pt.s; + if (!shallow) { + mpt = new MiniPropTween(pt, "s", p, mpt, pt.r); + pt.c = 0; + } + if (pt.type === 1) { + i = pt.l; + while (--i > 0) { + xp = "xn" + i; + p = pt.p + "_" + xp; + end[p] = pt.data[xp]; + start[p] = pt[xp]; + if (!shallow) { + mpt = new MiniPropTween(pt, xp, p, mpt, pt.rxp[xp]); + } + } + } + } + pt = pt._next; + } + return {proxy:start, end:end, firstMPT:mpt, pt:firstPT}; + }, + + + + /** + * @constructor Each property that is tweened has at least one CSSPropTween associated with it. These instances store important information like the target, property, starting value, amount of change, etc. They can also optionally have a number of "extra" strings and numeric values named xs1, xn1, xs2, xn2, xs3, xn3, etc. where "s" indicates string and "n" indicates number. These can be pieced together in a complex-value tween (type:1) that has alternating types of data like a string, number, string, number, etc. For example, boxShadow could be "5px 5px 8px rgb(102, 102, 51)". In that value, there are 6 numbers that may need to tween and then pieced back together into a string again with spaces, suffixes, etc. xs0 is special in that it stores the suffix for standard (type:0) tweens, -OR- the first string (prefix) in a complex-value (type:1) CSSPropTween -OR- it can be the non-tweening value in a type:-1 CSSPropTween. We do this to conserve memory. + * CSSPropTweens have the following optional properties as well (not defined through the constructor): + * - l: Length in terms of the number of extra properties that the CSSPropTween has (default: 0). For example, for a boxShadow we may need to tween 5 numbers in which case l would be 5; Keep in mind that the start/end values for the first number that's tweened are always stored in the s and c properties to conserve memory. All additional values thereafter are stored in xn1, xn2, etc. + * - xfirst: The first instance of any sub-CSSPropTweens that are tweening properties of this instance. For example, we may split up a boxShadow tween so that there's a main CSSPropTween of type:1 that has various xs* and xn* values associated with the h-shadow, v-shadow, blur, color, etc. Then we spawn a CSSPropTween for each of those that has a higher priority and runs BEFORE the main CSSPropTween so that the values are all set by the time it needs to re-assemble them. The xfirst gives us an easy way to identify the first one in that chain which typically ends at the main one (because they're all prepende to the linked list) + * - plugin: The TweenPlugin instance that will handle the tweening of any complex values. For example, sometimes we don't want to use normal subtweens (like xfirst refers to) to tween the values - we might want ThrowPropsPlugin or BezierPlugin some other plugin to do the actual tweening, so we create a plugin instance and store a reference here. We need this reference so that if we get a request to round values or disable a tween, we can pass along that request. + * - data: Arbitrary data that needs to be stored with the CSSPropTween. Typically if we're going to have a plugin handle the tweening of a complex-value tween, we create a generic object that stores the END values that we're tweening to and the CSSPropTween's xs1, xs2, etc. have the starting values. We store that object as data. That way, we can simply pass that object to the plugin and use the CSSPropTween as the target. + * - setRatio: Only used for type:2 tweens that require custom functionality. In this case, we call the CSSPropTween's setRatio() method and pass the ratio each time the tween updates. This isn't quite as efficient as doing things directly in the CSSPlugin's setRatio() method, but it's very convenient and flexible. + * @param {!Object} t Target object whose property will be tweened. Often a DOM element, but not always. It could be anything. + * @param {string} p Property to tween (name). For example, to tween element.width, p would be "width". + * @param {number} s Starting numeric value + * @param {number} c Change in numeric value over the course of the entire tween. For example, if element.width starts at 5 and should end at 100, c would be 95. + * @param {CSSPropTween=} next The next CSSPropTween in the linked list. If one is defined, we will define its _prev as the new instance, and the new instance's _next will be pointed at it. + * @param {number=} type The type of CSSPropTween where -1 = a non-tweening value, 0 = a standard simple tween, 1 = a complex value (like one that has multiple numbers in a comma- or space-delimited string like border:"1px solid red"), and 2 = one that uses a custom setRatio function that does all of the work of applying the values on each update. + * @param {string=} n Name of the property that should be used for overwriting purposes which is typically the same as p but not always. For example, we may need to create a subtween for the 2nd part of a "clip:rect(...)" tween in which case "p" might be xs1 but "n" is still "clip" + * @param {boolean=} r If true, the value(s) should be rounded + * @param {number=} pr Priority in the linked list order. Higher priority CSSPropTweens will be updated before lower priority ones. The default priority is 0. + * @param {string=} b Beginning value. We store this to ensure that it is EXACTLY what it was when the tween began without any risk of interpretation issues. + * @param {string=} e Ending value. We store this to ensure that it is EXACTLY what the user defined at the end of the tween without any risk of interpretation issues. + */ + CSSPropTween = _internals.CSSPropTween = function(t, p, s, c, next, type, n, r, pr, b, e) { + this.t = t; //target + this.p = p; //property + this.s = s; //starting value + this.c = c; //change value + this.n = n || p; //name that this CSSPropTween should be associated to (usually the same as p, but not always - n is what overwriting looks at) + if (!(t instanceof CSSPropTween)) { + _overwriteProps.push(this.n); + } + this.r = r; //round (boolean) + this.type = type || 0; //0 = normal tween, -1 = non-tweening (in which case xs0 will be applied to the target's property, like tp.t[tp.p] = tp.xs0), 1 = complex-value SpecialProp, 2 = custom setRatio() that does all the work + if (pr) { + this.pr = pr; + _hasPriority = true; + } + this.b = (b === undefined) ? s : b; + this.e = (e === undefined) ? s + c : e; + if (next) { + this._next = next; + next._prev = this; + } + }, + + /** + * Takes a target, the beginning value and ending value (as strings) and parses them into a CSSPropTween (possibly with child CSSPropTweens) that accommodates multiple numbers, colors, comma-delimited values, etc. For example: + * sp.parseComplex(element, "boxShadow", "5px 10px 20px rgb(255,102,51)", "0px 0px 0px red", true, "0px 0px 0px rgb(0,0,0,0)", pt); + * It will walk through the beginning and ending values (which should be in the same format with the same number and type of values) and figure out which parts are numbers, what strings separate the numeric/tweenable values, and then create the CSSPropTweens accordingly. If a plugin is defined, no child CSSPropTweens will be created. Instead, the ending values will be stored in the "data" property of the returned CSSPropTween like: {s:-5, xn1:-10, xn2:-20, xn3:255, xn4:0, xn5:0} so that it can be fed to any other plugin and it'll be plain numeric tweens but the recomposition of the complex value will be handled inside CSSPlugin's setRatio(). + * If a setRatio is defined, the type of the CSSPropTween will be set to 2 and recomposition of the values will be the responsibility of that method. + * + * @param {!Object} t Target whose property will be tweened + * @param {!string} p Property that will be tweened (its name, like "left" or "backgroundColor" or "boxShadow") + * @param {string} b Beginning value + * @param {string} e Ending value + * @param {boolean} clrs If true, the value could contain a color value like "rgb(255,0,0)" or "#F00" or "red". The default is false, so no colors will be recognized (a performance optimization) + * @param {(string|number|Object)} dflt The default beginning value that should be used if no valid beginning value is defined or if the number of values inside the complex beginning and ending values don't match + * @param {?CSSPropTween} pt CSSPropTween instance that is the current head of the linked list (we'll prepend to this). + * @param {number=} pr Priority in the linked list order. Higher priority properties will be updated before lower priority ones. The default priority is 0. + * @param {TweenPlugin=} plugin If a plugin should handle the tweening of extra properties, pass the plugin instance here. If one is defined, then NO subtweens will be created for any extra properties (the properties will be created - just not additional CSSPropTween instances to tween them) because the plugin is expected to do so. However, the end values WILL be populated in the "data" property, like {s:100, xn1:50, xn2:300} + * @param {function(number)=} setRatio If values should be set in a custom function instead of being pieced together in a type:1 (complex-value) CSSPropTween, define that custom function here. + * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parseComplex() call. + */ + _parseComplex = CSSPlugin.parseComplex = function(t, p, b, e, clrs, dflt, pt, pr, plugin, setRatio) { + //DEBUG: _log("parseComplex: "+p+", b: "+b+", e: "+e); + b = b || dflt || ""; + pt = new CSSPropTween(t, p, 0, 0, pt, (setRatio ? 2 : 1), null, false, pr, b, e); + e += ""; //ensures it's a string + var ba = b.split(", ").join(",").split(" "), //beginning array + ea = e.split(", ").join(",").split(" "), //ending array + l = ba.length, + autoRound = (_autoRound !== false), + i, xi, ni, bv, ev, bnums, enums, bn, rgba, temp, cv, str; + if (e.indexOf(",") !== -1 || b.indexOf(",") !== -1) { + ba = ba.join(" ").replace(_commasOutsideParenExp, ", ").split(" "); + ea = ea.join(" ").replace(_commasOutsideParenExp, ", ").split(" "); + l = ba.length; + } + if (l !== ea.length) { + //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")"); + ba = (dflt || "").split(" "); + l = ba.length; + } + pt.plugin = plugin; + pt.setRatio = setRatio; + for (i = 0; i < l; i++) { + bv = ba[i]; + ev = ea[i]; + bn = parseFloat(bv); + + //if the value begins with a number (most common). It's fine if it has a suffix like px + if (bn || bn === 0) { + pt.appendXtra("", bn, _parseChange(ev, bn), ev.replace(_relNumExp, ""), (autoRound && ev.indexOf("px") !== -1), true); + + //if the value is a color + } else if (clrs && (bv.charAt(0) === "#" || _colorLookup[bv] || _rgbhslExp.test(bv))) { + str = ev.charAt(ev.length - 1) === "," ? ")," : ")"; //if there's a comma at the end, retain it. + bv = _parseColor(bv); + ev = _parseColor(ev); + rgba = (bv.length + ev.length > 6); + if (rgba && !_supportsOpacity && ev[3] === 0) { //older versions of IE don't support rgba(), so if the destination alpha is 0, just use "transparent" for the end color + pt["xs" + pt.l] += pt.l ? " transparent" : "transparent"; + pt.e = pt.e.split(ea[i]).join("transparent"); + } else { + if (!_supportsOpacity) { //old versions of IE don't support rgba(). + rgba = false; + } + pt.appendXtra((rgba ? "rgba(" : "rgb("), bv[0], ev[0] - bv[0], ",", true, true) + .appendXtra("", bv[1], ev[1] - bv[1], ",", true) + .appendXtra("", bv[2], ev[2] - bv[2], (rgba ? "," : str), true); + if (rgba) { + bv = (bv.length < 4) ? 1 : bv[3]; + pt.appendXtra("", bv, ((ev.length < 4) ? 1 : ev[3]) - bv, str, false); + } + } + + } else { + bnums = bv.match(_numExp); //gets each group of numbers in the beginning value string and drops them into an array + + //if no number is found, treat it as a non-tweening value and just append the string to the current xs. + if (!bnums) { + pt["xs" + pt.l] += pt.l ? " " + bv : bv; + + //loop through all the numbers that are found and construct the extra values on the pt. + } else { + enums = ev.match(_relNumExp); //get each group of numbers in the end value string and drop them into an array. We allow relative values too, like +=50 or -=.5 + if (!enums || enums.length !== bnums.length) { + //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")"); + return pt; + } + ni = 0; + for (xi = 0; xi < bnums.length; xi++) { + cv = bnums[xi]; + temp = bv.indexOf(cv, ni); + pt.appendXtra(bv.substr(ni, temp - ni), Number(cv), _parseChange(enums[xi], cv), "", (autoRound && bv.substr(temp + cv.length, 2) === "px"), (xi === 0)); + ni = temp + cv.length; + } + pt["xs" + pt.l] += bv.substr(ni); + } + } + } + //if there are relative values ("+=" or "-=" prefix), we need to adjust the ending value to eliminate the prefixes and combine the values properly. + if (e.indexOf("=") !== -1) if (pt.data) { + str = pt.xs0 + pt.data.s; + for (i = 1; i < pt.l; i++) { + str += pt["xs" + i] + pt.data["xn" + i]; + } + pt.e = str + pt["xs" + i]; + } + if (!pt.l) { + pt.type = -1; + pt.xs0 = pt.e; + } + return pt.xfirst || pt; + }, + i = 9; + + + p = CSSPropTween.prototype; + p.l = p.pr = 0; //length (number of extra properties like xn1, xn2, xn3, etc. + while (--i > 0) { + p["xn" + i] = 0; + p["xs" + i] = ""; + } + p.xs0 = ""; + p._next = p._prev = p.xfirst = p.data = p.plugin = p.setRatio = p.rxp = null; + + + /** + * Appends and extra tweening value to a CSSPropTween and automatically manages any prefix and suffix strings. The first extra value is stored in the s and c of the main CSSPropTween instance, but thereafter any extras are stored in the xn1, xn2, xn3, etc. The prefixes and suffixes are stored in the xs0, xs1, xs2, etc. properties. For example, if I walk through a clip value like "rect(10px, 5px, 0px, 20px)", the values would be stored like this: + * xs0:"rect(", s:10, xs1:"px, ", xn1:5, xs2:"px, ", xn2:0, xs3:"px, ", xn3:20, xn4:"px)" + * And they'd all get joined together when the CSSPlugin renders (in the setRatio() method). + * @param {string=} pfx Prefix (if any) + * @param {!number} s Starting value + * @param {!number} c Change in numeric value over the course of the entire tween. For example, if the start is 5 and the end is 100, the change would be 95. + * @param {string=} sfx Suffix (if any) + * @param {boolean=} r Round (if true). + * @param {boolean=} pad If true, this extra value should be separated by the previous one by a space. If there is no previous extra and pad is true, it will automatically drop the space. + * @return {CSSPropTween} returns itself so that multiple methods can be chained together. + */ + p.appendXtra = function(pfx, s, c, sfx, r, pad) { + var pt = this, + l = pt.l; + pt["xs" + l] += (pad && l) ? " " + pfx : pfx || ""; + if (!c) if (l !== 0 && !pt.plugin) { //typically we'll combine non-changing values right into the xs to optimize performance, but we don't combine them when there's a plugin that will be tweening the values because it may depend on the values being split apart, like for a bezier, if a value doesn't change between the first and second iteration but then it does on the 3rd, we'll run into trouble because there's no xn slot for that value! + pt["xs" + l] += s + (sfx || ""); + return pt; + } + pt.l++; + pt.type = pt.setRatio ? 2 : 1; + pt["xs" + pt.l] = sfx || ""; + if (l > 0) { + pt.data["xn" + l] = s + c; + pt.rxp["xn" + l] = r; //round extra property (we need to tap into this in the _parseToProxy() method) + pt["xn" + l] = s; + if (!pt.plugin) { + pt.xfirst = new CSSPropTween(pt, "xn" + l, s, c, pt.xfirst || pt, 0, pt.n, r, pt.pr); + pt.xfirst.xs0 = 0; //just to ensure that the property stays numeric which helps modern browsers speed up processing. Remember, in the setRatio() method, we do pt.t[pt.p] = val + pt.xs0 so if pt.xs0 is "" (the default), it'll cast the end value as a string. When a property is a number sometimes and a string sometimes, it prevents the compiler from locking in the data type, slowing things down slightly. + } + return pt; + } + pt.data = {s:s + c}; + pt.rxp = {}; + pt.s = s; + pt.c = c; + pt.r = r; + return pt; + }; + + /** + * @constructor A SpecialProp is basically a css property that needs to be treated in a non-standard way, like if it may contain a complex value like boxShadow:"5px 10px 15px rgb(255, 102, 51)" or if it is associated with another plugin like ThrowPropsPlugin or BezierPlugin. Every SpecialProp is associated with a particular property name like "boxShadow" or "throwProps" or "bezier" and it will intercept those values in the vars object that's passed to the CSSPlugin and handle them accordingly. + * @param {!string} p Property name (like "boxShadow" or "throwProps") + * @param {Object=} options An object containing any of the following configuration options: + * - defaultValue: the default value + * - parser: A function that should be called when the associated property name is found in the vars. This function should return a CSSPropTween instance and it should ensure that it is properly inserted into the linked list. It will receive 4 paramters: 1) The target, 2) The value defined in the vars, 3) The CSSPlugin instance (whose _firstPT should be used for the linked list), and 4) A computed style object if one was calculated (this is a speed optimization that allows retrieval of starting values quicker) + * - formatter: a function that formats any value received for this special property (for example, boxShadow could take "5px 5px red" and format it to "5px 5px 0px 0px red" so that both the beginning and ending values have a common order and quantity of values.) + * - prefix: if true, we'll determine whether or not this property requires a vendor prefix (like Webkit or Moz or ms or O) + * - color: set this to true if the value for this SpecialProp may contain color-related values like rgb(), rgba(), etc. + * - priority: priority in the linked list order. Higher priority SpecialProps will be updated before lower priority ones. The default priority is 0. + * - multi: if true, the formatter should accommodate a comma-delimited list of values, like boxShadow could have multiple boxShadows listed out. + * - collapsible: if true, the formatter should treat the value like it's a top/right/bottom/left value that could be collapsed, like "5px" would apply to all, "5px, 10px" would use 5px for top/bottom and 10px for right/left, etc. + * - keyword: a special keyword that can [optionally] be found inside the value (like "inset" for boxShadow). This allows us to validate beginning/ending values to make sure they match (if the keyword is found in one, it'll be added to the other for consistency by default). + */ + var SpecialProp = function(p, options) { + options = options || {}; + this.p = options.prefix ? _checkPropPrefix(p) || p : p; + _specialProps[p] = _specialProps[this.p] = this; + this.format = options.formatter || _getFormatter(options.defaultValue, options.color, options.collapsible, options.multi); + if (options.parser) { + this.parse = options.parser; + } + this.clrs = options.color; + this.multi = options.multi; + this.keyword = options.keyword; + this.dflt = options.defaultValue; + this.pr = options.priority || 0; + }, + + //shortcut for creating a new SpecialProp that can accept multiple properties as a comma-delimited list (helps minification). dflt can be an array for multiple values (we don't do a comma-delimited list because the default value may contain commas, like rect(0px,0px,0px,0px)). We attach this method to the SpecialProp class/object instead of using a private _createSpecialProp() method so that we can tap into it externally if necessary, like from another plugin. + _registerComplexSpecialProp = _internals._registerComplexSpecialProp = function(p, options, defaults) { + if (typeof(options) !== "object") { + options = {parser:defaults}; //to make backwards compatible with older versions of BezierPlugin and ThrowPropsPlugin + } + var a = p.split(","), + d = options.defaultValue, + i, temp; + defaults = defaults || [d]; + for (i = 0; i < a.length; i++) { + options.prefix = (i === 0 && options.prefix); + options.defaultValue = defaults[i] || d; + temp = new SpecialProp(a[i], options); + } + }, + + //creates a placeholder special prop for a plugin so that the property gets caught the first time a tween of it is attempted, and at that time it makes the plugin register itself, thus taking over for all future tweens of that property. This allows us to not mandate that things load in a particular order and it also allows us to log() an error that informs the user when they attempt to tween an external plugin-related property without loading its .js file. + _registerPluginProp = function(p) { + if (!_specialProps[p]) { + var pluginName = p.charAt(0).toUpperCase() + p.substr(1) + "Plugin"; + _registerComplexSpecialProp(p, {parser:function(t, e, p, cssp, pt, plugin, vars) { + var pluginClass = (window.GreenSockGlobals || window).com.greensock.plugins[pluginName]; + if (!pluginClass) { + _log("Error: " + pluginName + " js file not loaded."); + return pt; + } + pluginClass._cssRegister(); + return _specialProps[p].parse(t, e, p, cssp, pt, plugin, vars); + }}); + } + }; + + + p = SpecialProp.prototype; + + /** + * Alias for _parseComplex() that automatically plugs in certain values for this SpecialProp, like its property name, whether or not colors should be sensed, the default value, and priority. It also looks for any keyword that the SpecialProp defines (like "inset" for boxShadow) and ensures that the beginning and ending values have the same number of values for SpecialProps where multi is true (like boxShadow and textShadow can have a comma-delimited list) + * @param {!Object} t target element + * @param {(string|number|object)} b beginning value + * @param {(string|number|object)} e ending (destination) value + * @param {CSSPropTween=} pt next CSSPropTween in the linked list + * @param {TweenPlugin=} plugin If another plugin will be tweening the complex value, that TweenPlugin instance goes here. + * @param {function=} setRatio If a custom setRatio() method should be used to handle this complex value, that goes here. + * @return {CSSPropTween=} First CSSPropTween in the linked list + */ + p.parseComplex = function(t, b, e, pt, plugin, setRatio) { + var kwd = this.keyword, + i, ba, ea, l, bi, ei; + //if this SpecialProp's value can contain a comma-delimited list of values (like boxShadow or textShadow), we must parse them in a special way, and look for a keyword (like "inset" for boxShadow) and ensure that the beginning and ending BOTH have it if the end defines it as such. We also must ensure that there are an equal number of values specified (we can't tween 1 boxShadow to 3 for example) + if (this.multi) if (_commasOutsideParenExp.test(e) || _commasOutsideParenExp.test(b)) { + ba = b.replace(_commasOutsideParenExp, "|").split("|"); + ea = e.replace(_commasOutsideParenExp, "|").split("|"); + } else if (kwd) { + ba = [b]; + ea = [e]; + } + if (ea) { + l = (ea.length > ba.length) ? ea.length : ba.length; + for (i = 0; i < l; i++) { + b = ba[i] = ba[i] || this.dflt; + e = ea[i] = ea[i] || this.dflt; + if (kwd) { + bi = b.indexOf(kwd); + ei = e.indexOf(kwd); + if (bi !== ei) { + e = (ei === -1) ? ea : ba; + e[i] += " " + kwd; + } + } + } + b = ba.join(", "); + e = ea.join(", "); + } + return _parseComplex(t, this.p, b, e, this.clrs, this.dflt, pt, this.pr, plugin, setRatio); + }; + + /** + * Accepts a target and end value and spits back a CSSPropTween that has been inserted into the CSSPlugin's linked list and conforms with all the conventions we use internally, like type:-1, 0, 1, or 2, setting up any extra property tweens, priority, etc. For example, if we have a boxShadow SpecialProp and call: + * this._firstPT = sp.parse(element, "5px 10px 20px rgb(2550,102,51)", "boxShadow", this); + * It should figure out the starting value of the element's boxShadow, compare it to the provided end value and create all the necessary CSSPropTweens of the appropriate types to tween the boxShadow. The CSSPropTween that gets spit back should already be inserted into the linked list (the 4th parameter is the current head, so prepend to that). + * @param {!Object} t Target object whose property is being tweened + * @param {Object} e End value as provided in the vars object (typically a string, but not always - like a throwProps would be an object). + * @param {!string} p Property name + * @param {!CSSPlugin} cssp The CSSPlugin instance that should be associated with this tween. + * @param {?CSSPropTween} pt The CSSPropTween that is the current head of the linked list (we'll prepend to it) + * @param {TweenPlugin=} plugin If a plugin will be used to tween the parsed value, this is the plugin instance. + * @param {Object=} vars Original vars object that contains the data for parsing. + * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parse() call. + */ + p.parse = function(t, e, p, cssp, pt, plugin, vars) { + return this.parseComplex(t.style, this.format(_getStyle(t, this.p, _cs, false, this.dflt)), this.format(e), pt, plugin); + }; + + /** + * Registers a special property that should be intercepted from any "css" objects defined in tweens. This allows you to handle them however you want without CSSPlugin doing it for you. The 2nd parameter should be a function that accepts 3 parameters: + * 1) Target object whose property should be tweened (typically a DOM element) + * 2) The end/destination value (could be a string, number, object, or whatever you want) + * 3) The tween instance (you probably don't need to worry about this, but it can be useful for looking up information like the duration) + * + * Then, your function should return a function which will be called each time the tween gets rendered, passing a numeric "ratio" parameter to your function that indicates the change factor (usually between 0 and 1). For example: + * + * CSSPlugin.registerSpecialProp("myCustomProp", function(target, value, tween) { + * var start = target.style.width; + * return function(ratio) { + * target.style.width = (start + value * ratio) + "px"; + * console.log("set width to " + target.style.width); + * } + * }, 0); + * + * Then, when I do this tween, it will trigger my special property: + * + * TweenLite.to(element, 1, {css:{myCustomProp:100}}); + * + * In the example, of course, we're just changing the width, but you can do anything you want. + * + * @param {!string} name Property name (or comma-delimited list of property names) that should be intercepted and handled by your function. For example, if I define "myCustomProp", then it would handle that portion of the following tween: TweenLite.to(element, 1, {css:{myCustomProp:100}}) + * @param {!function(Object, Object, Object, string):function(number)} onInitTween The function that will be called when a tween of this special property is performed. The function will receive 4 parameters: 1) Target object that should be tweened, 2) Value that was passed to the tween, 3) The tween instance itself (rarely used), and 4) The property name that's being tweened. Your function should return a function that should be called on every update of the tween. That function will receive a single parameter that is a "change factor" value (typically between 0 and 1) indicating the amount of change as a ratio. You can use this to determine how to set the values appropriately in your function. + * @param {number=} priority Priority that helps the engine determine the order in which to set the properties (default: 0). Higher priority properties will be updated before lower priority ones. + */ + CSSPlugin.registerSpecialProp = function(name, onInitTween, priority) { + _registerComplexSpecialProp(name, {parser:function(t, e, p, cssp, pt, plugin, vars) { + var rv = new CSSPropTween(t, p, 0, 0, pt, 2, p, false, priority); + rv.plugin = plugin; + rv.setRatio = onInitTween(t, e, cssp._tween, p); + return rv; + }, priority:priority}); + }; + + + + + + + + + //transform-related methods and properties + var _transformProps = ("scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective").split(","), + _transformProp = _checkPropPrefix("transform"), //the Javascript (camelCase) transform property, like msTransform, WebkitTransform, MozTransform, or OTransform. + _transformPropCSS = _prefixCSS + "transform", + _transformOriginProp = _checkPropPrefix("transformOrigin"), + _supports3D = (_checkPropPrefix("perspective") !== null), + Transform = _internals.Transform = function() { + this.skewY = 0; + }, + + /** + * Parses the transform values for an element, returning an object with x, y, z, scaleX, scaleY, scaleZ, rotation, rotationX, rotationY, skewX, and skewY properties. Note: by default (for performance reasons), all skewing is combined into skewX and rotation but skewY still has a place in the transform object so that we can record how much of the skew is attributed to skewX vs skewY. Remember, a skewY of 10 looks the same as a rotation of 10 and skewX of -10. + * @param {!Object} t target element + * @param {Object=} cs computed style object (optional) + * @param {boolean=} rec if true, the transform values will be recorded to the target element's _gsTransform object, like target._gsTransform = {x:0, y:0, z:0, scaleX:1...} + * @param {boolean=} parse if true, we'll ignore any _gsTransform values that already exist on the element, and force a reparsing of the css (calculated style) + * @return {object} object containing all of the transform properties/values like {x:0, y:0, z:0, scaleX:1...} + */ + _getTransform = _internals.getTransform = function(t, cs, rec, parse) { + if (t._gsTransform && rec && !parse) { + return t._gsTransform; //if the element already has a _gsTransform, use that. Note: some browsers don't accurately return the calculated style for the transform (particularly for SVG), so it's almost always safest to just use the values we've already applied rather than re-parsing things. + } + var tm = rec ? t._gsTransform || new Transform() : new Transform(), + invX = (tm.scaleX < 0), //in order to interpret things properly, we need to know if the user applied a negative scaleX previously so that we can adjust the rotation and skewX accordingly. Otherwise, if we always interpret a flipped matrix as affecting scaleY and the user only wants to tween the scaleX on multiple sequential tweens, it would keep the negative scaleY without that being the user's intent. + min = 0.00002, + rnd = 100000, + minAngle = 179.99, + minPI = minAngle * _DEG2RAD, + zOrigin = _supports3D ? parseFloat(_getStyle(t, _transformOriginProp, cs, false, "0 0 0").split(" ")[2]) || tm.zOrigin || 0 : 0, + s, m, i, n, dec, scaleX, scaleY, rotation, skewX, difX, difY, difR, difS; + if (_transformProp) { + s = _getStyle(t, _transformPropCSS, cs, true); + } else if (t.currentStyle) { + //for older versions of IE, we need to interpret the filter portion that is in the format: progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=-1, M21=1, M22=6.123233995736766e-17, sizingMethod='auto expand') Notice that we need to swap b and c compared to a normal matrix. + s = t.currentStyle.filter.match(_ieGetMatrixExp); + s = (s && s.length === 4) ? [s[0].substr(4), Number(s[2].substr(4)), Number(s[1].substr(4)), s[3].substr(4), (tm.x || 0), (tm.y || 0)].join(",") : ""; + } + //split the matrix values out into an array (m for matrix) + m = (s || "").match(/(?:\-|\b)[\d\-\.e]+\b/gi) || []; + i = m.length; + while (--i > -1) { + n = Number(m[i]); + m[i] = (dec = n - (n |= 0)) ? ((dec * rnd + (dec < 0 ? -0.5 : 0.5)) | 0) / rnd + n : n; //convert strings to Numbers and round to 5 decimal places to avoid issues with tiny numbers. Roughly 20x faster than Number.toFixed(). We also must make sure to round before dividing so that values like 0.9999999999 become 1 to avoid glitches in browser rendering and interpretation of flipped/rotated 3D matrices. And don't just multiply the number by rnd, floor it, and then divide by rnd because the bitwise operations max out at a 32-bit signed integer, thus it could get clipped at a relatively low value (like 22,000.00000 for example). + } + if (m.length === 16) { + + //we'll only look at these position-related 6 variables first because if x/y/z all match, it's relatively safe to assume we don't need to re-parse everything which risks losing important rotational information (like rotationX:180 plus rotationY:180 would look the same as rotation:180 - there's no way to know for sure which direction was taken based solely on the matrix3d() values) + var a13 = m[8], a23 = m[9], a33 = m[10], + a14 = m[12], a24 = m[13], a34 = m[14]; + + //we manually compensate for non-zero z component of transformOrigin to work around bugs in Safari + if (tm.zOrigin) { + a34 = -tm.zOrigin; + a14 = a13*a34-m[12]; + a24 = a23*a34-m[13]; + a34 = a33*a34+tm.zOrigin-m[14]; + } + + //only parse from the matrix if we MUST because not only is it usually unnecessary due to the fact that we store the values in the _gsTransform object, but also because it's impossible to accurately interpret rotationX, rotationY, rotationZ, scaleX, and scaleY if all are applied, so it's much better to rely on what we store. However, we must parse the first time that an object is tweened. We also assume that if the position has changed, the user must have done some styling changes outside of CSSPlugin, thus we force a parse in that scenario. + if (!rec || parse || tm.rotationX == null) { + var a11 = m[0], a21 = m[1], a31 = m[2], a41 = m[3], + a12 = m[4], a22 = m[5], a32 = m[6], a42 = m[7], + a43 = m[11], + angle = Math.atan2(a32, a33), + xFlip = (angle < -minPI || angle > minPI), + t1, t2, t3, cos, sin, yFlip, zFlip; + tm.rotationX = angle * _RAD2DEG; + //rotationX + if (angle) { + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a12*cos+a13*sin; + t2 = a22*cos+a23*sin; + t3 = a32*cos+a33*sin; + a13 = a12*-sin+a13*cos; + a23 = a22*-sin+a23*cos; + a33 = a32*-sin+a33*cos; + a43 = a42*-sin+a43*cos; + a12 = t1; + a22 = t2; + a32 = t3; + } + //rotationY + angle = Math.atan2(a13, a11); + tm.rotationY = angle * _RAD2DEG; + if (angle) { + yFlip = (angle < -minPI || angle > minPI); + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a11*cos-a13*sin; + t2 = a21*cos-a23*sin; + t3 = a31*cos-a33*sin; + a23 = a21*sin+a23*cos; + a33 = a31*sin+a33*cos; + a43 = a41*sin+a43*cos; + a11 = t1; + a21 = t2; + a31 = t3; + } + //rotationZ + angle = Math.atan2(a21, a22); + tm.rotation = angle * _RAD2DEG; + if (angle) { + zFlip = (angle < -minPI || angle > minPI); + cos = Math.cos(-angle); + sin = Math.sin(-angle); + a11 = a11*cos+a12*sin; + t2 = a21*cos+a22*sin; + a22 = a21*-sin+a22*cos; + a32 = a31*-sin+a32*cos; + a21 = t2; + } + + if (zFlip && xFlip) { + tm.rotation = tm.rotationX = 0; + } else if (zFlip && yFlip) { + tm.rotation = tm.rotationY = 0; + } else if (yFlip && xFlip) { + tm.rotationY = tm.rotationX = 0; + } + + tm.scaleX = ((Math.sqrt(a11 * a11 + a21 * a21) * rnd + 0.5) | 0) / rnd; + tm.scaleY = ((Math.sqrt(a22 * a22 + a23 * a23) * rnd + 0.5) | 0) / rnd; + tm.scaleZ = ((Math.sqrt(a32 * a32 + a33 * a33) * rnd + 0.5) | 0) / rnd; + tm.skewX = 0; + tm.perspective = a43 ? 1 / ((a43 < 0) ? -a43 : a43) : 0; + tm.x = a14; + tm.y = a24; + tm.z = a34; + } + + } else if ((!_supports3D || parse || !m.length || tm.x !== m[4] || tm.y !== m[5] || (!tm.rotationX && !tm.rotationY)) && !(tm.x !== undefined && _getStyle(t, "display", cs) === "none")) { //sometimes a 6-element matrix is returned even when we performed 3D transforms, like if rotationX and rotationY are 180. In cases like this, we still need to honor the 3D transforms. If we just rely on the 2D info, it could affect how the data is interpreted, like scaleY might get set to -1 or rotation could get offset by 180 degrees. For example, do a TweenLite.to(element, 1, {css:{rotationX:180, rotationY:180}}) and then later, TweenLite.to(element, 1, {css:{rotationX:0}}) and without this conditional logic in place, it'd jump to a state of being unrotated when the 2nd tween starts. Then again, we need to honor the fact that the user COULD alter the transforms outside of CSSPlugin, like by manually applying new css, so we try to sense that by looking at x and y because if those changed, we know the changes were made outside CSSPlugin and we force a reinterpretation of the matrix values. Also, in Webkit browsers, if the element's "display" is "none", its calculated style value will always return empty, so if we've already recorded the values in the _gsTransform object, we'll just rely on those. + var k = (m.length >= 6), + a = k ? m[0] : 1, + b = m[1] || 0, + c = m[2] || 0, + d = k ? m[3] : 1; + tm.x = m[4] || 0; + tm.y = m[5] || 0; + scaleX = Math.sqrt(a * a + b * b); + scaleY = Math.sqrt(d * d + c * c); + rotation = (a || b) ? Math.atan2(b, a) * _RAD2DEG : tm.rotation || 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist). + skewX = (c || d) ? Math.atan2(c, d) * _RAD2DEG + rotation : tm.skewX || 0; + difX = scaleX - Math.abs(tm.scaleX || 0); + difY = scaleY - Math.abs(tm.scaleY || 0); + if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) { + if (invX) { + scaleX *= -1; + skewX += (rotation <= 0) ? 180 : -180; + rotation += (rotation <= 0) ? 180 : -180; + } else { + scaleY *= -1; + skewX += (skewX <= 0) ? 180 : -180; + } + } + difR = (rotation - tm.rotation) % 180; //note: matching ranges would be very small (+/-0.0001) or very close to 180. + difS = (skewX - tm.skewX) % 180; + //if there's already a recorded _gsTransform in place for the target, we should leave those values in place unless we know things changed for sure (beyond a super small amount). This gets around ambiguous interpretations, like if scaleX and scaleY are both -1, the matrix would be the same as if the rotation was 180 with normal scaleX/scaleY. If the user tweened to particular values, those must be prioritized to ensure animation is consistent. + if (tm.skewX === undefined || difX > min || difX < -min || difY > min || difY < -min || (difR > -minAngle && difR < minAngle && (difR * rnd) | 0 !== 0) || (difS > -minAngle && difS < minAngle && (difS * rnd) | 0 !== 0)) { + tm.scaleX = scaleX; + tm.scaleY = scaleY; + tm.rotation = rotation; + tm.skewX = skewX; + } + if (_supports3D) { + tm.rotationX = tm.rotationY = tm.z = 0; + tm.perspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0; + tm.scaleZ = 1; + } + } + tm.zOrigin = zOrigin; + + //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 0 in these cases. The conditional logic here is faster than calling Math.abs(). Also, browsers tend to render a SLIGHTLY rotated object in a fuzzy way, so we need to snap to exactly 0 when appropriate. + for (i in tm) { + if (tm[i] < min) if (tm[i] > -min) { + tm[i] = 0; + } + } + //DEBUG: _log("parsed rotation: "+(tm.rotationX)+", "+(tm.rotationY)+", "+(tm.rotation)+", scale: "+tm.scaleX+", "+tm.scaleY+", "+tm.scaleZ+", position: "+tm.x+", "+tm.y+", "+tm.z+", perspective: "+tm.perspective); + if (rec) { + t._gsTransform = tm; //record to the object's _gsTransform which we use so that tweens can control individual properties independently (we need all the properties to accurately recompose the matrix in the setRatio() method) + } + return tm; + }, + + //for setting 2D transforms in IE6, IE7, and IE8 (must use a "filter" to emulate the behavior of modern day browser transforms) + _setIETransformRatio = function(v) { + var t = this.data, //refers to the element's _gsTransform object + ang = -t.rotation * _DEG2RAD, + skew = ang + t.skewX * _DEG2RAD, + rnd = 100000, + a = ((Math.cos(ang) * t.scaleX * rnd) | 0) / rnd, + b = ((Math.sin(ang) * t.scaleX * rnd) | 0) / rnd, + c = ((Math.sin(skew) * -t.scaleY * rnd) | 0) / rnd, + d = ((Math.cos(skew) * t.scaleY * rnd) | 0) / rnd, + style = this.t.style, + cs = this.t.currentStyle, + filters, val; + if (!cs) { + return; + } + val = b; //just for swapping the variables an inverting them (reused "val" to avoid creating another variable in memory). IE's filter matrix uses a non-standard matrix configuration (angle goes the opposite way, and b and c are reversed and inverted) + b = -c; + c = -val; + filters = cs.filter; + style.filter = ""; //remove filters so that we can accurately measure offsetWidth/offsetHeight + var w = this.t.offsetWidth, + h = this.t.offsetHeight, + clip = (cs.position !== "absolute"), + m = "progid:DXImageTransform.Microsoft.Matrix(M11=" + a + ", M12=" + b + ", M21=" + c + ", M22=" + d, + ox = t.x, + oy = t.y, + dx, dy; + + //if transformOrigin is being used, adjust the offset x and y + if (t.ox != null) { + dx = ((t.oxp) ? w * t.ox * 0.01 : t.ox) - w / 2; + dy = ((t.oyp) ? h * t.oy * 0.01 : t.oy) - h / 2; + ox += dx - (dx * a + dy * b); + oy += dy - (dx * c + dy * d); + } + + if (!clip) { + m += ", sizingMethod='auto expand')"; + } else { + dx = (w / 2); + dy = (h / 2); + //translate to ensure that transformations occur around the correct origin (default is center). + m += ", Dx=" + (dx - (dx * a + dy * b) + ox) + ", Dy=" + (dy - (dx * c + dy * d) + oy) + ")"; + } + if (filters.indexOf("DXImageTransform.Microsoft.Matrix(") !== -1) { + style.filter = filters.replace(_ieSetMatrixExp, m); + } else { + style.filter = m + " " + filters; //we must always put the transform/matrix FIRST (before alpha(opacity=xx)) to avoid an IE bug that slices part of the object when rotation is applied with alpha. + } + + //at the end or beginning of the tween, if the matrix is normal (1, 0, 0, 1) and opacity is 100 (or doesn't exist), remove the filter to improve browser performance. + if (v === 0 || v === 1) if (a === 1) if (b === 0) if (c === 0) if (d === 1) if (!clip || m.indexOf("Dx=0, Dy=0") !== -1) if (!_opacityExp.test(filters) || parseFloat(RegExp.$1) === 100) if (filters.indexOf("gradient(" && filters.indexOf("Alpha")) === -1) { + style.removeAttribute("filter"); + } + + //we must set the margins AFTER applying the filter in order to avoid some bugs in IE8 that could (in rare scenarios) cause them to be ignored intermittently (vibration). + if (!clip) { + var mult = (_ieVers < 8) ? 1 : -1, //in Internet Explorer 7 and before, the box model is broken, causing the browser to treat the width/height of the actual rotated filtered image as the width/height of the box itself, but Microsoft corrected that in IE8. We must use a negative offset in IE8 on the right/bottom + marg, prop, dif; + dx = t.ieOffsetX || 0; + dy = t.ieOffsetY || 0; + t.ieOffsetX = Math.round((w - ((a < 0 ? -a : a) * w + (b < 0 ? -b : b) * h)) / 2 + ox); + t.ieOffsetY = Math.round((h - ((d < 0 ? -d : d) * h + (c < 0 ? -c : c) * w)) / 2 + oy); + for (i = 0; i < 4; i++) { + prop = _margins[i]; + marg = cs[prop]; + //we need to get the current margin in case it is being tweened separately (we want to respect that tween's changes) + val = (marg.indexOf("px") !== -1) ? parseFloat(marg) : _convertToPixels(this.t, prop, parseFloat(marg), marg.replace(_suffixExp, "")) || 0; + if (val !== t[prop]) { + dif = (i < 2) ? -t.ieOffsetX : -t.ieOffsetY; //if another tween is controlling a margin, we cannot only apply the difference in the ieOffsets, so we essentially zero-out the dx and dy here in that case. We record the margin(s) later so that we can keep comparing them, making this code very flexible. + } else { + dif = (i < 2) ? dx - t.ieOffsetX : dy - t.ieOffsetY; + } + style[prop] = (t[prop] = Math.round( val - dif * ((i === 0 || i === 2) ? 1 : mult) )) + "px"; + } + } + }, + + _set3DTransformRatio = _internals.set3DTransformRatio = function(v) { + var t = this.data, //refers to the element's _gsTransform object + style = this.t.style, + angle = t.rotation * _DEG2RAD, + sx = t.scaleX, + sy = t.scaleY, + sz = t.scaleZ, + perspective = t.perspective, + a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, + zOrigin, rnd, cos, sin, t1, t2, t3, t4; + if (v === 1 || v === 0) if (t.force3D === "auto") if (!t.rotationY && !t.rotationX && sz === 1 && !perspective && !t.z) { //on the final render (which could be 0 for a from tween), if there are no 3D aspects, render in 2D to free up memory and improve performance especially on mobile devices + _set2DTransformRatio.call(this, v); + return; + } + if (_isFirefox) { + var n = 0.0001; + if (sx < n && sx > -n) { //Firefox has a bug (at least in v25) that causes it to render the transparent part of 32-bit PNG images as black when displayed inside an iframe and the 3D scale is very small and doesn't change sufficiently enough between renders (like if you use a Power4.easeInOut to scale from 0 to 1 where the beginning values only change a tiny amount to begin the tween before accelerating). In this case, we force the scale to be 0.00002 instead which is visually the same but works around the Firefox issue. + sx = sz = 0.00002; + } + if (sy < n && sy > -n) { + sy = sz = 0.00002; + } + if (perspective && !t.z && !t.rotationX && !t.rotationY) { //Firefox has a bug that causes elements to have an odd super-thin, broken/dotted black border on elements that have a perspective set but aren't utilizing 3D space (no rotationX, rotationY, or z). + perspective = 0; + } + } + if (angle || t.skewX) { + cos = Math.cos(angle); + sin = Math.sin(angle); + a11 = cos; + a21 = sin; + if (t.skewX) { + angle -= t.skewX * _DEG2RAD; + cos = Math.cos(angle); + sin = Math.sin(angle); + if (t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does + t1 = Math.tan(t.skewX * _DEG2RAD); + t1 = Math.sqrt(1 + t1 * t1); + cos *= t1; + sin *= t1; + } + } + a12 = -sin; + a22 = cos; + + } else if (!t.rotationY && !t.rotationX && sz === 1 && !perspective) { //if we're only translating and/or 2D scaling, this is faster... + style[_transformProp] = "translate3d(" + t.x + "px," + t.y + "px," + t.z +"px)" + ((sx !== 1 || sy !== 1) ? " scale(" + sx + "," + sy + ")" : ""); + return; + } else { + a11 = a22 = 1; + a12 = a21 = 0; + } + a33 = 1; + a13 = a14 = a23 = a24 = a31 = a32 = a34 = a41 = a42 = 0; + a43 = (perspective) ? -1 / perspective : 0; + zOrigin = t.zOrigin; + rnd = 100000; + angle = t.rotationY * _DEG2RAD; + if (angle) { + cos = Math.cos(angle); + sin = Math.sin(angle); + a31 = a33*-sin; + a41 = a43*-sin; + a13 = a11*sin; + a23 = a21*sin; + a33 *= cos; + a43 *= cos; + a11 *= cos; + a21 *= cos; + } + angle = t.rotationX * _DEG2RAD; + if (angle) { + cos = Math.cos(angle); + sin = Math.sin(angle); + t1 = a12*cos+a13*sin; + t2 = a22*cos+a23*sin; + t3 = a32*cos+a33*sin; + t4 = a42*cos+a43*sin; + a13 = a12*-sin+a13*cos; + a23 = a22*-sin+a23*cos; + a33 = a32*-sin+a33*cos; + a43 = a42*-sin+a43*cos; + a12 = t1; + a22 = t2; + a32 = t3; + a42 = t4; + } + if (sz !== 1) { + a13*=sz; + a23*=sz; + a33*=sz; + a43*=sz; + } + if (sy !== 1) { + a12*=sy; + a22*=sy; + a32*=sy; + a42*=sy; + } + if (sx !== 1) { + a11*=sx; + a21*=sx; + a31*=sx; + a41*=sx; + } + if (zOrigin) { + a34 -= zOrigin; + a14 = a13*a34; + a24 = a23*a34; + a34 = a33*a34+zOrigin; + } + //we round the x, y, and z slightly differently to allow even larger values. + a14 = (t1 = (a14 += t.x) - (a14 |= 0)) ? ((t1 * rnd + (t1 < 0 ? -0.5 : 0.5)) | 0) / rnd + a14 : a14; + a24 = (t1 = (a24 += t.y) - (a24 |= 0)) ? ((t1 * rnd + (t1 < 0 ? -0.5 : 0.5)) | 0) / rnd + a24 : a24; + a34 = (t1 = (a34 += t.z) - (a34 |= 0)) ? ((t1 * rnd + (t1 < 0 ? -0.5 : 0.5)) | 0) / rnd + a34 : a34; + style[_transformProp] = "matrix3d(" + [ (((a11 * rnd) | 0) / rnd), (((a21 * rnd) | 0) / rnd), (((a31 * rnd) | 0) / rnd), (((a41 * rnd) | 0) / rnd), (((a12 * rnd) | 0) / rnd), (((a22 * rnd) | 0) / rnd), (((a32 * rnd) | 0) / rnd), (((a42 * rnd) | 0) / rnd), (((a13 * rnd) | 0) / rnd), (((a23 * rnd) | 0) / rnd), (((a33 * rnd) | 0) / rnd), (((a43 * rnd) | 0) / rnd), a14, a24, a34, (perspective ? (1 + (-a34 / perspective)) : 1) ].join(",") + ")"; + }, + + _set2DTransformRatio = _internals.set2DTransformRatio = function(v) { + var t = this.data, //refers to the element's _gsTransform object + targ = this.t, + style = targ.style, + ang, skew, rnd, sx, sy; + if (t.rotationX || t.rotationY || t.z || t.force3D === true || (t.force3D === "auto" && v !== 1 && v !== 0)) { //if a 3D tween begins while a 2D one is running, we need to kick the rendering over to the 3D method. For example, imagine a yoyo-ing, infinitely repeating scale tween running, and then the object gets rotated in 3D space with a different tween. + this.setRatio = _set3DTransformRatio; + _set3DTransformRatio.call(this, v); + return; + } + if (!t.rotation && !t.skewX) { + style[_transformProp] = "matrix(" + t.scaleX + ",0,0," + t.scaleY + "," + t.x + "," + t.y + ")"; + } else { + ang = t.rotation * _DEG2RAD; + skew = ang - t.skewX * _DEG2RAD; + rnd = 100000; + sx = t.scaleX * rnd; + sy = t.scaleY * rnd; + //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 5 decimal places. + style[_transformProp] = "matrix(" + (((Math.cos(ang) * sx) | 0) / rnd) + "," + (((Math.sin(ang) * sx) | 0) / rnd) + "," + (((Math.sin(skew) * -sy) | 0) / rnd) + "," + (((Math.cos(skew) * sy) | 0) / rnd) + "," + t.x + "," + t.y + ")"; + } + }; + + _registerComplexSpecialProp("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType", {parser:function(t, e, p, cssp, pt, plugin, vars) { + if (cssp._transform) { return pt; } //only need to parse the transform once, and only if the browser supports it. + var m1 = cssp._transform = _getTransform(t, _cs, true, vars.parseTransform), + style = t.style, + min = 0.000001, + i = _transformProps.length, + v = vars, + endRotations = {}, + m2, skewY, copy, orig, has3D, hasChange, dr; + if (typeof(v.transform) === "string" && _transformProp) { //for values like transform:"rotate(60deg) scale(0.5, 0.8)" + copy = _tempDiv.style; //don't use the original target because it might be SVG in which case some browsers don't report computed style correctly. + copy[_transformProp] = v.transform; + copy.display = "block"; //if display is "none", the browser often refuses to report the transform properties correctly. + copy.position = "absolute"; + _doc.body.appendChild(_tempDiv); + m2 = _getTransform(_tempDiv, null, false); + _doc.body.removeChild(_tempDiv); + } else if (typeof(v) === "object") { //for values like scaleX, scaleY, rotation, x, y, skewX, and skewY or transform:{...} (object) + m2 = {scaleX:_parseVal((v.scaleX != null) ? v.scaleX : v.scale, m1.scaleX), + scaleY:_parseVal((v.scaleY != null) ? v.scaleY : v.scale, m1.scaleY), + scaleZ:_parseVal(v.scaleZ, m1.scaleZ), + x:_parseVal(v.x, m1.x), + y:_parseVal(v.y, m1.y), + z:_parseVal(v.z, m1.z), + perspective:_parseVal(v.transformPerspective, m1.perspective)}; + dr = v.directionalRotation; + if (dr != null) { + if (typeof(dr) === "object") { + for (copy in dr) { + v[copy] = dr[copy]; + } + } else { + v.rotation = dr; + } + } + m2.rotation = _parseAngle(("rotation" in v) ? v.rotation : ("shortRotation" in v) ? v.shortRotation + "_short" : ("rotationZ" in v) ? v.rotationZ : m1.rotation, m1.rotation, "rotation", endRotations); + if (_supports3D) { + m2.rotationX = _parseAngle(("rotationX" in v) ? v.rotationX : ("shortRotationX" in v) ? v.shortRotationX + "_short" : m1.rotationX || 0, m1.rotationX, "rotationX", endRotations); + m2.rotationY = _parseAngle(("rotationY" in v) ? v.rotationY : ("shortRotationY" in v) ? v.shortRotationY + "_short" : m1.rotationY || 0, m1.rotationY, "rotationY", endRotations); + } + m2.skewX = (v.skewX == null) ? m1.skewX : _parseAngle(v.skewX, m1.skewX); + + //note: for performance reasons, we combine all skewing into the skewX and rotation values, ignoring skewY but we must still record it so that we can discern how much of the overall skew is attributed to skewX vs. skewY. Otherwise, if the skewY would always act relative (tween skewY to 10deg, for example, multiple times and if we always combine things into skewX, we can't remember that skewY was 10 from last time). Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of -10 degrees. + m2.skewY = (v.skewY == null) ? m1.skewY : _parseAngle(v.skewY, m1.skewY); + if ((skewY = m2.skewY - m1.skewY)) { + m2.skewX += skewY; + m2.rotation += skewY; + } + } + + if (_supports3D && v.force3D != null) { + m1.force3D = v.force3D; + hasChange = true; + } + + m1.skewType = v.skewType || m1.skewType || CSSPlugin.defaultSkewType; + + has3D = (m1.force3D || m1.z || m1.rotationX || m1.rotationY || m2.z || m2.rotationX || m2.rotationY || m2.perspective); + if (!has3D && v.scale != null) { + m2.scaleZ = 1; //no need to tween scaleZ. + } + + while (--i > -1) { + p = _transformProps[i]; + orig = m2[p] - m1[p]; + if (orig > min || orig < -min || _forcePT[p] != null) { + hasChange = true; + pt = new CSSPropTween(m1, p, m1[p], orig, pt); + if (p in endRotations) { + pt.e = endRotations[p]; //directional rotations typically have compensated values during the tween, but we need to make sure they end at exactly what the user requested + } + pt.xs0 = 0; //ensures the value stays numeric in setRatio() + pt.plugin = plugin; + cssp._overwriteProps.push(pt.n); + } + } + + orig = v.transformOrigin; + if (orig || (_supports3D && has3D && m1.zOrigin)) { //if anything 3D is happening and there's a transformOrigin with a z component that's non-zero, we must ensure that the transformOrigin's z-component is set to 0 so that we can manually do those calculations to get around Safari bugs. Even if the user didn't specifically define a "transformOrigin" in this particular tween (maybe they did it via css directly). + if (_transformProp) { + hasChange = true; + p = _transformOriginProp; + orig = (orig || _getStyle(t, p, _cs, false, "50% 50%")) + ""; //cast as string to avoid errors + pt = new CSSPropTween(style, p, 0, 0, pt, -1, "transformOrigin"); + pt.b = style[p]; + pt.plugin = plugin; + if (_supports3D) { + copy = m1.zOrigin; + orig = orig.split(" "); + m1.zOrigin = ((orig.length > 2 && !(copy !== 0 && orig[2] === "0px")) ? parseFloat(orig[2]) : copy) || 0; //Safari doesn't handle the z part of transformOrigin correctly, so we'll manually handle it in the _set3DTransformRatio() method. + pt.xs0 = pt.e = orig[0] + " " + (orig[1] || "50%") + " 0px"; //we must define a z value of 0px specifically otherwise iOS 5 Safari will stick with the old one (if one was defined)! + pt = new CSSPropTween(m1, "zOrigin", 0, 0, pt, -1, pt.n); //we must create a CSSPropTween for the _gsTransform.zOrigin so that it gets reset properly at the beginning if the tween runs backward (as opposed to just setting m1.zOrigin here) + pt.b = copy; + pt.xs0 = pt.e = m1.zOrigin; + } else { + pt.xs0 = pt.e = orig; + } + + //for older versions of IE (6-8), we need to manually calculate things inside the setRatio() function. We record origin x and y (ox and oy) and whether or not the values are percentages (oxp and oyp). + } else { + _parsePosition(orig + "", m1); + } + } + + if (hasChange) { + cssp._transformType = (has3D || this._transformType === 3) ? 3 : 2; //quicker than calling cssp._enableTransforms(); + } + return pt; + }, prefix:true}); + + _registerComplexSpecialProp("boxShadow", {defaultValue:"0px 0px 0px 0px #999", prefix:true, color:true, multi:true, keyword:"inset"}); + + _registerComplexSpecialProp("borderRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) { + e = this.format(e); + var props = ["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"], + style = t.style, + ea1, i, es2, bs2, bs, es, bn, en, w, h, esfx, bsfx, rel, hn, vn, em; + w = parseFloat(t.offsetWidth); + h = parseFloat(t.offsetHeight); + ea1 = e.split(" "); + for (i = 0; i < props.length; i++) { //if we're dealing with percentages, we must convert things separately for the horizontal and vertical axis! + if (this.p.indexOf("border")) { //older browsers used a prefix + props[i] = _checkPropPrefix(props[i]); + } + bs = bs2 = _getStyle(t, props[i], _cs, false, "0px"); + if (bs.indexOf(" ") !== -1) { + bs2 = bs.split(" "); + bs = bs2[0]; + bs2 = bs2[1]; + } + es = es2 = ea1[i]; + bn = parseFloat(bs); + bsfx = bs.substr((bn + "").length); + rel = (es.charAt(1) === "="); + if (rel) { + en = parseInt(es.charAt(0)+"1", 10); + es = es.substr(2); + en *= parseFloat(es); + esfx = es.substr((en + "").length - (en < 0 ? 1 : 0)) || ""; + } else { + en = parseFloat(es); + esfx = es.substr((en + "").length); + } + if (esfx === "") { + esfx = _suffixMap[p] || bsfx; + } + if (esfx !== bsfx) { + hn = _convertToPixels(t, "borderLeft", bn, bsfx); //horizontal number (we use a bogus "borderLeft" property just because the _convertToPixels() method searches for the keywords "Left", "Right", "Top", and "Bottom" to determine of it's a horizontal or vertical property, and we need "border" in the name so that it knows it should measure relative to the element itself, not its parent. + vn = _convertToPixels(t, "borderTop", bn, bsfx); //vertical number + if (esfx === "%") { + bs = (hn / w * 100) + "%"; + bs2 = (vn / h * 100) + "%"; + } else if (esfx === "em") { + em = _convertToPixels(t, "borderLeft", 1, "em"); + bs = (hn / em) + "em"; + bs2 = (vn / em) + "em"; + } else { + bs = hn + "px"; + bs2 = vn + "px"; + } + if (rel) { + es = (parseFloat(bs) + en) + esfx; + es2 = (parseFloat(bs2) + en) + esfx; + } + } + pt = _parseComplex(style, props[i], bs + " " + bs2, es + " " + es2, false, "0px", pt); + } + return pt; + }, prefix:true, formatter:_getFormatter("0px 0px 0px 0px", false, true)}); + _registerComplexSpecialProp("backgroundPosition", {defaultValue:"0 0", parser:function(t, e, p, cssp, pt, plugin) { + var bp = "background-position", + cs = (_cs || _getComputedStyle(t, null)), + bs = this.format( ((cs) ? _ieVers ? cs.getPropertyValue(bp + "-x") + " " + cs.getPropertyValue(bp + "-y") : cs.getPropertyValue(bp) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), //Internet Explorer doesn't report background-position correctly - we must query background-position-x and background-position-y and combine them (even in IE10). Before IE9, we must do the same with the currentStyle object and use camelCase + es = this.format(e), + ba, ea, i, pct, overlap, src; + if ((bs.indexOf("%") !== -1) !== (es.indexOf("%") !== -1)) { + src = _getStyle(t, "backgroundImage").replace(_urlExp, ""); + if (src && src !== "none") { + ba = bs.split(" "); + ea = es.split(" "); + _tempImg.setAttribute("src", src); //set the temp 's src to the background-image so that we can measure its width/height + i = 2; + while (--i > -1) { + bs = ba[i]; + pct = (bs.indexOf("%") !== -1); + if (pct !== (ea[i].indexOf("%") !== -1)) { + overlap = (i === 0) ? t.offsetWidth - _tempImg.width : t.offsetHeight - _tempImg.height; + ba[i] = pct ? (parseFloat(bs) / 100 * overlap) + "px" : (parseFloat(bs) / overlap * 100) + "%"; + } + } + bs = ba.join(" "); + } + } + return this.parseComplex(t.style, bs, es, pt, plugin); + }, formatter:_parsePosition}); + _registerComplexSpecialProp("backgroundSize", {defaultValue:"0 0", formatter:_parsePosition}); + _registerComplexSpecialProp("perspective", {defaultValue:"0px", prefix:true}); + _registerComplexSpecialProp("perspectiveOrigin", {defaultValue:"50% 50%", prefix:true}); + _registerComplexSpecialProp("transformStyle", {prefix:true}); + _registerComplexSpecialProp("backfaceVisibility", {prefix:true}); + _registerComplexSpecialProp("userSelect", {prefix:true}); + _registerComplexSpecialProp("margin", {parser:_getEdgeParser("marginTop,marginRight,marginBottom,marginLeft")}); + _registerComplexSpecialProp("padding", {parser:_getEdgeParser("paddingTop,paddingRight,paddingBottom,paddingLeft")}); + _registerComplexSpecialProp("clip", {defaultValue:"rect(0px,0px,0px,0px)", parser:function(t, e, p, cssp, pt, plugin){ + var b, cs, delim; + if (_ieVers < 9) { //IE8 and earlier don't report a "clip" value in the currentStyle - instead, the values are split apart into clipTop, clipRight, clipBottom, and clipLeft. Also, in IE7 and earlier, the values inside rect() are space-delimited, not comma-delimited. + cs = t.currentStyle; + delim = _ieVers < 8 ? " " : ","; + b = "rect(" + cs.clipTop + delim + cs.clipRight + delim + cs.clipBottom + delim + cs.clipLeft + ")"; + e = this.format(e).split(",").join(delim); + } else { + b = this.format(_getStyle(t, this.p, _cs, false, this.dflt)); + e = this.format(e); + } + return this.parseComplex(t.style, b, e, pt, plugin); + }}); + _registerComplexSpecialProp("textShadow", {defaultValue:"0px 0px 0px #999", color:true, multi:true}); + _registerComplexSpecialProp("autoRound,strictUnits", {parser:function(t, e, p, cssp, pt) {return pt;}}); //just so that we can ignore these properties (not tween them) + _registerComplexSpecialProp("border", {defaultValue:"0px solid #000", parser:function(t, e, p, cssp, pt, plugin) { + return this.parseComplex(t.style, this.format(_getStyle(t, "borderTopWidth", _cs, false, "0px") + " " + _getStyle(t, "borderTopStyle", _cs, false, "solid") + " " + _getStyle(t, "borderTopColor", _cs, false, "#000")), this.format(e), pt, plugin); + }, color:true, formatter:function(v) { + var a = v.split(" "); + return a[0] + " " + (a[1] || "solid") + " " + (v.match(_colorExp) || ["#000"])[0]; + }}); + _registerComplexSpecialProp("borderWidth", {parser:_getEdgeParser("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}); //Firefox doesn't pick up on borderWidth set in style sheets (only inline). + _registerComplexSpecialProp("float,cssFloat,styleFloat", {parser:function(t, e, p, cssp, pt, plugin) { + var s = t.style, + prop = ("cssFloat" in s) ? "cssFloat" : "styleFloat"; + return new CSSPropTween(s, prop, 0, 0, pt, -1, p, false, 0, s[prop], e); + }}); + + //opacity-related + var _setIEOpacityRatio = function(v) { + var t = this.t, //refers to the element's style property + filters = t.filter || _getStyle(this.data, "filter"), + val = (this.s + this.c * v) | 0, + skip; + if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. + if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { + t.removeAttribute("filter"); + skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. + } else { + t.filter = filters.replace(_alphaFilterExp, ""); + skip = true; + } + } + if (!skip) { + if (this.xn1) { + t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. + } + if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues + if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) + t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. + } + } else { + t.filter = filters.replace(_opacityExp, "opacity=" + val); + } + } + }; + _registerComplexSpecialProp("opacity,alpha,autoAlpha", {defaultValue:"1", parser:function(t, e, p, cssp, pt, plugin) { + var b = parseFloat(_getStyle(t, "opacity", _cs, false, "1")), + style = t.style, + isAutoAlpha = (p === "autoAlpha"); + if (typeof(e) === "string" && e.charAt(1) === "=") { + e = ((e.charAt(0) === "-") ? -1 : 1) * parseFloat(e.substr(2)) + b; + } + if (isAutoAlpha && b === 1 && _getStyle(t, "visibility", _cs) === "hidden" && e !== 0) { //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience) + b = 0; + } + if (_supportsOpacity) { + pt = new CSSPropTween(style, "opacity", b, e - b, pt); + } else { + pt = new CSSPropTween(style, "opacity", b * 100, (e - b) * 100, pt); + pt.xn1 = isAutoAlpha ? 1 : 0; //we need to record whether or not this is an autoAlpha so that in the setRatio(), we know to duplicate the setting of the alpha in order to work around a bug in IE7 and IE8 that prevents changes to "visibility" from taking effect if the filter is changed to a different alpha(opacity) at the same time. Setting it to the SAME value first, then the new value works around the IE7/8 bug. + style.zoom = 1; //helps correct an IE issue. + pt.type = 2; + pt.b = "alpha(opacity=" + pt.s + ")"; + pt.e = "alpha(opacity=" + (pt.s + pt.c) + ")"; + pt.data = t; + pt.plugin = plugin; + pt.setRatio = _setIEOpacityRatio; + } + if (isAutoAlpha) { //we have to create the "visibility" PropTween after the opacity one in the linked list so that they run in the order that works properly in IE8 and earlier + pt = new CSSPropTween(style, "visibility", 0, 0, pt, -1, null, false, 0, ((b !== 0) ? "inherit" : "hidden"), ((e === 0) ? "hidden" : "inherit")); + pt.xs0 = "inherit"; + cssp._overwriteProps.push(pt.n); + cssp._overwriteProps.push(p); + } + return pt; + }}); + + + var _removeProp = function(s, p) { + if (p) { + if (s.removeProperty) { + if (p.substr(0,2) === "ms") { //Microsoft browsers don't conform to the standard of capping the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example) + p = "M" + p.substr(1); + } + s.removeProperty(p.replace(_capsExp, "-$1").toLowerCase()); + } else { //note: old versions of IE use "removeAttribute()" instead of "removeProperty()" + s.removeAttribute(p); + } + } + }, + _setClassNameRatio = function(v) { + this.t._gsClassPT = this; + if (v === 1 || v === 0) { + this.t.setAttribute("class", (v === 0) ? this.b : this.e); + var mpt = this.data, //first MiniPropTween + s = this.t.style; + while (mpt) { + if (!mpt.v) { + _removeProp(s, mpt.p); + } else { + s[mpt.p] = mpt.v; + } + mpt = mpt._next; + } + if (v === 1 && this.t._gsClassPT === this) { + this.t._gsClassPT = null; + } + } else if (this.t.getAttribute("class") !== this.e) { + this.t.setAttribute("class", this.e); + } + }; + _registerComplexSpecialProp("className", {parser:function(t, e, p, cssp, pt, plugin, vars) { + var b = t.getAttribute("class") || "", //don't use t.className because it doesn't work consistently on SVG elements; getAttribute("class") and setAttribute("class", value") is more reliable. + cssText = t.style.cssText, + difData, bs, cnpt, cnptLookup, mpt; + pt = cssp._classNamePT = new CSSPropTween(t, p, 0, 0, pt, 2); + pt.setRatio = _setClassNameRatio; + pt.pr = -11; + _hasPriority = true; + pt.b = b; + bs = _getAllStyles(t, _cs); + //if there's a className tween already operating on the target, force it to its end so that the necessary inline styles are removed and the class name is applied before we determine the end state (we don't want inline styles interfering that were there just for class-specific values) + cnpt = t._gsClassPT; + if (cnpt) { + cnptLookup = {}; + mpt = cnpt.data; //first MiniPropTween which stores the inline styles - we need to force these so that the inline styles don't contaminate things. Otherwise, there's a small chance that a tween could start and the inline values match the destination values and they never get cleaned. + while (mpt) { + cnptLookup[mpt.p] = 1; + mpt = mpt._next; + } + cnpt.setRatio(1); + } + t._gsClassPT = pt; + pt.e = (e.charAt(1) !== "=") ? e : b.replace(new RegExp("\\s*\\b" + e.substr(2) + "\\b"), "") + ((e.charAt(0) === "+") ? " " + e.substr(2) : ""); + if (cssp._tween._duration) { //if it's a zero-duration tween, there's no need to tween anything or parse the data. In fact, if we switch classes temporarily (which we must do for proper parsing) and the class has a transition applied, it could cause a quick flash to the end state and back again initially in some browsers. + t.setAttribute("class", pt.e); + difData = _cssDif(t, bs, _getAllStyles(t), vars, cnptLookup); + t.setAttribute("class", b); + pt.data = difData.firstMPT; + t.style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity). + pt = pt.xfirst = cssp.parse(t, difData.difs, pt, plugin); //we record the CSSPropTween as the xfirst so that we can handle overwriting propertly (if "className" gets overwritten, we must kill all the properties associated with the className part of the tween, so we can loop through from xfirst to the pt itself) + } + return pt; + }}); + + + var _setClearPropsRatio = function(v) { + if (v === 1 || v === 0) if (this.data._totalTime === this.data._totalDuration && this.data.data !== "isFromStart") { //this.data refers to the tween. Only clear at the END of the tween (remember, from() tweens make the ratio go from 1 to 0, so we can't just check that and if the tween is the zero-duration one that's created internally to render the starting values in a from() tween, ignore that because otherwise, for example, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in). + var s = this.t.style, + transformParse = _specialProps.transform.parse, + a, p, i, clearTransform; + if (this.e === "all") { + s.cssText = ""; + clearTransform = true; + } else { + a = this.e.split(","); + i = a.length; + while (--i > -1) { + p = a[i]; + if (_specialProps[p]) { + if (_specialProps[p].parse === transformParse) { + clearTransform = true; + } else { + p = (p === "transformOrigin") ? _transformOriginProp : _specialProps[p].p; //ensures that special properties use the proper browser-specific property name, like "scaleX" might be "-webkit-transform" or "boxShadow" might be "-moz-box-shadow" + } + } + _removeProp(s, p); + } + } + if (clearTransform) { + _removeProp(s, _transformProp); + if (this.t._gsTransform) { + delete this.t._gsTransform; + } + } + + } + }; + _registerComplexSpecialProp("clearProps", {parser:function(t, e, p, cssp, pt) { + pt = new CSSPropTween(t, p, 0, 0, pt, 2); + pt.setRatio = _setClearPropsRatio; + pt.e = e; + pt.pr = -10; + pt.data = cssp._tween; + _hasPriority = true; + return pt; + }}); + + p = "bezier,throwProps,physicsProps,physics2D".split(","); + i = p.length; + while (i--) { + _registerPluginProp(p[i]); + } + + + + + + + + + p = CSSPlugin.prototype; + p._firstPT = null; + + //gets called when the tween renders for the first time. This kicks everything off, recording start/end values, etc. + p._onInitTween = function(target, vars, tween) { + if (!target.nodeType) { //css is only for dom elements + return false; + } + this._target = target; + this._tween = tween; + this._vars = vars; + _autoRound = vars.autoRound; + _hasPriority = false; + _suffixMap = vars.suffixMap || CSSPlugin.suffixMap; + _cs = _getComputedStyle(target, ""); + _overwriteProps = this._overwriteProps; + var style = target.style, + v, pt, pt2, first, last, next, zIndex, tpt, threeD; + if (_reqSafariFix) if (style.zIndex === "") { + v = _getStyle(target, "zIndex", _cs); + if (v === "auto" || v === "") { + //corrects a bug in [non-Android] Safari that prevents it from repainting elements in their new positions if they don't have a zIndex set. We also can't just apply this inside _parseTransform() because anything that's moved in any way (like using "left" or "top" instead of transforms like "x" and "y") can be affected, so it is best to ensure that anything that's tweening has a z-index. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. Plus zIndex is less memory-intensive. + this._addLazySet(style, "zIndex", 0); + } + } + + if (typeof(vars) === "string") { + first = style.cssText; + v = _getAllStyles(target, _cs); + style.cssText = first + ";" + vars; + v = _cssDif(target, v, _getAllStyles(target)).difs; + if (!_supportsOpacity && _opacityValExp.test(vars)) { + v.opacity = parseFloat( RegExp.$1 ); + } + vars = v; + style.cssText = first; + } + this._firstPT = pt = this.parse(target, vars, null); + + if (this._transformType) { + threeD = (this._transformType === 3); + if (!_transformProp) { + style.zoom = 1; //helps correct an IE issue. + } else if (_isSafari) { + _reqSafariFix = true; + //if zIndex isn't set, iOS Safari doesn't repaint things correctly sometimes (seemingly at random). + if (style.zIndex === "") { + zIndex = _getStyle(target, "zIndex", _cs); + if (zIndex === "auto" || zIndex === "") { + this._addLazySet(style, "zIndex", 0); + } + } + //Setting WebkitBackfaceVisibility corrects 3 bugs: + // 1) [non-Android] Safari skips rendering changes to "top" and "left" that are made on the same frame/render as a transform update. + // 2) iOS Safari sometimes neglects to repaint elements in their new positions. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. + // 3) Safari sometimes displayed odd artifacts when tweening the transform (or WebkitTransform) property, like ghosts of the edges of the element remained. Definitely a browser bug. + //Note: we allow the user to override the auto-setting by defining WebkitBackfaceVisibility in the vars of the tween. + if (_isSafariLT6) { + this._addLazySet(style, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (threeD ? "visible" : "hidden")); + } + } + pt2 = pt; + while (pt2 && pt2._next) { + pt2 = pt2._next; + } + tpt = new CSSPropTween(target, "transform", 0, 0, null, 2); + this._linkCSSP(tpt, null, pt2); + tpt.setRatio = (threeD && _supports3D) ? _set3DTransformRatio : _transformProp ? _set2DTransformRatio : _setIETransformRatio; + tpt.data = this._transform || _getTransform(target, _cs, true); + _overwriteProps.pop(); //we don't want to force the overwrite of all "transform" tweens of the target - we only care about individual transform properties like scaleX, rotation, etc. The CSSPropTween constructor automatically adds the property to _overwriteProps which is why we need to pop() here. + } + + if (_hasPriority) { + //reorders the linked list in order of pr (priority) + while (pt) { + next = pt._next; + pt2 = first; + while (pt2 && pt2.pr > pt.pr) { + pt2 = pt2._next; + } + if ((pt._prev = pt2 ? pt2._prev : last)) { + pt._prev._next = pt; + } else { + first = pt; + } + if ((pt._next = pt2)) { + pt2._prev = pt; + } else { + last = pt; + } + pt = next; + } + this._firstPT = first; + } + return true; + }; + + + p.parse = function(target, vars, pt, plugin) { + var style = target.style, + p, sp, bn, en, bs, es, bsfx, esfx, isStr, rel; + for (p in vars) { + es = vars[p]; //ending value string + sp = _specialProps[p]; //SpecialProp lookup. + if (sp) { + pt = sp.parse(target, es, p, this, pt, plugin, vars); + + } else { + bs = _getStyle(target, p, _cs) + ""; + isStr = (typeof(es) === "string"); + if (p === "color" || p === "fill" || p === "stroke" || p.indexOf("Color") !== -1 || (isStr && _rgbhslExp.test(es))) { //Opera uses background: to define color sometimes in addition to backgroundColor: + if (!isStr) { + es = _parseColor(es); + es = ((es.length > 3) ? "rgba(" : "rgb(") + es.join(",") + ")"; + } + pt = _parseComplex(style, p, bs, es, true, "transparent", pt, 0, plugin); + + } else if (isStr && (es.indexOf(" ") !== -1 || es.indexOf(",") !== -1)) { + pt = _parseComplex(style, p, bs, es, true, null, pt, 0, plugin); + + } else { + bn = parseFloat(bs); + bsfx = (bn || bn === 0) ? bs.substr((bn + "").length) : ""; //remember, bs could be non-numeric like "normal" for fontWeight, so we should default to a blank suffix in that case. + + if (bs === "" || bs === "auto") { + if (p === "width" || p === "height") { + bn = _getDimension(target, p, _cs); + bsfx = "px"; + } else if (p === "left" || p === "top") { + bn = _calculateOffset(target, p, _cs); + bsfx = "px"; + } else { + bn = (p !== "opacity") ? 0 : 1; + bsfx = ""; + } + } + + rel = (isStr && es.charAt(1) === "="); + if (rel) { + en = parseInt(es.charAt(0) + "1", 10); + es = es.substr(2); + en *= parseFloat(es); + esfx = es.replace(_suffixExp, ""); + } else { + en = parseFloat(es); + esfx = isStr ? es.substr((en + "").length) || "" : ""; + } + + if (esfx === "") { + esfx = (p in _suffixMap) ? _suffixMap[p] : bsfx; //populate the end suffix, prioritizing the map, then if none is found, use the beginning suffix. + } + + es = (en || en === 0) ? (rel ? en + bn : en) + esfx : vars[p]; //ensures that any += or -= prefixes are taken care of. Record the end value before normalizing the suffix because we always want to end the tween on exactly what they intended even if it doesn't match the beginning value's suffix. + + //if the beginning/ending suffixes don't match, normalize them... + if (bsfx !== esfx) if (esfx !== "") if (en || en === 0) if (bn) { //note: if the beginning value (bn) is 0, we don't need to convert units! + bn = _convertToPixels(target, p, bn, bsfx); + if (esfx === "%") { + bn /= _convertToPixels(target, p, 100, "%") / 100; + if (vars.strictUnits !== true) { //some browsers report only "px" values instead of allowing "%" with getComputedStyle(), so we assume that if we're tweening to a %, we should start there too unless strictUnits:true is defined. This approach is particularly useful for responsive designs that use from() tweens. + bs = bn + "%"; + } + + } else if (esfx === "em") { + bn /= _convertToPixels(target, p, 1, "em"); + + //otherwise convert to pixels. + } else if (esfx !== "px") { + en = _convertToPixels(target, p, en, esfx); + esfx = "px"; //we don't use bsfx after this, so we don't need to set it to px too. + } + if (rel) if (en || en === 0) { + es = (en + bn) + esfx; //the changes we made affect relative calculations, so adjust the end value here. + } + } + + if (rel) { + en += bn; + } + + if ((bn || bn === 0) && (en || en === 0)) { //faster than isNaN(). Also, previously we required en !== bn but that doesn't really gain much performance and it prevents _parseToProxy() from working properly if beginning and ending values match but need to get tweened by an external plugin anyway. For example, a bezier tween where the target starts at left:0 and has these points: [{left:50},{left:0}] wouldn't work properly because when parsing the last point, it'd match the first (current) one and a non-tweening CSSPropTween would be recorded when we actually need a normal tween (type:0) so that things get updated during the tween properly. + pt = new CSSPropTween(style, p, bn, en - bn, pt, 0, p, (_autoRound !== false && (esfx === "px" || p === "zIndex")), 0, bs, es); + pt.xs0 = esfx; + //DEBUG: _log("tween "+p+" from "+pt.b+" ("+bn+esfx+") to "+pt.e+" with suffix: "+pt.xs0); + } else if (style[p] === undefined || !es && (es + "" === "NaN" || es == null)) { + _log("invalid " + p + " tween value: " + vars[p]); + } else { + pt = new CSSPropTween(style, p, en || bn || 0, 0, pt, -1, p, false, 0, bs, es); + pt.xs0 = (es === "none" && (p === "display" || p.indexOf("Style") !== -1)) ? bs : es; //intermediate value should typically be set immediately (end value) except for "display" or things like borderTopStyle, borderBottomStyle, etc. which should use the beginning value during the tween. + //DEBUG: _log("non-tweening value "+p+": "+pt.xs0); + } + } + } + if (plugin) if (pt && !pt.plugin) { + pt.plugin = plugin; + } + } + return pt; + }; + + + //gets called every time the tween updates, passing the new ratio (typically a value between 0 and 1, but not always (for example, if an Elastic.easeOut is used, the value can jump above 1 mid-tween). It will always start and 0 and end at 1. + p.setRatio = function(v) { + var pt = this._firstPT, + min = 0.000001, + val, str, i; + + //at the end of the tween, we set the values to exactly what we received in order to make sure non-tweening values (like "position" or "float" or whatever) are set and so that if the beginning/ending suffixes (units) didn't match and we normalized to px, the value that the user passed in is used here. We check to see if the tween is at its beginning in case it's a from() tween in which case the ratio will actually go from 1 to 0 over the course of the tween (backwards). + if (v === 1 && (this._tween._time === this._tween._duration || this._tween._time === 0)) { + while (pt) { + if (pt.type !== 2) { + pt.t[pt.p] = pt.e; + } else { + pt.setRatio(v); + } + pt = pt._next; + } + + } else if (v || !(this._tween._time === this._tween._duration || this._tween._time === 0) || this._tween._rawPrevTime === -0.000001) { + while (pt) { + val = pt.c * v + pt.s; + if (pt.r) { + val = Math.round(val); + } else if (val < min) if (val > -min) { + val = 0; + } + if (!pt.type) { + pt.t[pt.p] = val + pt.xs0; + } else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)" + i = pt.l; + if (i === 2) { + pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2; + } else if (i === 3) { + pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3; + } else if (i === 4) { + pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4; + } else if (i === 5) { + pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4 + pt.xn4 + pt.xs5; + } else { + str = pt.xs0 + val + pt.xs1; + for (i = 1; i < pt.l; i++) { + str += pt["xn"+i] + pt["xs"+(i+1)]; + } + pt.t[pt.p] = str; + } + + } else if (pt.type === -1) { //non-tweening value + pt.t[pt.p] = pt.xs0; + + } else if (pt.setRatio) { //custom setRatio() for things like SpecialProps, external plugins, etc. + pt.setRatio(v); + } + pt = pt._next; + } + + //if the tween is reversed all the way back to the beginning, we need to restore the original values which may have different units (like % instead of px or em or whatever). + } else { + while (pt) { + if (pt.type !== 2) { + pt.t[pt.p] = pt.b; + } else { + pt.setRatio(v); + } + pt = pt._next; + } + } + }; + + /** + * @private + * Forces rendering of the target's transforms (rotation, scale, etc.) whenever the CSSPlugin's setRatio() is called. + * Basically, this tells the CSSPlugin to create a CSSPropTween (type 2) after instantiation that runs last in the linked + * list and calls the appropriate (3D or 2D) rendering function. We separate this into its own method so that we can call + * it from other plugins like BezierPlugin if, for example, it needs to apply an autoRotation and this CSSPlugin + * doesn't have any transform-related properties of its own. You can call this method as many times as you + * want and it won't create duplicate CSSPropTweens. + * + * @param {boolean} threeD if true, it should apply 3D tweens (otherwise, just 2D ones are fine and typically faster) + */ + p._enableTransforms = function(threeD) { + this._transformType = (threeD || this._transformType === 3) ? 3 : 2; + this._transform = this._transform || _getTransform(this._target, _cs, true); //ensures that the element has a _gsTransform property with the appropriate values. + }; + + var lazySet = function(v) { + this.t[this.p] = this.e; + this.data._linkCSSP(this, this._next, null, true); //we purposefully keep this._next even though it'd make sense to null it, but this is a performance optimization, as this happens during the while (pt) {} loop in setRatio() at the bottom of which it sets pt = pt._next, so if we null it, the linked list will be broken in that loop. + }; + /** @private Gives us a way to set a value on the first render (and only the first render). **/ + p._addLazySet = function(t, p, v) { + var pt = this._firstPT = new CSSPropTween(t, p, 0, 0, this._firstPT, 2); + pt.e = v; + pt.setRatio = lazySet; + pt.data = this; + }; + + /** @private **/ + p._linkCSSP = function(pt, next, prev, remove) { + if (pt) { + if (next) { + next._prev = pt; + } + if (pt._next) { + pt._next._prev = pt._prev; + } + if (pt._prev) { + pt._prev._next = pt._next; + } else if (this._firstPT === pt) { + this._firstPT = pt._next; + remove = true; //just to prevent resetting this._firstPT 5 lines down in case pt._next is null. (optimized for speed) + } + if (prev) { + prev._next = pt; + } else if (!remove && this._firstPT === null) { + this._firstPT = pt; + } + pt._next = next; + pt._prev = prev; + } + return pt; + }; + + //we need to make sure that if alpha or autoAlpha is killed, opacity is too. And autoAlpha affects the "visibility" property. + p._kill = function(lookup) { + var copy = lookup, + pt, p, xfirst; + if (lookup.autoAlpha || lookup.alpha) { + copy = {}; + for (p in lookup) { //copy the lookup so that we're not changing the original which may be passed elsewhere. + copy[p] = lookup[p]; + } + copy.opacity = 1; + if (copy.autoAlpha) { + copy.visibility = 1; + } + } + if (lookup.className && (pt = this._classNamePT)) { //for className tweens, we need to kill any associated CSSPropTweens too; a linked list starts at the className's "xfirst". + xfirst = pt.xfirst; + if (xfirst && xfirst._prev) { + this._linkCSSP(xfirst._prev, pt._next, xfirst._prev._prev); //break off the prev + } else if (xfirst === this._firstPT) { + this._firstPT = pt._next; + } + if (pt._next) { + this._linkCSSP(pt._next, pt._next._next, xfirst._prev); + } + this._classNamePT = null; + } + return TweenPlugin.prototype._kill.call(this, copy); + }; + + + + //used by cascadeTo() for gathering all the style properties of each child element into an array for comparison. + var _getChildStyles = function(e, props, targets) { + var children, i, child, type; + if (e.slice) { + i = e.length; + while (--i > -1) { + _getChildStyles(e[i], props, targets); + } + return; + } + children = e.childNodes; + i = children.length; + while (--i > -1) { + child = children[i]; + type = child.type; + if (child.style) { + props.push(_getAllStyles(child)); + if (targets) { + targets.push(child); + } + } + if ((type === 1 || type === 9 || type === 11) && child.childNodes.length) { + _getChildStyles(child, props, targets); + } + } + }; + + /** + * Typically only useful for className tweens that may affect child elements, this method creates a TweenLite + * and then compares the style properties of all the target's child elements at the tween's start and end, and + * if any are different, it also creates tweens for those and returns an array containing ALL of the resulting + * tweens (so that you can easily add() them to a TimelineLite, for example). The reason this functionality is + * wrapped into a separate static method of CSSPlugin instead of being integrated into all regular className tweens + * is because it creates entirely new tweens that may have completely different targets than the original tween, + * so if they were all lumped into the original tween instance, it would be inconsistent with the rest of the API + * and it would create other problems. For example: + * - If I create a tween of elementA, that tween instance may suddenly change its target to include 50 other elements (unintuitive if I specifically defined the target I wanted) + * - We can't just create new independent tweens because otherwise, what happens if the original/parent tween is reversed or pause or dropped into a TimelineLite for tight control? You'd expect that tween's behavior to affect all the others. + * - Analyzing every style property of every child before and after the tween is an expensive operation when there are many children, so this behavior shouldn't be imposed on all className tweens by default, especially since it's probably rare that this extra functionality is needed. + * + * @param {Object} target object to be tweened + * @param {number} Duration in seconds (or frames for frames-based tweens) + * @param {Object} Object containing the end values, like {className:"newClass", ease:Linear.easeNone} + * @return {Array} An array of TweenLite instances + */ + CSSPlugin.cascadeTo = function(target, duration, vars) { + var tween = TweenLite.to(target, duration, vars), + results = [tween], + b = [], + e = [], + targets = [], + _reservedProps = TweenLite._internals.reservedProps, + i, difs, p; + target = tween._targets || tween.target; + _getChildStyles(target, b, targets); + tween.render(duration, true); + _getChildStyles(target, e); + tween.render(0, true); + tween._enabled(true); + i = targets.length; + while (--i > -1) { + difs = _cssDif(targets[i], b[i], e[i]); + if (difs.firstMPT) { + difs = difs.difs; + for (p in vars) { + if (_reservedProps[p]) { + difs[p] = vars[p]; + } + } + results.push( TweenLite.to(targets[i], duration, difs) ); + } + } + return results; + }; + + TweenPlugin.activate([CSSPlugin]); + return CSSPlugin; + + }, true); + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * RoundPropsPlugin + * ---------------------------------------------------------------- + */ + (function() { + + var RoundPropsPlugin = window._gsDefine.plugin({ + propName: "roundProps", + priority: -1, + API: 2, + + //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. + init: function(target, value, tween) { + this._tween = tween; + return true; + } + + }), + p = RoundPropsPlugin.prototype; + + p._onInitAllProps = function() { + var tween = this._tween, + rp = (tween.vars.roundProps instanceof Array) ? tween.vars.roundProps : tween.vars.roundProps.split(","), + i = rp.length, + lookup = {}, + rpt = tween._propLookup.roundProps, + prop, pt, next; + while (--i > -1) { + lookup[rp[i]] = 1; + } + i = rp.length; + while (--i > -1) { + prop = rp[i]; + pt = tween._firstPT; + while (pt) { + next = pt._next; //record here, because it may get removed + if (pt.pg) { + pt.t._roundProps(lookup, true); + } else if (pt.n === prop) { + this._add(pt.t, prop, pt.s, pt.c); + //remove from linked list + if (next) { + next._prev = pt._prev; + } + if (pt._prev) { + pt._prev._next = next; + } else if (tween._firstPT === pt) { + tween._firstPT = next; + } + pt._next = pt._prev = null; + tween._propLookup[prop] = rpt; + } + pt = next; + } + } + return false; + }; + + p._add = function(target, p, s, c) { + this._addTween(target, p, s, s + c, p, true); + this._overwriteProps.push(p); + }; + + }()); + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * AttrPlugin + * ---------------------------------------------------------------- + */ + window._gsDefine.plugin({ + propName: "attr", + API: 2, + version: "0.3.2", + + //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. + init: function(target, value, tween) { + var p, start, end; + if (typeof(target.setAttribute) !== "function") { + return false; + } + this._target = target; + this._proxy = {}; + this._start = {}; // we record start and end values exactly as they are in case they're strings (not numbers) - we need to be able to revert to them cleanly. + this._end = {}; + for (p in value) { + this._start[p] = this._proxy[p] = start = target.getAttribute(p); + end = this._addTween(this._proxy, p, parseFloat(start), value[p], p); + this._end[p] = end ? end.s + end.c : value[p]; + this._overwriteProps.push(p); + } + return true; + }, + + //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) + set: function(ratio) { + this._super.setRatio.call(this, ratio); + var props = this._overwriteProps, + i = props.length, + lookup = (ratio === 1) ? this._end : ratio ? this._proxy : this._start, + p; + while (--i > -1) { + p = props[i]; + this._target.setAttribute(p, lookup[p] + ""); + } + } + + }); + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * DirectionalRotationPlugin + * ---------------------------------------------------------------- + */ + window._gsDefine.plugin({ + propName: "directionalRotation", + API: 2, + version: "0.2.0", + + //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. + init: function(target, value, tween) { + if (typeof(value) !== "object") { + value = {rotation:value}; + } + this.finals = {}; + var cap = (value.useRadians === true) ? Math.PI * 2 : 360, + min = 0.000001, + p, v, start, end, dif, split; + for (p in value) { + if (p !== "useRadians") { + split = (value[p] + "").split("_"); + v = split[0]; + start = parseFloat( (typeof(target[p]) !== "function") ? target[p] : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]() ); + end = this.finals[p] = (typeof(v) === "string" && v.charAt(1) === "=") ? start + parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : Number(v) || 0; + dif = end - start; + if (split.length) { + v = split.join("_"); + if (v.indexOf("short") !== -1) { + dif = dif % cap; + if (dif !== dif % (cap / 2)) { + dif = (dif < 0) ? dif + cap : dif - cap; + } + } + if (v.indexOf("_cw") !== -1 && dif < 0) { + dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; + } else if (v.indexOf("ccw") !== -1 && dif > 0) { + dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; + } + } + if (dif > min || dif < -min) { + this._addTween(target, p, start, start + dif, p); + this._overwriteProps.push(p); + } + } + } + return true; + }, + + //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) + set: function(ratio) { + var pt; + if (ratio !== 1) { + this._super.setRatio.call(this, ratio); + } else { + pt = this._firstPT; + while (pt) { + if (pt.f) { + pt.t[pt.p](this.finals[pt.p]); + } else { + pt.t[pt.p] = this.finals[pt.p]; + } + pt = pt._next; + } + } + } + + })._autoCSS = true; + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * EasePack + * ---------------------------------------------------------------- + */ + window._gsDefine("easing.Back", ["easing.Ease"], function(Ease) { + + var w = (window.GreenSockGlobals || window), + gs = w.com.greensock, + _2PI = Math.PI * 2, + _HALF_PI = Math.PI / 2, + _class = gs._class, + _create = function(n, f) { + var C = _class("easing." + n, function(){}, true), + p = C.prototype = new Ease(); + p.constructor = C; + p.getRatio = f; + return C; + }, + _easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist. + _wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) { + var C = _class("easing."+name, { + easeOut:new EaseOut(), + easeIn:new EaseIn(), + easeInOut:new EaseInOut() + }, true); + _easeReg(C, name); + return C; + }, + EasePoint = function(time, value, next) { + this.t = time; + this.v = value; + if (next) { + this.next = next; + next.prev = this; + this.c = next.v - value; + this.gap = next.t - time; + } + }, + + //Back + _createBack = function(n, f) { + var C = _class("easing." + n, function(overshoot) { + this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158; + this._p2 = this._p1 * 1.525; + }, true), + p = C.prototype = new Ease(); + p.constructor = C; + p.getRatio = f; + p.config = function(overshoot) { + return new C(overshoot); + }; + return C; + }, + + Back = _wrap("Back", + _createBack("BackOut", function(p) { + return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1); + }), + _createBack("BackIn", function(p) { + return p * p * ((this._p1 + 1) * p - this._p1); + }), + _createBack("BackInOut", function(p) { + return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2); + }) + ), + + + //SlowMo + SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) { + power = (power || power === 0) ? power : 0.7; + if (linearRatio == null) { + linearRatio = 0.7; + } else if (linearRatio > 1) { + linearRatio = 1; + } + this._p = (linearRatio !== 1) ? power : 0; + this._p1 = (1 - linearRatio) / 2; + this._p2 = linearRatio; + this._p3 = this._p1 + this._p2; + this._calcEnd = (yoyoMode === true); + }, true), + p = SlowMo.prototype = new Ease(), + SteppedEase, RoughEase, _createElastic; + + p.constructor = SlowMo; + p.getRatio = function(p) { + var r = p + (0.5 - p) * this._p; + if (p < this._p1) { + return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r); + } else if (p > this._p3) { + return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p); + } + return this._calcEnd ? 1 : r; + }; + SlowMo.ease = new SlowMo(0.7, 0.7); + + p.config = SlowMo.config = function(linearRatio, power, yoyoMode) { + return new SlowMo(linearRatio, power, yoyoMode); + }; + + + //SteppedEase + SteppedEase = _class("easing.SteppedEase", function(steps) { + steps = steps || 1; + this._p1 = 1 / steps; + this._p2 = steps + 1; + }, true); + p = SteppedEase.prototype = new Ease(); + p.constructor = SteppedEase; + p.getRatio = function(p) { + if (p < 0) { + p = 0; + } else if (p >= 1) { + p = 0.999999999; + } + return ((this._p2 * p) >> 0) * this._p1; + }; + p.config = SteppedEase.config = function(steps) { + return new SteppedEase(steps); + }; + + + //RoughEase + RoughEase = _class("easing.RoughEase", function(vars) { + vars = vars || {}; + var taper = vars.taper || "none", + a = [], + cnt = 0, + points = (vars.points || 20) | 0, + i = points, + randomize = (vars.randomize !== false), + clamp = (vars.clamp === true), + template = (vars.template instanceof Ease) ? vars.template : null, + strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4, + x, y, bump, invX, obj, pnt; + while (--i > -1) { + x = randomize ? Math.random() : (1 / points) * i; + y = template ? template.getRatio(x) : x; + if (taper === "none") { + bump = strength; + } else if (taper === "out") { + invX = 1 - x; + bump = invX * invX * strength; + } else if (taper === "in") { + bump = x * x * strength; + } else if (x < 0.5) { //"both" (start) + invX = x * 2; + bump = invX * invX * 0.5 * strength; + } else { //"both" (end) + invX = (1 - x) * 2; + bump = invX * invX * 0.5 * strength; + } + if (randomize) { + y += (Math.random() * bump) - (bump * 0.5); + } else if (i % 2) { + y += bump * 0.5; + } else { + y -= bump * 0.5; + } + if (clamp) { + if (y > 1) { + y = 1; + } else if (y < 0) { + y = 0; + } + } + a[cnt++] = {x:x, y:y}; + } + a.sort(function(a, b) { + return a.x - b.x; + }); + + pnt = new EasePoint(1, 1, null); + i = points; + while (--i > -1) { + obj = a[i]; + pnt = new EasePoint(obj.x, obj.y, pnt); + } + + this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next); + }, true); + p = RoughEase.prototype = new Ease(); + p.constructor = RoughEase; + p.getRatio = function(p) { + var pnt = this._prev; + if (p > pnt.t) { + while (pnt.next && p >= pnt.t) { + pnt = pnt.next; + } + pnt = pnt.prev; + } else { + while (pnt.prev && p <= pnt.t) { + pnt = pnt.prev; + } + } + this._prev = pnt; + return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c); + }; + p.config = function(vars) { + return new RoughEase(vars); + }; + RoughEase.ease = new RoughEase(); + + + //Bounce + _wrap("Bounce", + _create("BounceOut", function(p) { + if (p < 1 / 2.75) { + return 7.5625 * p * p; + } else if (p < 2 / 2.75) { + return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75; + } else if (p < 2.5 / 2.75) { + return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375; + } + return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375; + }), + _create("BounceIn", function(p) { + if ((p = 1 - p) < 1 / 2.75) { + return 1 - (7.5625 * p * p); + } else if (p < 2 / 2.75) { + return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75); + } else if (p < 2.5 / 2.75) { + return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375); + } + return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375); + }), + _create("BounceInOut", function(p) { + var invert = (p < 0.5); + if (invert) { + p = 1 - (p * 2); + } else { + p = (p * 2) - 1; + } + if (p < 1 / 2.75) { + p = 7.5625 * p * p; + } else if (p < 2 / 2.75) { + p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75; + } else if (p < 2.5 / 2.75) { + p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375; + } else { + p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375; + } + return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5; + }) + ); + + + //CIRC + _wrap("Circ", + _create("CircOut", function(p) { + return Math.sqrt(1 - (p = p - 1) * p); + }), + _create("CircIn", function(p) { + return -(Math.sqrt(1 - (p * p)) - 1); + }), + _create("CircInOut", function(p) { + return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1); + }) + ); + + + //Elastic + _createElastic = function(n, f, def) { + var C = _class("easing." + n, function(amplitude, period) { + this._p1 = amplitude || 1; + this._p2 = period || def; + this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0); + }, true), + p = C.prototype = new Ease(); + p.constructor = C; + p.getRatio = f; + p.config = function(amplitude, period) { + return new C(amplitude, period); + }; + return C; + }; + _wrap("Elastic", + _createElastic("ElasticOut", function(p) { + return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * _2PI / this._p2 ) + 1; + }, 0.3), + _createElastic("ElasticIn", function(p) { + return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2 )); + }, 0.3), + _createElastic("ElasticInOut", function(p) { + return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2 ) *0.5 + 1; + }, 0.45) + ); + + + //Expo + _wrap("Expo", + _create("ExpoOut", function(p) { + return 1 - Math.pow(2, -10 * p); + }), + _create("ExpoIn", function(p) { + return Math.pow(2, 10 * (p - 1)) - 0.001; + }), + _create("ExpoInOut", function(p) { + return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); + }) + ); + + + //Sine + _wrap("Sine", + _create("SineOut", function(p) { + return Math.sin(p * _HALF_PI); + }), + _create("SineIn", function(p) { + return -Math.cos(p * _HALF_PI) + 1; + }), + _create("SineInOut", function(p) { + return -0.5 * (Math.cos(Math.PI * p) - 1); + }) + ); + + _class("easing.EaseLookup", { + find:function(s) { + return Ease.map[s]; + } + }, true); + + //register the non-standard eases + _easeReg(w.SlowMo, "SlowMo", "ease,"); + _easeReg(RoughEase, "RoughEase", "ease,"); + _easeReg(SteppedEase, "SteppedEase", "ease,"); + + return Back; + + }, true); + + +}); + + + + + + + + + + + +/* + * ---------------------------------------------------------------- + * Base classes like TweenLite, SimpleTimeline, Ease, Ticker, etc. + * ---------------------------------------------------------------- + */ +(function(window) { + + "use strict"; + var _globals = window.GreenSockGlobals || window; + if (_globals.TweenLite) { + return; //in case the core set of classes is already loaded, don't instantiate twice. + } + var _namespace = function(ns) { + var a = ns.split("."), + p = _globals, i; + for (i = 0; i < a.length; i++) { + p[a[i]] = p = p[a[i]] || {}; + } + return p; + }, + gs = _namespace("com.greensock"), + _tinyNum = 0.0000000001, + _slice = [].slice, + _emptyFunc = function() {}, + _isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower) + var toString = Object.prototype.toString, + array = toString.call([]); + return function(obj) { + return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array)); + }; + }()), + a, i, p, _ticker, _tickerActive, + _defLookup = {}, + + /** + * @constructor + * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition. + * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is + * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin + * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally. + * + * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found, + * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere, + * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so + * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything + * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock + * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could + * sandbox the banner one like: + * + * + * + * + * + * + * + * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back". + * @param {!Array.} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"] + * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition. + * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object) + */ + Definition = function(ns, dependencies, func, global) { + this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses + _defLookup[ns] = this; + this.gsClass = null; + this.func = func; + var _classes = []; + this.check = function(init) { + var i = dependencies.length, + missing = i, + cur, a, n, cl; + while (--i > -1) { + if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) { + _classes[i] = cur.gsClass; + missing--; + } else if (init) { + cur.sc.push(this); + } + } + if (missing === 0 && func) { + a = ("com.greensock." + ns).split("."); + n = a.pop(); + cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes); + + //exports to multiple environments + if (global) { + _globals[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.) + if (typeof(define) === "function" && define.amd){ //AMD + define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").join("/"), [], function() { return cl; }); + } else if (typeof(module) !== "undefined" && module.exports){ //node + module.exports = cl; + } + } + for (i = 0; i < this.sc.length; i++) { + this.sc[i].check(); + } + } + }; + this.check(true); + }, + + //used to create Definition instances (which basically registers a class that has dependencies). + _gsDefine = window._gsDefine = function(ns, dependencies, func, global) { + return new Definition(ns, dependencies, func, global); + }, + + //a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class). + _class = gs._class = function(ns, func, global) { + func = func || function() {}; + _gsDefine(ns, [], function(){ return func; }, global); + return func; + }; + + _gsDefine.globals = _globals; + + + +/* + * ---------------------------------------------------------------- + * Ease + * ---------------------------------------------------------------- + */ + var _baseParams = [0, 0, 1, 1], + _blankArray = [], + Ease = _class("easing.Ease", function(func, extraParams, type, power) { + this._func = func; + this._type = type || 0; + this._power = power || 0; + this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams; + }, true), + _easeMap = Ease.map = {}, + _easeReg = Ease.register = function(ease, names, types, create) { + var na = names.split(","), + i = na.length, + ta = (types || "easeIn,easeOut,easeInOut").split(","), + e, name, j, type; + while (--i > -1) { + name = na[i]; + e = create ? _class("easing."+name, null, true) : gs.easing[name] || {}; + j = ta.length; + while (--j > -1) { + type = ta[j]; + _easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease(); + } + } + }; + + p = Ease.prototype; + p._calcEnd = false; + p.getRatio = function(p) { + if (this._func) { + this._params[0] = p; + return this._func.apply(null, this._params); + } + var t = this._type, + pw = this._power, + r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2; + if (pw === 1) { + r *= r; + } else if (pw === 2) { + r *= r * r; + } else if (pw === 3) { + r *= r * r * r; + } else if (pw === 4) { + r *= r * r * r * r; + } + return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2); + }; + + //create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut) + a = ["Linear","Quad","Cubic","Quart","Quint,Strong"]; + i = a.length; + while (--i > -1) { + p = a[i]+",Power"+i; + _easeReg(new Ease(null,null,1,i), p, "easeOut", true); + _easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : "")); + _easeReg(new Ease(null,null,3,i), p, "easeInOut"); + } + _easeMap.linear = gs.easing.Linear.easeIn; + _easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks + + +/* + * ---------------------------------------------------------------- + * EventDispatcher + * ---------------------------------------------------------------- + */ + var EventDispatcher = _class("events.EventDispatcher", function(target) { + this._listeners = {}; + this._eventTarget = target || this; + }); + p = EventDispatcher.prototype; + + p.addEventListener = function(type, callback, scope, useParam, priority) { + priority = priority || 0; + var list = this._listeners[type], + index = 0, + listener, i; + if (list == null) { + this._listeners[type] = list = []; + } + i = list.length; + while (--i > -1) { + listener = list[i]; + if (listener.c === callback && listener.s === scope) { + list.splice(i, 1); + } else if (index === 0 && listener.pr < priority) { + index = i + 1; + } + } + list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority}); + if (this === _ticker && !_tickerActive) { + _ticker.wake(); + } + }; + + p.removeEventListener = function(type, callback) { + var list = this._listeners[type], i; + if (list) { + i = list.length; + while (--i > -1) { + if (list[i].c === callback) { + list.splice(i, 1); + return; + } + } + } + }; + + p.dispatchEvent = function(type) { + var list = this._listeners[type], + i, t, listener; + if (list) { + i = list.length; + t = this._eventTarget; + while (--i > -1) { + listener = list[i]; + if (listener.up) { + listener.c.call(listener.s || t, {type:type, target:t}); + } else { + listener.c.call(listener.s || t); + } + } + } + }; + + +/* + * ---------------------------------------------------------------- + * Ticker + * ---------------------------------------------------------------- + */ + var _reqAnimFrame = window.requestAnimationFrame, + _cancelAnimFrame = window.cancelAnimationFrame, + _getTime = Date.now || function() {return new Date().getTime();}, + _lastUpdate = _getTime(); + + //now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill. + a = ["ms","moz","webkit","o"]; + i = a.length; + while (--i > -1 && !_reqAnimFrame) { + _reqAnimFrame = window[a[i] + "RequestAnimationFrame"]; + _cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"]; + } + + _class("Ticker", function(fps, useRAF) { + var _self = this, + _startTime = _getTime(), + _useRAF = (useRAF !== false && _reqAnimFrame), + _lagThreshold = 500, + _adjustedLag = 33, + _fps, _req, _id, _gap, _nextTime, + _tick = function(manual) { + var elapsed = _getTime() - _lastUpdate, + overlap, dispatch; + if (elapsed > _lagThreshold) { + _startTime += elapsed - _adjustedLag; + } + _lastUpdate += elapsed; + _self.time = (_lastUpdate - _startTime) / 1000; + overlap = _self.time - _nextTime; + if (!_fps || overlap > 0 || manual === true) { + _self.frame++; + _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap); + dispatch = true; + } + if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise. + _id = _req(_tick); + } + if (dispatch) { + _self.dispatchEvent("tick"); + } + }; + + EventDispatcher.call(_self); + _self.time = _self.frame = 0; + _self.tick = function() { + _tick(true); + }; + + _self.lagSmoothing = function(threshold, adjustedLag) { + _lagThreshold = threshold || (1 / _tinyNum); //zero should be interpreted as basically unlimited + _adjustedLag = Math.min(adjustedLag, _lagThreshold, 0); + }; + + _self.sleep = function() { + if (_id == null) { + return; + } + if (!_useRAF || !_cancelAnimFrame) { + clearTimeout(_id); + } else { + _cancelAnimFrame(_id); + } + _req = _emptyFunc; + _id = null; + if (_self === _ticker) { + _tickerActive = false; + } + }; + + _self.wake = function() { + if (_id !== null) { + _self.sleep(); + } else if (_self.frame > 10) { //don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout(). + _lastUpdate = _getTime() - _lagThreshold + 5; + } + _req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame; + if (_self === _ticker) { + _tickerActive = true; + } + _tick(2); + }; + + _self.fps = function(value) { + if (!arguments.length) { + return _fps; + } + _fps = value; + _gap = 1 / (_fps || 60); + _nextTime = this.time + _gap; + _self.wake(); + }; + + _self.useRAF = function(value) { + if (!arguments.length) { + return _useRAF; + } + _self.sleep(); + _useRAF = value; + _self.fps(_fps); + }; + _self.fps(fps); + + //a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition. + setTimeout(function() { + if (_useRAF && (!_id || _self.frame < 5)) { + _self.useRAF(false); + } + }, 1500); + }); + + p = gs.Ticker.prototype = new gs.events.EventDispatcher(); + p.constructor = gs.Ticker; + + +/* + * ---------------------------------------------------------------- + * Animation + * ---------------------------------------------------------------- + */ + var Animation = _class("core.Animation", function(duration, vars) { + this.vars = vars = vars || {}; + this._duration = this._totalDuration = duration || 0; + this._delay = Number(vars.delay) || 0; + this._timeScale = 1; + this._active = (vars.immediateRender === true); + this.data = vars.data; + this._reversed = (vars.reversed === true); + + if (!_rootTimeline) { + return; + } + if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly. + _ticker.wake(); + } + + var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline; + tl.add(this, tl._time); + + if (this.vars.paused) { + this.paused(true); + } + }); + + _ticker = Animation.ticker = new gs.Ticker(); + p = Animation.prototype; + p._dirty = p._gc = p._initted = p._paused = false; + p._totalTime = p._time = 0; + p._rawPrevTime = -1; + p._next = p._last = p._onUpdate = p._timeline = p.timeline = null; + p._paused = false; + + + //some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker. + var _checkTimeout = function() { + if (_tickerActive && _getTime() - _lastUpdate > 2000) { + _ticker.wake(); + } + setTimeout(_checkTimeout, 2000); + }; + _checkTimeout(); + + + p.play = function(from, suppressEvents) { + if (from != null) { + this.seek(from, suppressEvents); + } + return this.reversed(false).paused(false); + }; + + p.pause = function(atTime, suppressEvents) { + if (atTime != null) { + this.seek(atTime, suppressEvents); + } + return this.paused(true); + }; + + p.resume = function(from, suppressEvents) { + if (from != null) { + this.seek(from, suppressEvents); + } + return this.paused(false); + }; + + p.seek = function(time, suppressEvents) { + return this.totalTime(Number(time), suppressEvents !== false); + }; + + p.restart = function(includeDelay, suppressEvents) { + return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true); + }; + + p.reverse = function(from, suppressEvents) { + if (from != null) { + this.seek((from || this.totalDuration()), suppressEvents); + } + return this.reversed(true).paused(false); + }; + + p.render = function(time, suppressEvents, force) { + //stub - we override this method in subclasses. + }; + + p.invalidate = function() { + return this; + }; + + p.isActive = function() { + var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active. + startTime = this._startTime, + rawTime; + return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime()) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale)); + }; + + p._enabled = function (enabled, ignoreTimeline) { + if (!_tickerActive) { + _ticker.wake(); + } + this._gc = !enabled; + this._active = this.isActive(); + if (ignoreTimeline !== true) { + if (enabled && !this.timeline) { + this._timeline.add(this, this._startTime - this._delay); + } else if (!enabled && this.timeline) { + this._timeline._remove(this, true); + } + } + return false; + }; + + + p._kill = function(vars, target) { + return this._enabled(false, false); + }; + + p.kill = function(vars, target) { + this._kill(vars, target); + return this; + }; + + p._uncache = function(includeSelf) { + var tween = includeSelf ? this : this.timeline; + while (tween) { + tween._dirty = true; + tween = tween.timeline; + } + return this; + }; + + p._swapSelfInParams = function(params) { + var i = params.length, + copy = params.concat(); + while (--i > -1) { + if (params[i] === "{self}") { + copy[i] = this; + } + } + return copy; + }; + +//----Animation getters/setters -------------------------------------------------------- + + p.eventCallback = function(type, callback, params, scope) { + if ((type || "").substr(0,2) === "on") { + var v = this.vars; + if (arguments.length === 1) { + return v[type]; + } + if (callback == null) { + delete v[type]; + } else { + v[type] = callback; + v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params; + v[type + "Scope"] = scope; + } + if (type === "onUpdate") { + this._onUpdate = callback; + } + } + return this; + }; + + p.delay = function(value) { + if (!arguments.length) { + return this._delay; + } + if (this._timeline.smoothChildTiming) { + this.startTime( this._startTime + value - this._delay ); + } + this._delay = value; + return this; + }; + + p.duration = function(value) { + if (!arguments.length) { + this._dirty = false; + return this._duration; + } + this._duration = this._totalDuration = value; + this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration. + if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) { + this.totalTime(this._totalTime * (value / this._duration), true); + } + return this; + }; + + p.totalDuration = function(value) { + this._dirty = false; + return (!arguments.length) ? this._totalDuration : this.duration(value); + }; + + p.time = function(value, suppressEvents) { + if (!arguments.length) { + return this._time; + } + if (this._dirty) { + this.totalDuration(); + } + return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents); + }; + + p.totalTime = function(time, suppressEvents, uncapped) { + if (!_tickerActive) { + _ticker.wake(); + } + if (!arguments.length) { + return this._totalTime; + } + if (this._timeline) { + if (time < 0 && !uncapped) { + time += this.totalDuration(); + } + if (this._timeline.smoothChildTiming) { + if (this._dirty) { + this.totalDuration(); + } + var totalDuration = this._totalDuration, + tl = this._timeline; + if (time > totalDuration && !uncapped) { + time = totalDuration; + } + this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale); + if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here. + this._uncache(false); + } + //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed. + if (tl._timeline) { + while (tl._timeline) { + if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) { + tl.totalTime(tl._totalTime, true); + } + tl = tl._timeline; + } + } + } + if (this._gc) { + this._enabled(true, false); + } + if (this._totalTime !== time || this._duration === 0) { + this.render(time, suppressEvents, false); + if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render. + _lazyRender(); + } + } + } + return this; + }; + + p.progress = p.totalProgress = function(value, suppressEvents) { + return (!arguments.length) ? this._time / this.duration() : this.totalTime(this.duration() * value, suppressEvents); + }; + + p.startTime = function(value) { + if (!arguments.length) { + return this._startTime; + } + if (value !== this._startTime) { + this._startTime = value; + if (this.timeline) if (this.timeline._sortChildren) { + this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct. + } + } + return this; + }; + + p.timeScale = function(value) { + if (!arguments.length) { + return this._timeScale; + } + value = value || _tinyNum; //can't allow zero because it'll throw the math off + if (this._timeline && this._timeline.smoothChildTiming) { + var pauseTime = this._pauseTime, + t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime(); + this._startTime = t - ((t - this._startTime) * this._timeScale / value); + } + this._timeScale = value; + return this._uncache(false); + }; + + p.reversed = function(value) { + if (!arguments.length) { + return this._reversed; + } + if (value != this._reversed) { + this._reversed = value; + this.totalTime(((this._timeline && !this._timeline.smoothChildTiming) ? this.totalDuration() - this._totalTime : this._totalTime), true); + } + return this; + }; + + p.paused = function(value) { + if (!arguments.length) { + return this._paused; + } + if (value != this._paused) if (this._timeline) { + if (!_tickerActive && !value) { + _ticker.wake(); + } + var tl = this._timeline, + raw = tl.rawTime(), + elapsed = raw - this._pauseTime; + if (!value && tl.smoothChildTiming) { + this._startTime += elapsed; + this._uncache(false); + } + this._pauseTime = value ? raw : null; + this._paused = value; + this._active = this.isActive(); + if (!value && elapsed !== 0 && this._initted && this.duration()) { + this.render((tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale), true, true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render. + } + } + if (this._gc && !value) { + this._enabled(true, false); + } + return this; + }; + + +/* + * ---------------------------------------------------------------- + * SimpleTimeline + * ---------------------------------------------------------------- + */ + var SimpleTimeline = _class("core.SimpleTimeline", function(vars) { + Animation.call(this, 0, vars); + this.autoRemoveChildren = this.smoothChildTiming = true; + }); + + p = SimpleTimeline.prototype = new Animation(); + p.constructor = SimpleTimeline; + p.kill()._gc = false; + p._first = p._last = null; + p._sortChildren = false; + + p.add = p.insert = function(child, position, align, stagger) { + var prevTween, st; + child._startTime = Number(position || 0) + child._delay; + if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order). + child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale); + } + if (child.timeline) { + child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one. + } + child.timeline = child._timeline = this; + if (child._gc) { + child._enabled(true, true); + } + prevTween = this._last; + if (this._sortChildren) { + st = child._startTime; + while (prevTween && prevTween._startTime > st) { + prevTween = prevTween._prev; + } + } + if (prevTween) { + child._next = prevTween._next; + prevTween._next = child; + } else { + child._next = this._first; + this._first = child; + } + if (child._next) { + child._next._prev = child; + } else { + this._last = child; + } + child._prev = prevTween; + if (this._timeline) { + this._uncache(true); + } + return this; + }; + + p._remove = function(tween, skipDisable) { + if (tween.timeline === this) { + if (!skipDisable) { + tween._enabled(false, true); + } + tween.timeline = null; + + if (tween._prev) { + tween._prev._next = tween._next; + } else if (this._first === tween) { + this._first = tween._next; + } + if (tween._next) { + tween._next._prev = tween._prev; + } else if (this._last === tween) { + this._last = tween._prev; + } + + if (this._timeline) { + this._uncache(true); + } + } + return this; + }; + + p.render = function(time, suppressEvents, force) { + var tween = this._first, + next; + this._totalTime = this._time = this._rawPrevTime = time; + while (tween) { + next = tween._next; //record it here because the value could change after rendering... + if (tween._active || (time >= tween._startTime && !tween._paused)) { + if (!tween._reversed) { + tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); + } else { + tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); + } + } + tween = next; + } + }; + + p.rawTime = function() { + if (!_tickerActive) { + _ticker.wake(); + } + return this._totalTime; + }; + +/* + * ---------------------------------------------------------------- + * TweenLite + * ---------------------------------------------------------------- + */ + var TweenLite = _class("TweenLite", function(target, duration, vars) { + Animation.call(this, duration, vars); + this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method) + + if (target == null) { + throw "Cannot tween a null target."; + } + + this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target; + + var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))), + overwrite = this.vars.overwrite, + i, targ, targets; + + this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite]; + + if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") { + this._targets = targets = _slice.call(target, 0); + this._propLookup = []; + this._siblings = []; + for (i = 0; i < targets.length; i++) { + targ = targets[i]; + if (!targ) { + targets.splice(i--, 1); + continue; + } else if (typeof(targ) === "string") { + targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings + if (typeof(targ) === "string") { + targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case) + } + continue; + } else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that