Example usage for org.apache.commons.lang3.tuple ImmutableTriple getLeft

List of usage examples for org.apache.commons.lang3.tuple ImmutableTriple getLeft

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple ImmutableTriple getLeft.

Prototype

@Override
public L getLeft() 

Source Link

Usage

From source file:ddf.catalog.transformer.csv.common.CsvTransformerTest.java

private void buildMetacardDataMap() {
    for (ImmutableTriple entry : ATTRIBUTE_DATA) {
        String attributeName = (String) entry.getLeft();
        Serializable attributeValue = (Serializable) entry.getMiddle();
        AttributeType attributeType = (AttributeType) entry.getRight();
        Attribute attribute = new AttributeImpl(attributeName, attributeValue);
        metacardDataMap.put(attributeName, attribute);
        ATTRIBUTE_DESCRIPTOR_LIST.add(buildAttributeDescriptor(attributeName, attributeType));
    }/*from  w  w w . j a v  a  2  s. c  o m*/
}

From source file:io.lavagna.service.NotificationService.java

private void sendEmailToUser(User user, List<Event> events, MailConfig mailConfig)
        throws MustacheException, IOException {

    Set<Integer> userIds = new HashSet<>();
    userIds.add(user.getId());/*from   w  w w. ja va2s  .  co m*/
    Set<Integer> cardIds = new HashSet<>();
    Set<Integer> cardDataIds = new HashSet<>();
    Set<Integer> columnIds = new HashSet<>();

    for (Event e : events) {
        cardIds.add(e.getCardId());
        userIds.add(e.getUserId());

        addIfNotNull(userIds, e.getValueUser());
        addIfNotNull(cardIds, e.getValueCard());

        addIfNotNull(cardDataIds, e.getDataId());
        addIfNotNull(cardDataIds, e.getPreviousDataId());

        addIfNotNull(columnIds, e.getColumnId());
        addIfNotNull(columnIds, e.getPreviousColumnId());
    }

    final ImmutableTriple<String, String, String> subjectAndText = composeEmailForUser(
            new EventsContext(events, userRepository.findByIds(userIds), cardRepository.findAllByIds(cardIds),
                    cardDataRepository.findDataByIds(cardDataIds), boardColumnRepository.findByIds(columnIds)));

    mailConfig.send(user.getEmail(), StringUtils.substring("Lavagna: " + subjectAndText.getLeft(), 0, 78),
            subjectAndText.getMiddle(), subjectAndText.getRight());
}

From source file:com.telefonica.iot.cygnus.interceptors.NGSINameMappingsInterceptor.java

@Override
public Event intercept(Event event) {
    if (invalidConfiguration) {
        return event;
    } // if/*  w  ww .  j av  a 2s.  c  o  m*/

    LOGGER.debug("[nmi] Event intercepted, id=" + event.hashCode());

    // Casting to NGSIEvent
    NGSIEvent ngsiEvent = (NGSIEvent) event;

    // Get the original headers
    Map<String, String> headers = event.getHeaders();

    // Get some original header values
    String originalService = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
    String originalServicePath = headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH);

    // Create the mapped NotifyContextRequest
    ImmutableTriple<String, String, ContextElement> map = doMap(originalService, originalServicePath,
            ngsiEvent.getOriginalCE());
    LOGGER.debug("[nmi] Mapped ContextElement: " + map.getRight().toString());

    // Add the mapped ContextElement to the NGSIEvent
    ngsiEvent.setMappedCE(map.getRight());

    // Add the bytes version of the mapped ContextElement to event's body
    byte[] originalCEBytes = ngsiEvent.getBody();
    byte[] mappedCEBytes = map.getRight().toString().getBytes();
    byte[] newBody = new byte[originalCEBytes.length + mappedCEBytes.length];
    System.arraycopy(originalCEBytes, 0, newBody, 0, originalCEBytes.length);
    System.arraycopy(mappedCEBytes, 0, newBody, originalCEBytes.length, mappedCEBytes.length);
    ngsiEvent.setBody(newBody);
    LOGGER.debug("[nmi] New body: " + new String(newBody));

    // Add the mapped service and service path to the headers
    headers.put(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE, map.getLeft());
    LOGGER.debug("[nmi] Header added to NGSI event (" + NGSIConstants.FLUME_HEADER_MAPPED_SERVICE + ": "
            + map.getLeft() + ")");
    headers.put(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH, map.getMiddle());
    LOGGER.debug("[nmi] Header added to NGSI event (" + NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH + ": "
            + map.getMiddle() + ")");

    // Return the intercepted event
    LOGGER.debug("[nmi] Event put in the channel, id=" + ngsiEvent.hashCode());
    return ngsiEvent;
}

From source file:com.telefonica.iot.cygnus.interceptors.NGSINameMappingsInterceptorTest.java

/**
 * [NGSIGroupingInterceptor.doMapConfig4] -------- Original fields can be
 * omitted.//from w w w . j av  a 2s  .  c o m
 */
@Test
public void testDoMapConfig4() {
    System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
            + "-------- Original fields can be omitted");
    NGSINameMappingsInterceptor nameMappingsInterceptor = new NGSINameMappingsInterceptor(null, false);
    nameMappingsInterceptor.loadNameMappings(nameMappingsStrConfig4);
    ContextElement originalCE;
    ContextElement expectedCE;

    try {
        originalCE = NGSIUtilsForTests.createJsonContextElement(originalCEStrConfig2);
        expectedCE = NGSIUtilsForTests.createJsonContextElement(expectedCEStrConfig4);
    } catch (Exception e) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "- FAIL - There was some problem when parsing the ContextElements");
        throw new AssertionError(e.getMessage());
    } // try catch

    ImmutableTriple<String, String, ContextElement> map = nameMappingsInterceptor.doMap(originalServiceConfig,
            originalServicePathConfig, originalCE);
    ContextElement mappedCE = map.getRight();
    boolean equals = true;

    if (!mappedCE.getType().equals(expectedCE.getType())) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "-  ERROR  - The mapped type is not equal to the expected one");
        equals = false;
    } else if (!expectedServicePathConfig2.equals(map.getMiddle())) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "-  ERROR  - The mapped servicePath is not equal to the expected one");
        equals = false;
    } else if (!mappedCE.getId().equals(expectedCE.getId())) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "-  ERROR  - The mapped Id is not equal to the expected one");
        equals = false;
    } else if (!map.getLeft().equals(expectedServiceConfig4)) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "-  ERROR  - The Service tyepe is not equal to the expected one");
        equals = false;
    }

    try {
        assertTrue(equals);
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "-  OK  - The mapped NotifyContextRequest is equals to the expected one");
    } catch (AssertionError e) {
        System.out.println(getTestTraceHead("[NGSIGroupingInterceptor.doMapConfig4]")
                + "- FAIL - The mapped NotifyContextRequest is not equals to the expected one");
        throw e;
    } // try catch
}

From source file:org.coinspark.wallet.CSMessage.java

protected boolean mayBeRetrieve(Wallet wallet) {
    boolean updateRequired = false;

    messageRetrievalState = messageState;

    // aeskey must be set, if required, before nextRetrievalInterval() is invoke
    // In future, perhaps use expiring map, by time or by count of usage
    setAesKey(txidWalletPasswordMap.get(txID));

    if (nextRetrievalInterval() == 0) {
        try {/*from  w ww  . j  av  a  2s .c  om*/
            this.isRetrieving = true;
            CSEventBus.INSTANCE.postAsyncEvent(CSEventType.MESSAGE_RETRIEVAL_STARTED, txID);
            load();
            ImmutableTriple<Boolean, CSUtils.CSServerError, String> triplet = retrieve(wallet);
            this.isRetrieving = false;
            this.db.putServerError(txID, triplet.getMiddle());
            updateRequired |= triplet.getLeft(); // replaced --> updateRequired |= retrieve(wallet);
        } catch (KeyCrypterException e) {
            messageRetrievalState = CSMessageState.ENCRYPTED_KEY;
            this.isRetrieving = false;
        }
    }

    updateRequired |= (messageState != messageRetrievalState);

    if (updateRequired) {
        setState(messageRetrievalState);
    }

    // If set, clear the AESKey when done
    if (messageRetrievalState == CSMessageState.VALID) {
        setAesKey(null);
        txidWalletPasswordMap.remove(txID);
    }

    return updateRequired;
}

From source file:org.opendaylight.nemo.renderer.openflow.FlowUtils.java

/**
 * TODO/*from   w ww  .  j  av a  2  s. com*/
 *
 * @author Zhigang Ji
 * @param packetReceived TODO
 * @param ingress TODO
 */
public void handleArp(PacketReceived packetReceived, NodeConnectorRef ingress) {
    byte[] payload = packetReceived.getPayload();
    Ethernet ethernet = new Ethernet();

    try {
        ethernet.deserialize(payload, 0, NetUtils.NumBitsInAByte * payload.length);
    } catch (PacketException exception) {
        LOG.error("Failed to decode the received packet to ethernet packet.");

        return;
    }

    ARP arp = new ARP();

    try {
        arp.deserialize(ethernet.getRawPayload(), 0, NetUtils.NumBitsInAByte * ethernet.getRawPayload().length);
    } catch (PacketException exception) {
        LOG.error("Failed to decode the raw payload of ethernet packet to arp packet.");

        return;
    }

    ImmutableTriple<VirtualNetworkId, VirtualNodeId, VirtualPortId> mappingValueForExternalPhysicalPort = arpHandlerHelper
            .getMappingValueForExternalPhysicalPort(ingress);
    VirtualNetworkId virtualNetworkId = mappingValueForExternalPhysicalPort.getLeft();
    VirtualNodeId ingressVirtualNodeId = mappingValueForExternalPhysicalPort.getMiddle();
    VirtualPortId ingressVirtualPortId = mappingValueForExternalPhysicalPort.getRight();

    IpAddress srcIpAddress = convertByteArray4ToIpAddress(arp.getSenderProtocolAddress());
    IpAddress dstIpAddress = convertByteArray4ToIpAddress(arp.getTargetProtocolAddress());

    VirtualNetworkHelper virtualNetworkHelper = virtualNetworkHelpers.get(virtualNetworkId);
    VirtualNode ingressVirtualNode = virtualNetworkHelper.getVirtualNode(ingressVirtualNodeId);
    VirtualArp virtualArp;

    switch (ingressVirtualNode.getNodeType()) {
    case Vswitch:
        virtualArp = virtualNetworkHelper.getVirtualArp(srcIpAddress);

        if (null == virtualArp) {
            virtualArp = new VirtualArpBuilder().setIpAddress(srcIpAddress)
                    .setMacAddress(convertByteArray6ToMacAddress(arp.getSenderHardwareAddress()))
                    .setNodeId(ingressVirtualNodeId).setPortId(ingressVirtualPortId).build();
            virtualNetworkHelper.addVirtualArp(virtualArp);

            UserId userId = new UserId(virtualNetworkId.getValue());
            Map<VirtualNodeId, Map.Entry<VirtualPort, VirtualLink>> connectedVirtualRouters = virtualNetworkHelper
                    .getConnectedVirtualRouters(ingressVirtualNodeId);

            if (null != connectedVirtualRouters && !connectedVirtualRouters.isEmpty()) {
                VirtualLink virtualLink = virtualNetworkHelper.getVirtualLink(
                        connectedVirtualRouters.keySet().iterator().next(), ingressVirtualNodeId);
                VnPnMappingResult vnPnMappingResult = getVnPnMappingResult(
                        userVnPnMappings.get(userId).getVnPnMappingResult(),
                        new VirtualResourceEntityId(virtualLink.getLinkId().getValue()));
                PhysicalPathId physicalPathId = new PhysicalPathId(
                        vnPnMappingResult.getPhysicalResourceEntityId().getValue());
                PhysicalPath physicalPath = physicalNetworkHelper.getPhysicalPath(physicalPathId);

                configArpTableEntry(userId, virtualArp, physicalPath);
            }

            PhysicalNodeId ingressPhysicalNodeId = convertNodeConnectorRefToPhysicalNodeId(ingress);
            PhysicalPortId ingressPhysicalPortId = convertNodeConnectorRefToPhysicalPortId(ingress);

            configMacTableEntry(userId, virtualArp.getMacAddress(), ingressPhysicalNodeId,
                    ingressPhysicalPortId);

            Map<VirtualNodeId, Map.Entry<VirtualPort, VirtualLink>> connectedVirtualSwitches = virtualNetworkHelper
                    .getConnectedVirtualSwitches(ingressVirtualNodeId);

            if (null != connectedVirtualSwitches && !connectedVirtualSwitches.isEmpty()) {
                List<VnPnMappingResult> vnPnMappingResults = userVnPnMappings.get(userId)
                        .getVnPnMappingResult();
                VirtualLink virtualLink;
                VnPnMappingResult vnPnMappingResult;
                PhysicalPathId physicalPathId;
                PhysicalPath physicalPath;

                for (VirtualNodeId virtualNodeId : connectedVirtualSwitches.keySet()) {
                    virtualLink = virtualNetworkHelper.getVirtualLink(virtualNodeId, ingressVirtualNodeId);
                    vnPnMappingResult = getVnPnMappingResult(vnPnMappingResults,
                            new VirtualResourceEntityId(virtualLink.getLinkId().getValue()));
                    physicalPathId = new PhysicalPathId(
                            vnPnMappingResult.getPhysicalResourceEntityId().getValue());
                    physicalPath = physicalNetworkHelper.getPhysicalPath(physicalPathId);

                    configMacTableEntry(userId, virtualArp.getMacAddress(), physicalPath);
                }
            }
        }

        if (ARP.REQUEST == arp.getOpCode()) {
            IpAddress gatewayIpAddress = getGatewayIpAddress(virtualNetworkId, ingressVirtualNode);

            if (dstIpAddress.equals(gatewayIpAddress)) {
                MacAddress gatewayMacAddress = getGatewayMacAddress(virtualNetworkId, ingressVirtualNode);
                byte[] targetProtocolAddress = arp.getTargetProtocolAddress();

                arp.setTargetHardwareAddress(arp.getSenderHardwareAddress());
                arp.setTargetProtocolAddress(arp.getSenderProtocolAddress());
                arp.setSenderHardwareAddress(convertMacAddressToByteArray6(gatewayMacAddress));
                arp.setSenderProtocolAddress(targetProtocolAddress);
                arp.setOpCode(ARP.REPLY);

                ethernet.setSourceMACAddress(arp.getSenderHardwareAddress());
                ethernet.setDestinationMACAddress(arp.getTargetHardwareAddress());

                sendPacketOut(createArpPacket(ethernet, arp), ingress, ingress);
                break;
            }

            virtualArp = virtualNetworkHelper.getVirtualArp(dstIpAddress);

            if (null != virtualArp) {
                byte[] targetProtocolAddress = arp.getTargetProtocolAddress();

                arp.setTargetHardwareAddress(arp.getSenderHardwareAddress());
                arp.setTargetProtocolAddress(arp.getSenderProtocolAddress());
                arp.setSenderHardwareAddress(convertMacAddressToByteArray6(virtualArp.getMacAddress()));
                arp.setSenderProtocolAddress(targetProtocolAddress);
                arp.setOpCode(ARP.REPLY);

                ethernet.setSourceMACAddress(arp.getSenderHardwareAddress());
                ethernet.setDestinationMACAddress(arp.getTargetHardwareAddress());

                sendPacketOut(createArpPacket(ethernet, arp), ingress, ingress);
                break;
            }

            Map<VirtualNodeId, Map.Entry<VirtualPort, VirtualLink>> connectedVirtualSwitches = virtualNetworkHelper
                    .getConnectedVirtualSwitches(ingressVirtualNodeId);

            if (null != connectedVirtualSwitches && !connectedVirtualSwitches.isEmpty()) {
                UserId userId = new UserId(virtualNetworkId.getValue());
                UserVnPnMapping userVnPnMapping = userVnPnMappings.get(userId);
                List<VnPnMappingResult> vnPnMappingResults = userVnPnMapping.getVnPnMappingResult();
                VirtualPort layer2ExternalVirtualPort;
                VnPnMappingResult vnPnMappingResult;
                PhysicalNodeId physicalNodeId;
                PhysicalPortId physicalPortId;

                for (VirtualNodeId virtualNodeId : connectedVirtualSwitches.keySet()) {
                    layer2ExternalVirtualPort = virtualNetworkHelper
                            .getLayer2ExternalVirtualPort(virtualNodeId);

                    if (null != layer2ExternalVirtualPort) {
                        vnPnMappingResult = getVnPnMappingResult(vnPnMappingResults,
                                new VirtualResourceEntityId(layer2ExternalVirtualPort.getPortId().getValue()));
                        physicalNodeId = new PhysicalNodeId(
                                vnPnMappingResult.getParentPhysicalResourceEntityId().getValue());
                        physicalPortId = new PhysicalPortId(
                                vnPnMappingResult.getPhysicalResourceEntityId().getValue());

                        sendPacketOut(payload, ingress, createNodeConnectorRef(physicalNodeId, physicalPortId));
                    }
                }
            }
        } else {
            virtualArp = virtualNetworkHelper.getVirtualArp(dstIpAddress);

            if (null != virtualArp) {
                UserId userId = new UserId(virtualNetworkId.getValue());
                UserVnPnMapping userVnPnMapping = userVnPnMappings.get(userId);
                List<VnPnMappingResult> vnPnMappingResults = userVnPnMapping.getVnPnMappingResult();
                VnPnMappingResult vnPnMappingResult = getVnPnMappingResult(vnPnMappingResults,
                        new VirtualResourceEntityId(virtualArp.getPortId().getValue()));

                PhysicalNodeId physicalNodeId = new PhysicalNodeId(
                        vnPnMappingResult.getParentPhysicalResourceEntityId().getValue());
                PhysicalPortId physicalPortId = new PhysicalPortId(
                        vnPnMappingResult.getPhysicalResourceEntityId().getValue());

                sendPacketOut(payload, ingress, createNodeConnectorRef(physicalNodeId, physicalPortId));
            }
        }
        break;

    case Vrouter:
        VirtualPort ingressVirtualPort = virtualNetworkHelper.getVirtualPort(ingressVirtualNodeId,
                ingressVirtualPortId);

        if (virtualNetworkHelper.isLayer2ExternalVirtualPort(ingressVirtualPort)) {
            virtualArp = virtualNetworkHelper.getVirtualArp(srcIpAddress);

            if (null == virtualArp) {
                virtualArp = new VirtualArpBuilder().setIpAddress(srcIpAddress)
                        .setMacAddress(convertByteArray6ToMacAddress(arp.getSenderHardwareAddress()))
                        .setNodeId(ingressVirtualNodeId).setPortId(ingressVirtualPortId).build();
                virtualNetworkHelper.addVirtualArp(virtualArp);

                UserId userId = new UserId(virtualNetworkId.getValue());
                PhysicalNodeId ingressPhysicalNodeId = convertNodeConnectorRefToPhysicalNodeId(ingress);
                PhysicalPortId ingressPhysicalPortId = convertNodeConnectorRefToPhysicalPortId(ingress);

                configArpTableEntry(userId, virtualArp, ingressPhysicalNodeId, ingressPhysicalPortId);
            }

            if (ARP.REQUEST == arp.getOpCode()) {
                IpAddress gatewayIpAddress = getGatewayIpAddress(virtualNetworkId, ingressVirtualNode);

                if (dstIpAddress.equals(gatewayIpAddress)) {
                    MacAddress gatewayMacAddress = getGatewayMacAddress(virtualNetworkId, ingressVirtualNode);
                    byte[] targetProtocolAddress = arp.getTargetProtocolAddress();

                    arp.setTargetHardwareAddress(arp.getSenderHardwareAddress());
                    arp.setTargetProtocolAddress(arp.getSenderProtocolAddress());
                    arp.setSenderHardwareAddress(convertMacAddressToByteArray6(gatewayMacAddress));
                    arp.setSenderProtocolAddress(targetProtocolAddress);
                    arp.setOpCode(ARP.REPLY);

                    ethernet.setSourceMACAddress(arp.getSenderHardwareAddress());
                    ethernet.setDestinationMACAddress(arp.getTargetHardwareAddress());

                    sendPacketOut(createArpPacket(ethernet, arp), ingress, ingress);
                }
            }
        }
        break;

    default:
        break;
    }

    return;
}

From source file:org.openecomp.sdc.be.dao.titan.TitanGenericDao.java

public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteria(NodeTypeEnum type,
        Class<T> clazz, List<ImmutableTriple<QueryType, String, Object>> props) {
    Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
    if (graph.isLeft()) {
        try {/*from  w  ww  . ja  va2 s . com*/
            TitanGraph tGraph = graph.left().value();

            TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
            query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
            for (ImmutableTriple<QueryType, String, Object> prop : props) {
                if (QueryType.HAS.equals(prop.getLeft())) {
                    query = query.has(prop.getMiddle(), prop.getRight());
                } else {
                    query = query.hasNot(prop.getMiddle(), prop.getRight());
                }
            }
            Iterable<TitanVertex> vertices = query.vertices();
            if (vertices == null) {
                return Either.right(TitanOperationStatus.NOT_FOUND);
            }

            Iterator<TitanVertex> iterator = vertices.iterator();
            List<T> result = new ArrayList<T>();

            while (iterator.hasNext()) {
                Vertex vertex = iterator.next();

                Map<String, Object> newProp = getProperties(vertex);

                T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node,
                        newProp, clazz);
                result.add(element);
            }
            if (result.size() == 0) {
                return Either.right(TitanOperationStatus.NOT_FOUND);
            }

            return Either.left(result);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed  get by  criteria for type = {}", type, e);
            }
            return Either.right(TitanGraphClient.handleTitanException(e));
        }

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed  get by  criteria for type ={}  error : {}", type, graph.right().value());
        }
        return Either.right(graph.right().value());
    }
}

From source file:org.openecomp.sdc.be.model.operations.impl.ComponentOperation.java

@Deprecated
public Either<List<Component>, ActionStatus> getComponentsFromCacheForCatalog(Set<String> components,
        ComponentTypeEnum componentType) {

    Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache
            .getComponentsForCatalog(components, componentType);
    if (componentsForCatalog.isLeft()) {
        ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = componentsForCatalog
                .left().value();/*from   w ww  .j a va2  s  .  com*/
        List<Component> foundComponents = immutableTriple.getLeft();

        if (foundComponents != null) {
            // foundComponents.forEach(p -> result.add((Resource)p));
            log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(),
                    foundComponents.size());

        }
        List<Component> foundDirtyComponents = immutableTriple.getMiddle();
        Set<String> nonCachedComponents = immutableTriple.getRight();
        int numberDirtyResources = foundDirtyComponents == null ? 0 : foundDirtyComponents.size();
        int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size();
        log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(),
                numberDirtyResources + numberNonCached);
        return Either.left(foundComponents);
    }

    return Either.right(componentsForCatalog.right().value());
}

From source file:org.openecomp.sdc.ci.tests.api.ComponentBaseTest.java

private void cleanComponents() throws Exception {

    // Components to delete
    List<String> vfResourcesToDelete = new ArrayList<String>();
    List<String> nonVfResourcesToDelete = new ArrayList<String>();
    List<String> servicesToDelete = new ArrayList<String>();
    List<String> productsToDelete = new ArrayList<String>();

    // Categories to delete
    List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
    List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
    List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
    List<String> productCategoriesToDelete = new ArrayList<>();
    List<String> resourceCategoriesToDelete = new ArrayList<String>();
    List<String> serviceCategoriesToDelete = new ArrayList<String>();

    List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
    List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
    List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
    TitanGraphQuery<? extends TitanGraphQuery> query = titanGraph.query();
    query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName());
    Iterable<TitanVertex> vertices = query.vertices();
    //      Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex vertex = iter.next();
            Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
            // if (!isAbstract) {
            String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
            String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());

            if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name))
                    || (version != null && !version.equals("1.0"))) {
                String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
                // if (name.startsWith("ci")) {
                if (resourceType.equals(ResourceTypeEnum.VF.name())) {
                    vfResourcesToDelete.add(id);
                } else {
                    nonVfResourcesToDelete.add(id);
                }/*  w w w .ja  v a 2 s  .  c  o  m*/
                // }
            } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name))
                    || (version != null && version.equals("1.0"))) {
                if ((boolean) vertex
                        .value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
                    vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
                }
            }
            // }
        }
    }
    vertices = titanGraph.query()
            .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex vertex = iter.next();
            String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
            String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
            // if (name.startsWith("ci")){
            servicesToDelete.add(id);
            // }
        }
    }

    vertices = titanGraph.query()
            .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex vertex = iter.next();
            String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
            String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
            //if (name.startsWith("ci")) {
            productsToDelete.add(id);
            //}
        }
    }

    // Getting categories

    vertices = titanGraph.query()
            .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName())
            .vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex category = iter.next();
            String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
            if (!resourceCategoriesNotToDelete.contains(name)) {
                String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                resourceCategoriesToDelete.add(catId);
                Iterator<Vertex> subs = category.vertices(Direction.OUT,
                        GraphEdgeLabels.SUB_CATEGORY.getProperty());
                while (subs.hasNext()) {
                    Vertex sub = subs.next();
                    String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                    resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
                }
            }
        }
    }

    vertices = titanGraph.query()
            .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName())
            .vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex category = iter.next();
            String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
            if (!serviceCategoriesNotToDelete.contains(name)) {
                String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                serviceCategoriesToDelete.add(id);
            }
        }
    }

    vertices = titanGraph.query()
            .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName())
            .vertices();
    if (vertices != null) {
        Iterator<TitanVertex> iter = vertices.iterator();
        while (iter.hasNext()) {
            Vertex category = iter.next();
            String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
            productCategoriesToDelete.add(catId);
            Iterator<Vertex> subs = category.vertices(Direction.OUT,
                    GraphEdgeLabels.SUB_CATEGORY.getProperty());
            while (subs.hasNext()) {
                Vertex sub = subs.next();
                String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
                Iterator<Vertex> groupings = sub.vertices(Direction.OUT,
                        GraphEdgeLabels.GROUPING.getProperty());
                while (groupings.hasNext()) {
                    Vertex grouping = groupings.next();
                    String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                    productGroupingsToDelete
                            .add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
                }
            }

        }
    }

    titanGraph.tx().commit();

    String adminId = UserRoleEnum.ADMIN.getUserId();
    String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();

    // Component delete
    for (String id : productsToDelete) {
        RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);

    }
    for (String id : servicesToDelete) {
        RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);

    }
    for (String id : vfResourcesToDelete) {
        RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);

    }

    for (String id : nonVfResourcesToDelete) {
        RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);

    }

    // Categories delete - product
    String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
    for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
        CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(),
                productStrategistId, componentType);
    }
    for (ImmutablePair<String, String> pair : productSubsToDelete) {
        CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId,
                componentType);
    }
    for (String id : productCategoriesToDelete) {
        CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
    }

    // Categories delete - resource
    componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
    for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
        CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
    }
    for (String id : resourceCategoriesToDelete) {
        CategoryRestUtils.deleteCategory(id, adminId, componentType);
    }
    // Categories delete - resource
    componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
    for (String id : serviceCategoriesToDelete) {
        CategoryRestUtils.deleteCategory(id, adminId, componentType);
    }

}