Example usage for java.util Collections EMPTY_MAP

List of usage examples for java.util Collections EMPTY_MAP

Introduction

In this page you can find the example usage for java.util Collections EMPTY_MAP.

Prototype

Map EMPTY_MAP

To view the source code for java.util Collections EMPTY_MAP.

Click Source Link

Document

The empty map (immutable).

Usage

From source file:de.hybris.platform.order.impl.DefaultCalculationService.java

protected Map<TaxValue, Map<Set<TaxValue>, Double>> calculateSubtotal(final AbstractOrderModel order,
        final boolean recalculate) {
    if (recalculate || orderRequiresCalculationStrategy.requiresCalculation(order)) {
        double subtotal = 0.0;
        // entry grouping via map { tax code -> Double }
        final List<AbstractOrderEntryModel> entries = order.getEntries();
        final Map<TaxValue, Map<Set<TaxValue>, Double>> taxValueMap = new LinkedHashMap<TaxValue, Map<Set<TaxValue>, Double>>(
                entries.size() * 2);/*  w  ww.  ja  va 2s .  c o  m*/

        for (final AbstractOrderEntryModel entry : entries) {
            calculateTotals(entry, recalculate);
            final double entryTotal = entry.getTotalPrice().doubleValue();
            subtotal += entryTotal;
            // use un-applied version of tax values!!!
            final Collection<TaxValue> allTaxValues = entry.getTaxValues();
            final Set<TaxValue> relativeTaxGroupKey = getUnappliedRelativeTaxValues(allTaxValues);
            for (final TaxValue taxValue : allTaxValues) {
                if (taxValue.isAbsolute()) {
                    addAbsoluteEntryTaxValue(entry.getQuantity().longValue(), taxValue.unapply(), taxValueMap);
                } else {
                    addRelativeEntryTaxValue(entryTotal, taxValue.unapply(), relativeTaxGroupKey, taxValueMap);
                }
            }
        }
        // store subtotal
        subtotal = commonI18NService.roundCurrency(subtotal, order.getCurrency().getDigits().intValue());
        order.setSubtotal(Double.valueOf(subtotal));
        return taxValueMap;
    }
    return Collections.EMPTY_MAP;
}

From source file:com.alibaba.rocketmq.tools.admin.DefaultMQAdminExtImpl.java

@Override
public Map<String, Map<MessageQueue, Long>> getConsumeStatus(String topic, String group, String clientAddr)
        throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
    TopicRouteData topicRouteData = this.examineTopicRouteInfo(topic);
    List<BrokerData> brokerDatas = topicRouteData.getBrokerDatas();
    if (brokerDatas != null && brokerDatas.size() > 0) {
        String addr = brokerDatas.get(0).selectBrokerAddr();
        if (addr != null) {
            return this.mqClientInstance.getMQClientAPIImpl().invokeBrokerToGetConsumerStatus(addr, topic,
                    group, clientAddr, timeoutMillis);
        }/*from w  w  w  . j  a  v  a 2  s.  co  m*/
    }
    return Collections.EMPTY_MAP;
}

From source file:org.apache.atlas.web.integration.BaseResourceIT.java

protected Referenceable createHiveTableInstanceBuiltIn(String dbName, String tableName, Id dbId)
        throws Exception {
    Map<String, Object> values = new HashMap<>();
    values.put(NAME, dbName);/*from  w w w .  ja va2s  .c o m*/
    values.put(DESCRIPTION, "foo database");
    values.put(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, dbName);
    values.put("owner", "user1");
    values.put(CLUSTER_NAME, "cl1");
    values.put("parameters", Collections.EMPTY_MAP);
    values.put("location", "/tmp");
    Referenceable databaseInstance = new Referenceable(dbId._getId(), dbId.getTypeName(), values);
    Referenceable tableInstance = new Referenceable(HIVE_TABLE_TYPE_BUILTIN, "classification", "pii", "phi",
            "pci", "sox", "sec", "finance");
    tableInstance.set(NAME, tableName);
    tableInstance.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, tableName);
    tableInstance.set("db", databaseInstance);
    tableInstance.set(DESCRIPTION, "bar table");
    tableInstance.set("lastAccessTime", "2014-07-11T08:00:00.000Z");
    tableInstance.set("type", "managed");
    tableInstance.set("level", 2);
    tableInstance.set("tableType", 1); // enum
    tableInstance.set("compressed", false);

    Struct traitInstance = (Struct) tableInstance.getTrait("classification");
    traitInstance.set("tag", "foundation_etl");

    Struct serde1Instance = new Struct("serdeType");
    serde1Instance.set(NAME, "serde1");
    serde1Instance.set("serde", "serde1");
    tableInstance.set("serde1", serde1Instance);

    Struct serde2Instance = new Struct("serdeType");
    serde2Instance.set(NAME, "serde2");
    serde2Instance.set("serde", "serde2");
    tableInstance.set("serde2", serde2Instance);

    List<String> traits = tableInstance.getTraits();
    Assert.assertEquals(traits.size(), 7);

    return tableInstance;
}

From source file:org.artificer.repository.hibernate.data.SrampToHibernateEntityRelationshipsVisitor.java

private void setRelationship(String relationshipName, RelationshipType relationshipType, Target target)
        throws Exception {
    if (target != null && StringUtils.isNotBlank(target.getValue())) {
        ArtificerRelationship artificerRelationship = createRelationship(relationshipName, relationshipType,
                Collections.EMPTY_MAP);

        createTarget(artificerRelationship, target);

        artificerArtifact.getRelationships().add(artificerRelationship);
    }//from w ww .  j  ava2s  .  c o  m
}

From source file:com.redhat.rhn.manager.user.UserManager.java

/**
 * Retrieve the list of all active users in the specified user's org
 * @param user The user who's org to search for users.
 * @return A list containing the specified number of users.
 *//*  www. j a va 2 s.co m*/
public static DataResult activeInOrg2(User user) {
    if (!user.hasRole(RoleFactory.ORG_ADMIN)) {
        //Throw an exception with a nice error message so the user
        //knows what went wrong.
        LocalizationService ls = LocalizationService.getInstance();
        PermissionException pex = new PermissionException(
                "User must be an" + " Org Admin to access the user list");
        pex.setLocalizedTitle(ls.getMessage("permission.jsp.title.userlist"));
        pex.setLocalizedSummary(ls.getMessage("permission.jsp.summary.userlist"));
        throw pex;
    }
    SelectMode m = ModeFactory.getMode("User_queries", "active_in_org");
    Map params = new HashMap();
    params.put("org_id", user.getOrg().getId());
    DataResult dr = m.execute(params);
    dr.elaborate(Collections.EMPTY_MAP);
    return dr;
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

@SuppressWarnings("unchecked")
private Collection<Artifact> getTransitive(Artifact ours)
        throws ArtifactResolutionException, ArtifactNotFoundException {
    ArtifactResolutionResult result = artifactResolver.resolveTransitively(Collections.singleton(ours),
            project.getArtifact(), Collections.EMPTY_MAP, localRepository, remoteRepositories, metadataSource,
            null, Collections.EMPTY_LIST);
    return result.getArtifacts();
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *///w w  w.  j a v a  2  s .  c om
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = findTargetClass(key, classMap);
                            newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                    : newTargetClass;
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    null);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = findTargetClass(key, classMap);
                                targetClass = targetClass == null ? findTargetClass(name, classMap)
                                        : targetClass;
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    null);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}

From source file:net.sf.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*  www . j av  a 2s  . c om*/
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = resolveClass(classMap, key, name, type);
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = resolveClass(classMap, key, name, type);
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    (JSONObject) value);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = resolveClass(classMap, key, name, type);
                                if (targetClass == null) {
                                    targetClass = Object.class;
                                }
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    (JSONObject) value);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}

From source file:org.alfresco.rest.api.tests.TestCMIS.java

/**
 * Tests OpenCMIS api.//from  ww  w .jav a 2  s .c om
 */
@SuppressWarnings("unchecked")
@Test
public void testCMIS() throws Exception {
    // Test Case cloud-2353
    // Test Case cloud-2354
    // Test Case cloud-2356
    // Test Case cloud-2378
    // Test Case cloud-2357
    // Test Case cloud-2358
    // Test Case cloud-2360

    final TestNetwork network1 = getTestFixture().getRandomNetwork();
    Iterator<String> personIt = network1.getPersonIds().iterator();
    final String personId = personIt.next();
    assertNotNull(personId);
    Person person = repoService.getPerson(personId);
    assertNotNull(person);

    // Create a site
    final TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
        @Override
        public TestSite doWork() throws Exception {
            String siteName = "site" + System.currentTimeMillis();
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName,
                    SiteVisibility.PRIVATE);
            TestSite site = network1.createSite(siteInfo);
            return site;
        }
    }, personId, network1.getId());

    publicApiClient.setRequestContext(new RequestContext(network1.getId(), personId));
    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10,
            AlfrescoObjectFactoryImpl.class.getName());
    Nodes nodesProxy = publicApiClient.nodes();
    Comments commentsProxy = publicApiClient.comments();

    String expectedContent = "Ipsum and so on";
    Document doc = null;
    Folder documentLibrary = (Folder) cmisSession
            .getObjectByPath("/Sites/" + site.getSiteId() + "/documentLibrary");
    FolderNode expectedDocumentLibrary = (FolderNode) CMISNode.createNode(documentLibrary);
    Document testDoc = null;
    Folder testFolder = null;
    FolderNode testFolderNode = null;

    // create some sub-folders and documents
    {
        for (int i = 0; i < 3; i++) {
            Map<String, String> properties = new HashMap<String, String>();
            {
                properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
                properties.put(PropertyIds.NAME, "folder-" + i);
            }

            Folder f = documentLibrary.createFolder(properties);
            FolderNode fn = (FolderNode) CMISNode.createNode(f);
            if (testFolder == null) {
                testFolder = f;
                testFolderNode = fn;
            }
            expectedDocumentLibrary.addFolder(fn);

            for (int k = 0; k < 3; k++) {
                properties = new HashMap<String, String>();
                {
                    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
                    properties.put(PropertyIds.NAME, "folder-" + k);
                }

                Folder f1 = f.createFolder(properties);
                FolderNode childFolder = (FolderNode) CMISNode.createNode(f1);
                fn.addFolder(childFolder);
            }

            for (int j = 0; j < 3; j++) {
                properties = new HashMap<String, String>();
                {
                    properties.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
                    properties.put(PropertyIds.NAME, "doc-" + j);
                }

                ContentStreamImpl fileContent = new ContentStreamImpl();
                {
                    ContentWriter writer = new FileContentWriter(
                            TempFileProvider.createTempFile(GUID.generate(), ".txt"));
                    writer.putContent(expectedContent);
                    ContentReader reader = writer.getReader();
                    fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                    fileContent.setStream(reader.getContentInputStream());
                }

                Document d = f.createDocument(properties, fileContent, VersioningState.MAJOR);
                if (testDoc == null) {
                    testDoc = d;
                }

                CMISNode childDocument = CMISNode.createNode(d);
                fn.addNode(childDocument);
            }
        }

        for (int i = 0; i < 10; i++) {
            Map<String, String> properties = new HashMap<String, String>();
            {
                properties.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
                properties.put(PropertyIds.NAME, "doc-" + i);
            }

            ContentStreamImpl fileContent = new ContentStreamImpl();
            {
                ContentWriter writer = new FileContentWriter(
                        TempFileProvider.createTempFile(GUID.generate(), ".txt"));
                writer.putContent(expectedContent);
                ContentReader reader = writer.getReader();
                fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                fileContent.setStream(reader.getContentInputStream());
            }

            documentLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
        }
    }

    // try to add and remove ratings, comments, tags to folders created by CMIS
    {
        Aggregate aggregate = new Aggregate(1, null);
        NodeRating expectedNodeRating = new NodeRating("likes", true, aggregate);
        Comment expectedComment = new Comment("commenty", "commenty", false, null, person, person);
        Tag expectedTag = new Tag("taggy");

        NodeRating rating = nodesProxy.createNodeRating(testFolder.getId(), expectedNodeRating);
        expectedNodeRating.expected(rating);
        assertNotNull(rating.getId());

        Tag tag = nodesProxy.createNodeTag(testFolder.getId(), expectedTag);
        expectedTag.expected(tag);
        assertNotNull(tag.getId());

        Comment comment = commentsProxy.createNodeComment(testFolder.getId(), expectedComment);
        expectedComment.expected(comment);
        assertNotNull(comment.getId());
    }

    // try to add and remove ratings, comments, tags to documents created by CMIS
    {
        Aggregate aggregate = new Aggregate(1, null);
        NodeRating expectedNodeRating = new NodeRating("likes", true, aggregate);
        Comment expectedComment = new Comment("commenty", "commenty", false, null, person, person);
        Tag expectedTag = new Tag("taggy");

        NodeRating rating = nodesProxy.createNodeRating(testDoc.getId(), expectedNodeRating);
        expectedNodeRating.expected(rating);
        assertNotNull(rating.getId());

        Tag tag = nodesProxy.createNodeTag(testDoc.getId(), expectedTag);
        expectedTag.expected(tag);
        assertNotNull(tag.getId());

        Comment comment = commentsProxy.createNodeComment(testDoc.getId(), expectedComment);
        expectedComment.expected(comment);
        assertNotNull(comment.getId());
    }

    // descendants
    {
        List<Tree<FileableCmisObject>> descendants = documentLibrary.getDescendants(4);
        expectedDocumentLibrary.checkDescendants(descendants);
    }

    // upload/setContent
    {
        Map<String, String> fileProps = new HashMap<String, String>();
        {
            fileProps.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
            fileProps.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
        }
        ContentStreamImpl fileContent = new ContentStreamImpl();
        {
            ContentWriter writer = new FileContentWriter(
                    TempFileProvider.createTempFile(GUID.generate(), ".txt"));
            writer.putContent(expectedContent);
            ContentReader reader = writer.getReader();
            fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            fileContent.setStream(reader.getContentInputStream());
        }
        doc = documentLibrary.createDocument(fileProps, fileContent, VersioningState.MAJOR);

        String nodeId = stripCMISSuffix(doc.getId());
        final NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId);
        ContentReader reader = TenantUtil.runAsUserTenant(new TenantRunAsWork<ContentReader>() {
            @Override
            public ContentReader doWork() throws Exception {
                ContentReader reader = repoService.getContent(nodeRef, ContentModel.PROP_CONTENT);
                return reader;
            }
        }, personId, network1.getId());

        String actualContent = reader.getContentString();
        assertEquals(expectedContent, actualContent);
    }

    // get content
    {
        ContentStream stream = doc.getContentStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(stream.getStream(), writer, "UTF-8");
        String actualContent = writer.toString();
        assertEquals(expectedContent, actualContent);
    }

    // get children
    {
        Folder folder = (Folder) cmisSession
                .getObjectByPath("/Sites/" + site.getSiteId() + "/documentLibrary/" + testFolder.getName());

        ItemIterable<CmisObject> children = folder.getChildren();
        testFolderNode.checkChildren(children);
    }

    // query
    {
        Folder folder = (Folder) cmisSession
                .getObjectByPath("/Sites/" + site.getSiteId() + "/documentLibrary/" + testFolder.getName());
        String folderId = folder.getId();

        Set<String> expectedFolderNames = new HashSet<String>();
        for (CMISNode n : testFolderNode.getFolderNodes().values()) {
            expectedFolderNames.add((String) n.getProperty("cmis:name"));
        }
        int expectedNumFolders = expectedFolderNames.size();
        int numMatchingFoldersFound = 0;
        List<CMISNode> results = cmisSession.query(
                "SELECT * FROM cmis:folder WHERE IN_TREE('" + folderId + "')", false, 0, Integer.MAX_VALUE);
        for (CMISNode node : results) {
            String name = (String) node.getProperties().get("cmis:name");
            if (expectedFolderNames.contains(name)) {
                numMatchingFoldersFound++;
            }
        }
        assertEquals(expectedNumFolders, numMatchingFoldersFound);

        Set<String> expectedDocNames = new HashSet<String>();
        for (CMISNode n : testFolderNode.getDocumentNodes().values()) {
            expectedDocNames.add((String) n.getProperty("cmis:name"));
        }
        int expectedNumDocs = expectedDocNames.size();
        int numMatchingDocsFound = 0;
        results = cmisSession.query("SELECT * FROM cmis:document where IN_TREE('" + folderId + "')", false, 0,
                Integer.MAX_VALUE);
        for (CMISNode node : results) {
            String name = (String) node.getProperties().get("cmis:name");
            if (expectedDocNames.contains(name)) {
                numMatchingDocsFound++;
            }
        }
        assertEquals(expectedNumDocs, numMatchingDocsFound);
    }

    // versioning
    {
        String nodeId = stripCMISSuffix(doc.getId());
        final NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId);

        // checkout
        ObjectId pwcId = doc.checkOut();
        Document pwc = (Document) cmisSession.getObject(pwcId.getId());
        Boolean isCheckedOut = TenantUtil.runAsUserTenant(new TenantRunAsWork<Boolean>() {
            @Override
            public Boolean doWork() throws Exception {
                Boolean isCheckedOut = repoService.isCheckedOut(nodeRef);
                return isCheckedOut;
            }
        }, personId, network1.getId());
        assertTrue(isCheckedOut);

        // checkin with new content
        expectedContent = "Big bad wolf";

        ContentStreamImpl fileContent = new ContentStreamImpl();
        {
            ContentWriter writer = new FileContentWriter(
                    TempFileProvider.createTempFile(GUID.generate(), ".txt"));
            writer.putContent(expectedContent);
            ContentReader reader = writer.getReader();
            fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            fileContent.setStream(reader.getContentInputStream());
        }
        ObjectId checkinId = pwc.checkIn(true, Collections.EMPTY_MAP, fileContent, "checkin 1");
        doc = (Document) cmisSession.getObject(checkinId.getId());
        isCheckedOut = TenantUtil.runAsUserTenant(new TenantRunAsWork<Boolean>() {
            @Override
            public Boolean doWork() throws Exception {
                Boolean isCheckedOut = repoService.isCheckedOut(nodeRef);
                return isCheckedOut;
            }
        }, personId, network1.getId());
        assertFalse(isCheckedOut);

        // check that the content has been updated
        ContentStream stream = doc.getContentStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(stream.getStream(), writer, "UTF-8");
        String actualContent = writer.toString();
        assertEquals(expectedContent, actualContent);

        List<Document> allVersions = doc.getAllVersions();
        assertEquals(2, allVersions.size());
        assertEquals("2.0", allVersions.get(0).getVersionLabel());
        assertEquals(CMIS_VERSION_10, allVersions.get(1).getVersionLabel());
    }

    {
        // https://issues.alfresco.com/jira/browse/PUBLICAPI-95
        // Test that documents are created with autoVersion=true

        Map<String, String> fileProps = new HashMap<String, String>();
        {
            fileProps.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
            fileProps.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
        }
        ContentStreamImpl fileContent = new ContentStreamImpl();
        {
            ContentWriter writer = new FileContentWriter(
                    TempFileProvider.createTempFile(GUID.generate(), ".txt"));
            writer.putContent("Ipsum and so on");
            ContentReader reader = writer.getReader();
            fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            fileContent.setStream(reader.getContentInputStream());
        }

        {
            // a versioned document

            Document autoVersionedDoc = documentLibrary.createDocument(fileProps, fileContent,
                    VersioningState.MAJOR);
            String objectId = autoVersionedDoc.getId();
            String bareObjectId = getBareObjectId(objectId);
            final NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, bareObjectId);
            Boolean autoVersion = TenantUtil.runAsUserTenant(new TenantRunAsWork<Boolean>() {
                @Override
                public Boolean doWork() throws Exception {
                    Boolean autoVersion = (Boolean) repoService.getProperty(nodeRef,
                            ContentModel.PROP_AUTO_VERSION);
                    return autoVersion;
                }
            }, personId, network1.getId());
            assertEquals(Boolean.TRUE, autoVersion);
        }

        // https://issues.alfresco.com/jira/browse/PUBLICAPI-92
        // Test that a get on an objectId without a version suffix returns the current version of the document
        {
            // do a few checkout, checkin cycles to create some versions
            fileProps = new HashMap<String, String>();
            {
                fileProps.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
                fileProps.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
            }

            Document autoVersionedDoc = documentLibrary.createDocument(fileProps, fileContent,
                    VersioningState.MAJOR);
            String objectId = autoVersionedDoc.getId();
            String bareObjectId = getBareObjectId(objectId);

            for (int i = 0; i < 3; i++) {
                Document doc1 = (Document) cmisSession.getObject(bareObjectId);

                ObjectId pwcId = doc1.checkOut();
                Document pwc = (Document) cmisSession.getObject(pwcId.getId());

                ContentStreamImpl contentStream = new ContentStreamImpl();
                {
                    ContentWriter writer = new FileContentWriter(
                            TempFileProvider.createTempFile(GUID.generate(), ".txt"));
                    expectedContent = GUID.generate();
                    writer.putContent(expectedContent);
                    ContentReader reader = writer.getReader();
                    contentStream.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                    contentStream.setStream(reader.getContentInputStream());
                }
                pwc.checkIn(true, Collections.EMPTY_MAP, contentStream, "checkin " + i);
            }

            // get the object, supplying an objectId without a version suffix
            Document doc1 = (Document) cmisSession.getObject(bareObjectId);
            String versionLabel = doc1.getVersionLabel();
            ContentStream cs = doc1.getContentStream();
            String content = IOUtils.toString(cs.getStream());

            assertEquals("4.0", versionLabel);
            assertEquals(expectedContent, content);
        }
    }
}

From source file:org.artificer.repository.hibernate.data.SrampToHibernateEntityRelationshipsVisitor.java

private void setRelationships(String relationshipName, RelationshipType relationshipType,
        List<? extends Target> targets) throws Exception {
    setRelationships(relationshipName, relationshipType, targets, Collections.EMPTY_MAP);
}