Example usage for java.util Map replace

List of usage examples for java.util Map replace

Introduction

In this page you can find the example usage for java.util Map replace.

Prototype

default V replace(K key, V value) 

Source Link

Document

Replaces the entry for the specified key only if it is currently mapped to some value.

Usage

From source file:org.esa.nest.gpf.SliceAssemblyOp.java

private void computeTargetWidthAndHeight() {

    // In GRD products, all the bands will have the same width and height, so the width and height of the
    // product are equal to the width and height of the bands. E.g a GRD product will have these bands:
    // - Amplitude_VH
    // - Amplitude_VV
    // They will have the same width and height.
    ///*from  w  ww.ja v  a 2  s  . com*/
    // In SLC products, each band belongs to a swath and bands belonging to the same swath will have the
    // same width and height. E.g. a SLC product will have these bands:
    //
    // IW1: w x h = 22553 x 14850
    // - i_IW1_VH
    // - q_IW1_VH
    // - i_IW1_VV
    // - q_IW1_VV
    //
    // IW2: w x h = 26326 x 15363
    // - i_IW2_VH
    // - q_IW2_VH
    // - i_IW2_VV
    // - q_IW2_VV
    //
    // IW3: w x h = 25321 x 15534
    // - i_IW3_VH
    // - q_IW3_VH
    // - i_IW3_VV
    // - q_IW3_VV
    //
    // We assume for such a SLC slice product, the scene raster width and height will be the maximum
    // among the swaths, so product scene raster width = 26326 and product scene raster height = 15534.
    //
    // Say 1st slice:
    //  IW1: w x h = 22553 x 14850
    //  IW2: w x h = 26326 x 15363
    //  IW3: w x h = 25321 x 15534
    //  product width = 26326 and height = 15534
    //
    // 2nd slice:
    //  IW1: w x h = 22571 x 14850
    //  IW2: w x h = 26351 x 15363
    //  IW3: w x h = 25350 x 15543
    // product width = 26351 and height = 15543
    //
    // Assemble the 2 slices:
    //  IW1: w x h = 22571 x 29700
    //  IW2: w x h = 26351 x 30726
    //  IW3: w x h = 25350 x 31077
    // product width = 26351 and height = 31077

    final String productType = sliceProducts[0].getProductType();

    if (productType.equals("GRD")) {

        for (Product srcProduct : sliceProducts) {

            if (targetWidth < srcProduct.getSceneRasterWidth())
                targetWidth = srcProduct.getSceneRasterWidth();
            targetHeight += srcProduct.getSceneRasterHeight();

            final Map<String, int[]> tmp = new HashMap<>();
            tmp.put("", new int[] { srcProduct.getSceneRasterHeight(), srcProduct.getSceneRasterWidth() });
            sliceSwathImageDimMap.put(srcProduct, tmp);
        }

        swathAssembledImageDimMap.put("", new int[] { targetHeight, targetWidth });

    } else {

        final ArrayList<String> swaths = getSwaths(sliceProducts[0]);
        final Map<String, Integer> swathHeight = new HashMap<>();
        final Map<String, Integer> swathWidth = new HashMap<>();

        for (String swath : swaths) {
            swathHeight.put(swath, 0);
            swathWidth.put(swath, 0);
        }

        for (Product srcProduct : sliceProducts) {

            for (String swath : swaths) {

                final int[] dim = new int[2];
                getSwathDim(srcProduct, swath, dim);

                if (swathWidth.get(swath) < dim[1]) {
                    swathWidth.replace(swath, dim[1]);
                }
                swathHeight.replace(swath, swathHeight.get(swath) + dim[0]);

                if (sliceSwathImageDimMap.containsKey(srcProduct)) {
                    final Map<String, int[]> tmp = sliceSwathImageDimMap.get(srcProduct);
                    tmp.put(swath, dim);
                } else {
                    final Map<String, int[]> tmp = new HashMap<>();
                    tmp.put(swath, dim);
                    sliceSwathImageDimMap.put(srcProduct, tmp);
                }
            }
        }

        for (String swath : swaths) {
            swathAssembledImageDimMap.put(swath, new int[] { swathHeight.get(swath), swathWidth.get(swath) });
            if (targetWidth < swathWidth.get(swath))
                targetWidth = swathWidth.get(swath);
            if (targetHeight < swathHeight.get(swath))
                targetHeight = swathHeight.get(swath);
        }
    }
}

From source file:org.esa.snap.classification.gpf.maximumlikelihood.MaximumLikelihood.java

@Override
public Map<Object, Double> classDistribution(Instance instance) {

    // i = class, N = number of features
    // Natural log of likelihood is expressed as...
    // g(i) = - 0.5*[ transpose(x - m_i) * invCov_i * (x - m_i)] - (N/2)*ln(2*PI) - (0.5 * ln(abs(det_i)))
    // So likelihood is
    // exp(g(i)) = exp{ - 0.5*[ transpose(x - m_i) * invCov_i * (x - m_i)] } * { 1/[(2 PI)^(N/2)] } * { 1/sqrt(det_i) }

    final Map<Object, Double> dis = new HashMap<>();
    double sum = 0.0;
    for (Object o : meanVector.keySet()) {

        if (!invCov.containsKey(o) || !determinant.containsKey(o)) {
            continue;
        }/*  www.ja  v  a 2  s .c o  m*/

        double[] tmp = new double[instance.noAttributes()];
        for (int i = 0; i < instance.noAttributes(); i++) {
            tmp[i] = instance.value(i) - meanVector.get(o)[i];
        }

        // x - m_i
        Matrix diffMat = new Matrix(tmp, tmp.length);

        //SystemUtils.LOG.info("diffMat rol x col = " + diffMat.getRowDimension() + " x " + diffMat.getColumnDimension());
        //SystemUtils.LOG.info("invCov rol x col = " + invCov.get(o).getRowDimension() + " x " + invCov.get(o).getColumnDimension());

        // transpose(x - m_i) * invCov
        Matrix tmpMat = diffMat.transpose().times(invCov.get(o));

        //SystemUtils.LOG.info("transpose(x - m_i) * invCov rol  x col = " + tmpMat.getRowDimension() + " x " + tmpMat.getColumnDimension());

        // transpose(x - m_i) * invCov] * (x - m_i)
        Matrix m1 = tmpMat.times(diffMat);

        if (m1.getColumnDimension() != 1 || m1.getRowDimension() != 1) {
            SystemUtils.LOG
                    .info("ERROR: #col = " + m1.getColumnDimension() + " #row = " + m1.getRowDimension());
        }

        // This is the likelihood
        double expg = Math.exp(-0.5 * m1.get(0, 0)) * constantTerm
                * (1.0 / Math.sqrt(Math.abs(determinant.get(o))));
        sum += expg;
        dis.put(o, expg);
    }

    // Normalize...
    for (Object o : dis.keySet()) {
        final double val = dis.get(o);
        dis.replace(o, val / sum);
        //SystemUtils.LOG.info("DEBUG: o = " + o + ": " + dis.get(o));
    }

    return dis;
}

From source file:com.evolveum.polygon.test.scim.StandardScimTestUtils.java

public static Map<String, String> processResult(List<ConnectorObject> results, String resourceName,
        String testType, Uid userTestUid, Integer testNumber) {
    Map<String, String> evaluationResult = new HashMap<String, String>();

    Set<Attribute> createAttributeSet = new HashSet<Attribute>();

    String notPressentAttribute = "";

    String createAttributeName;//from   w w w.j  a  va2s  . c om

    if (USERS.equals(resourceName)) {
        if (CREATE.equals(testType)) {
            createAttributeSet = userCreateBuilder(testNumber);
        } else if (UPDATESINGLE.equals(testType)) {
            createAttributeSet = userSingleValUpdateBuilder(testNumber);
        } else if (UPDATEMULTI.equals(testType)) {
            createAttributeSet = userMultiValUpdateBuilder(testNumber);
        } else if ("update-disabled".equals(testType)) {
            createAttributeSet = userDisableUpdate();
        } else if ("update-enabled".equals(testType)) {
            createAttributeSet = userEnableUpdate();
        }

        notPressentAttribute = USERNAME;

    } else if (GROUPS.equals(resourceName)) {
        if (CREATE.equals(testType)) {
            createAttributeSet = groupCreateBuilder(testNumber);
        } else if (UPDATESINGLE.equals(testType)) {
            createAttributeSet = groupSingleValUpdateBuilder(testNumber);
        } else if (UPDATEMULTI.equals(testType)) {
            createAttributeSet = groupMultiValUpdateBuilder(testNumber, userTestUid);
        }
        notPressentAttribute = DISPLAYNAME;
    }

    for (Attribute createAttribute : createAttributeSet) {
        createAttributeName = createAttribute.getName();
        if (!notPressentAttribute.equals(createAttributeName)) {
            evaluationResult.put(createAttributeName, "#AttributeNameNotFound#");
        }
    }
    for (ConnectorObject result : results) {
        Set<Attribute> returnedAttributeSet = new HashSet<Attribute>();

        returnedAttributeSet = result.getAttributes();

        for (Attribute attribute : returnedAttributeSet) {

            String returnedAttributeName = attribute.getName();
            LOGGER.info("The attribute Name: {0}", returnedAttributeName);

            for (Attribute createAttribute : createAttributeSet) {
                createAttributeName = createAttribute.getName();

                if (createAttributeName.equals(returnedAttributeName)) {

                    if (createAttribute.getValue().equals(attribute.getValue())) {

                        evaluationResult.replace(createAttributeName, returnedAttributeName);
                        break;

                    } else {

                        evaluationResult.replace(createAttributeName,
                                "The returned value does not correspond to the value which vas set");
                    }
                }

            }
        }

    }

    return evaluationResult;
}

From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImplIT.java

@Test
public void testAddApiAndResourceSpecificEndpointToApi() throws APIMgtDAOException {
    Endpoint apiSpecificEndpoint = new Endpoint.Builder(SampleTestObjectCreator.createMockEndpoint())
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint urlSpecificEndpoint = new Endpoint.Builder(SampleTestObjectCreator.createMockEndpoint())
            .id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT)
            .name("URI1").build();
    Endpoint endpointToInsert = SampleTestObjectCreator.createAlternativeEndpoint();
    Endpoint globalEndpoint = new Endpoint.Builder().applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT)
            .id(endpointToInsert.getId()).build();
    Map<String, Endpoint> apiEndpointMap = new HashMap();

    apiEndpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, apiSpecificEndpoint);
    apiEndpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, globalEndpoint);
    Map<String, Endpoint> uriTemplateEndpointMap = new HashMap();
    uriTemplateEndpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, urlSpecificEndpoint);
    Map<String, UriTemplate> uriTemplateMap = SampleTestObjectCreator.getMockUriTemplates();
    uriTemplateMap.forEach((k, v) -> {
        UriTemplate uriTemplate = new UriTemplate.UriTemplateBuilder(v).endpoint(uriTemplateEndpointMap)
                .build();//from w  ww  .j a v a 2  s . com
        uriTemplateMap.replace(k, uriTemplate);
    });
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    API api = SampleTestObjectCreator.createDefaultAPI().apiDefinition(SampleTestObjectCreator.apiDefinition)
            .endpoint(apiEndpointMap).uriTemplates(uriTemplateMap).build();
    apiDAO.addEndpoint(endpointToInsert);
    apiDAO.addAPI(api);
    Map<String, Endpoint> retrievedApiEndpoint = apiDAO.getAPI(api.getId()).getEndpoint();
    Assert.assertTrue(apiDAO.isEndpointAssociated(globalEndpoint.getId()));
    Assert.assertEquals(apiEndpointMap, retrievedApiEndpoint);
    apiDAO.deleteAPI(api.getId());
    Endpoint retrievedGlobal = apiDAO.getEndpoint(globalEndpoint.getId());
    Assert.assertNotNull(retrievedGlobal);
    Assert.assertEquals(endpointToInsert, retrievedGlobal);
}

From source file:org.wildfly.security.tool.FileSystemRealmCommand.java

/**
 * Handles creating the Elytron filesystem-realm from the input arrays
 *
 * @throws Exception Exception to be handled by Elytron Tool
 *///from w  w  w  .j av  a  2 s  .c  o  m
private void createFileSystemRealm() throws Exception {
    Security.addProvider(new WildFlyElytronProvider());
    for (int i = 0; i < descriptors.size(); i++) {
        Descriptor descriptor = descriptors.get(i);
        if (descriptor.getUsersFile() == null || descriptor.getRolesFile() == null
                || descriptor.getOutputLocation() == null) {
            continue;
        }
        List<String> usersList = parseInputFile(descriptor, USERS_FILE_PARAM, i + 1);
        List<String> rolesList = parseInputFile(descriptor, ROLES_FILE_PARAM, i + 1);
        if (usersList.isEmpty() || rolesList.isEmpty()) {
            descriptor.reset();
            continue;
        }
        FileSystemSecurityRealm newFileSystemRealm = new FileSystemSecurityRealm(
                Paths.get(descriptor.getOutputLocation()));
        Map<String, ArrayList<String>> usersMap = new HashMap<>();
        for (String userMapping : usersList) {
            String[] userStringSplit = userMapping.split("=");
            String user = userStringSplit[0].trim();
            String password;
            if (userStringSplit.length == 1) {
                String message = String.format("No password was found for user %s", user);
                warningHandler(message);
                password = null;
            } else {
                password = userStringSplit[1].trim();
            }
            ArrayList<String> userAttributes = new ArrayList<>();
            userAttributes.add(password);
            usersMap.put(user, userAttributes);
        }
        for (String rolesMapping : rolesList) {
            String[] rolesStringSplit = rolesMapping.split("=");
            String user = rolesStringSplit[0].trim();
            String[] roles = new String[] {};
            if (rolesStringSplit.length < 2) {
                String message = String.format("No roles were found for user %s", user);
                warningHandler(message);
            } else {
                roles = rolesStringSplit[1].trim().split(",");
            }
            ArrayList<String> userAttributes = usersMap.get(user);
            if (userAttributes == null) {
                String message = String.format("Roles were found for user %1$s, but user %1$s was not defined.",
                        user);
                warningHandler(message);
                ArrayList<String> attributesWithEmptyPassword = new ArrayList<>();
                attributesWithEmptyPassword.add(null);
                attributesWithEmptyPassword.addAll(new ArrayList<>(Arrays.asList(roles)));
                userAttributes = attributesWithEmptyPassword;
                usersMap.put(user, userAttributes);
            } else {
                userAttributes.addAll(Arrays.asList(roles));
                usersMap.replace(user, userAttributes);
            }
            if (summaryMode) {
                summaryString.append(
                        String.format("Added roles: %s for user %s.", ArrayUtils.toString(roles), user));
                summaryString.append(System.getProperty("line.separator"));
            }
        }
        usersMap.forEach((key, value) -> {
            ModifiableRealmIdentity identity = newFileSystemRealm
                    .getRealmIdentityForUpdate(new NamePrincipal(key));
            try {
                identity.create();
                MapAttributes attributes = new MapAttributes();
                attributes.addAll("roles", value.subList(1, value.size()));
                identity.setAttributes(attributes);
                String password = value.get(0);
                if (password != null) {
                    byte[] hashed = ByteIterator.ofBytes(password.getBytes(StandardCharsets.UTF_8))
                            .asUtf8String().hexDecode().drain();
                    PasswordSpec passwordSpec = new DigestPasswordSpec(key, descriptor.getRealmName(), hashed);
                    PasswordFactory factory = PasswordFactory.getInstance(DigestPassword.ALGORITHM_DIGEST_MD5);
                    DigestPassword digestPassword = (DigestPassword) factory.generatePassword(passwordSpec);
                    identity.setCredentials(Collections.singleton(new PasswordCredential(digestPassword)));
                }
                identity.dispose();
            } catch (NullPointerException e) {
                warningHandler(String.format("Could not read realm name from the users file"));
            } catch (Exception e) {
                warningHandler(String.format("Could not create realm for user %s due to error: ", key)
                        + e.getMessage());
            }
        });
    }
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java

@Test(description = "Test add api with production endpoint", expectedExceptions = {
        APIManagementException.class }, expectedExceptionsMessageRegExp = "Endpoint Already Exist By Name : endpoint3")
public void testUpdateApiEndpointNameWithAlreadyExistingName() throws APIManagementException {
    /**/*from w  w w  . j  ava  2 s.  c o  m*/
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Endpoint endpoint1 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint1")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint2 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, endpoint1);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, endpoint2);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString())
            .endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    apiBuilder.policies(Collections.emptySet());
    apiBuilder.apiPolicy(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gatewaySourceGenerator,
            gateway);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getId())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpoint(endpoint2.getId())).thenReturn(endpoint2);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getName())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpointByName(endpoint2.getName())).thenReturn(endpoint2);
    Endpoint endpoint3 = new Endpoint.Builder(endpoint2).name("endpoint3").build();
    Mockito.when(apiDAO.getEndpointByName(endpoint3.getName())).thenReturn(endpoint3);
    Map<String, Endpoint> updatedEndpointMap = new HashMap<>(endpointMap);
    updatedEndpointMap.replace(APIMgtConstants.SANDBOX_ENDPOINT, endpoint3);
    apiBuilder.endpoint(updatedEndpointMap);
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java

@Test(description = "Test add api with production endpoint")
public void testUpdateApiEndpointName() throws APIManagementException {
    /**// w ww .j  a  va 2s  .  com
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Endpoint endpoint1 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint1")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint2 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, endpoint1);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, endpoint2);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString())
            .endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    apiBuilder.policies(Collections.emptySet());
    apiBuilder.apiPolicy(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api,
            APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gatewaySourceGenerator,
            gateway, policyDAO);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getId())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpoint(endpoint2.getId())).thenReturn(endpoint2);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getName())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpointByName(endpoint2.getName())).thenReturn(endpoint2);
    Endpoint endpoint3 = new Endpoint.Builder(endpoint2).name("endpoint3").build();
    Map<String, Endpoint> updatedEndpointMap = new HashMap<>(endpointMap);
    updatedEndpointMap.replace(APIMgtConstants.SANDBOX_ENDPOINT, endpoint3);
    apiBuilder.endpoint(updatedEndpointMap);
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java

@Test(description = "Test add api with production endpoint")
public void testUpdateApiEndpointUrl() throws APIManagementException {
    /**//from  w  w w .  j a v  a2  s .  c  o m
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Endpoint endpoint1 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint1")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint2 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, endpoint1);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, endpoint2);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString())
            .endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    apiBuilder.policies(Collections.emptySet());
    apiBuilder.apiPolicy(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api,
            APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gatewaySourceGenerator,
            gateway, policyDAO);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getId())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpoint(endpoint2.getId())).thenReturn(endpoint2);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getName())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpointByName(endpoint2.getName())).thenReturn(endpoint2);
    Endpoint endpoint3 = new Endpoint.Builder(endpoint2).maxTps(1200).build();
    Map<String, Endpoint> updatedEndpointMap = new HashMap<>(endpointMap);
    updatedEndpointMap.replace(APIMgtConstants.SANDBOX_ENDPOINT, endpoint3);
    apiBuilder.endpoint(updatedEndpointMap);
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java

@Test(description = "Test add api with production endpoint", expectedExceptions = {
        APIManagementException.class }, expectedExceptionsMessageRegExp = "Endpoint Already Exist By Name : endpoint2")
public void testUpdateApiEndpointWithAlreadyAvailableEndpointName() throws APIManagementException {
    /**/*from   w w w.j  a v a  2  s  .com*/
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Endpoint endpoint1 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint1")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint2 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint3 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, endpoint1);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, endpoint2);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString())
            .endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    apiBuilder.policies(Collections.emptySet());
    apiBuilder.apiPolicy(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gatewaySourceGenerator,
            gateway);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getId())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpoint(endpoint2.getId())).thenReturn(endpoint2);
    Mockito.when(apiDAO.getEndpoint(endpoint3.getId())).thenReturn(null);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getName())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpointByName(endpoint2.getName())).thenReturn(endpoint2);
    Map<String, Endpoint> updatedEndpointMap = new HashMap<>(endpointMap);
    updatedEndpointMap.replace(APIMgtConstants.SANDBOX_ENDPOINT, endpoint3);
    apiBuilder.endpoint(updatedEndpointMap);
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java

@Test(description = "Test add api with production endpoint")
public void testUpdateApiEndpointWithNewApiLevel() throws APIManagementException {
    /**/*from  w ww  .  j  av a2 s  . c  om*/
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Endpoint endpoint1 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint1")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint2 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint2")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint endpoint3 = new Endpoint.Builder().id(UUID.randomUUID().toString())
            .endpointConfig("http://localhost").name("endpoint3")
            .applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, endpoint1);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, endpoint2);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString())
            .endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    apiBuilder.policies(Collections.emptySet());
    apiBuilder.apiPolicy(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api,
            APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gatewaySourceGenerator,
            gateway, policyDAO);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getId())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpoint(endpoint2.getId())).thenReturn(endpoint2);
    Mockito.when(apiDAO.getEndpoint(endpoint3.getId())).thenReturn(null);
    Mockito.when(apiDAO.getEndpoint(endpoint1.getName())).thenReturn(endpoint1);
    Mockito.when(apiDAO.getEndpointByName(endpoint2.getName())).thenReturn(endpoint2);
    Map<String, Endpoint> updatedEndpointMap = new HashMap<>(endpointMap);
    updatedEndpointMap.replace(APIMgtConstants.SANDBOX_ENDPOINT, endpoint3);
    apiBuilder.endpoint(updatedEndpointMap);
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}