Example usage for java.net URI equals

List of usage examples for java.net URI equals

Introduction

In this page you can find the example usage for java.net URI equals.

Prototype

public boolean equals(Object ob) 

Source Link

Document

Tests this URI for equality with another object.

Usage

From source file:org.wrml.runtime.rest.ApiBuilder.java

private void autoLink(final Resource referrerResource, final Prototype prototype) {

    final Context context = getContext();
    final ApiLoader apiLoader = context.getApiLoader();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final Collection<LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots().values();
    for (final LinkProtoSlot linkProtoSlot : linkProtoSlots) {

        URI linkResponseSchemaUri = linkProtoSlot.getResponseSchemaUri();
        if (linkResponseSchemaUri == null) {
            continue;
        }/* ww  w . j a v  a  2s.  c o  m*/

        final URI requestSchemaUri = linkProtoSlot.getRequestSchemaUri();

        final URI linkRelationUri = linkProtoSlot.getLinkRelationUri();
        final LinkRelation linkRelation = apiLoader.loadLinkRelation(linkRelationUri);

        final UUID referrerResourceTemplateId = referrerResource.getResourceTemplateId();

        final Resource endpointResource = findSuitableLinkEndpoint(referrerResource, linkRelation,
                linkResponseSchemaUri);
        if (endpointResource != null) {
            final UUID endpointResourceTemplateId = endpointResource.getResourceTemplateId();

            if (linkResponseSchemaUri.equals(schemaLoader.getDocumentSchemaUri())) {
                final URI defaultSchemaUri = endpointResource.getDefaultSchemaUri();
                if (defaultSchemaUri != null) {
                    linkResponseSchemaUri = defaultSchemaUri;
                }

            }

            link(referrerResourceTemplateId, linkRelationUri, endpointResourceTemplateId, linkResponseSchemaUri,
                    requestSchemaUri);
        }
    }
}

From source file:com.mindcognition.mindraider.application.model.outline.OutlineCustodian.java

/**
 * Load a notebook./*from w w w.j av  a 2s .  c  o m*/
 * @param uri notebook URI.
 */
public boolean loadOutline(URI uri) {
    if (uri == null || "".equals(uri)) {
        StatusBar.show("Unable to load Notebook - URI is null!");
        return false;
    }

    // check whether notebook is not already loaded
    if (uri.equals(MindRaider.profile.getActiveOutline()) && activeOutlineResource != null) {
        StatusBar.show("Notebook '" + uri.toString() + "' already loaded ;-)");
        return false;
    }

    StatusBar.show("Loading notebook '" + uri + "'...");
    String notebookResourceFilename = getResourceFilenameByDirectory(getOutlineDirectory(uri.toString()));
    Resource resource;
    try {
        resource = new Resource(notebookResourceFilename);
    } catch (Exception e) {
        logger.debug("Unable to load notebook " + uri, e);
        StatusBar.show("Error: Unable to load notebook " + uri + "! " + e.getMessage(), Color.RED);
        return false;
    }

    // load RDF model
    String notebookModelFilename = getModelFilenameByDirectory(getOutlineDirectory(uri.toString()));
    try {
        MindRaider.spidersGraph.load(notebookModelFilename);
    } catch (Exception e1) {
        logger.debug("Unable to load notebook model: " + e1.getMessage(), e1);
        MindRaider.profile.setActiveOutline(null);
        MindRaider.profile.setActiveOutlineUri(null);
        activeOutlineResource = null;

        return false;
    }
    MindRaider.spidersGraph.selectNodeByUri(uri.toString());
    MindRaider.masterToolBar.setModelLocation(notebookModelFilename);

    // set notebook URI in profile
    MindRaider.profile.setActiveOutline(uri);
    activeOutlineResource = new OutlineResource(resource);
    activeOutlineResource.rdfModel = MindRaider.spidersGraph.getRdfModel();

    if (resource != null && resource.getMetadata() != null && resource.getMetadata().getUri() != null) {
        MindRaider.history.add(resource.getMetadata().getUri().toString());
    } else {
        logger.error("Resource " + uri + "not loaded is null!");
        return false;
    }
    return true;
}

From source file:ddf.catalog.impl.operations.ResourceOperations.java

private ResourceInfo getResourceInfo(QueryRequest queryRequest, URI uri,
        Map<String, Serializable> requestProperties, StringBuilder federatedSite, boolean fanoutEnabled)
        throws ResourceNotFoundException, UnsupportedQueryException, FederationException {
    Metacard metacard;/*from   www . j  a v a  2  s . c  o m*/
    URI resourceUri = uri;
    QueryResponse queryResponse = queryOperations.query(queryRequest, null, true, fanoutEnabled);
    if (queryResponse.getResults().isEmpty()) {
        throw new ResourceNotFoundException("Could not resolve source id for URI by doing a URI based query.");
    }
    metacard = queryResponse.getResults().get(0).getMetacard();
    if (uri != null && queryResponse.getResults().size() > 1) {
        for (Result result : queryResponse.getResults()) {
            if (uri.equals(result.getMetacard().getResourceURI())) {
                metacard = result.getMetacard();
                break;
            }
        }
    }
    if (resourceUri == null) {
        resourceUri = metacard.getResourceURI();
    }
    federatedSite.append(metacard.getSourceId());
    LOGGER.debug("Trying to lookup resource URI {} for metacardId: {}", resourceUri, metacard.getId());

    if (!requestProperties.containsKey(Metacard.ID)) {
        requestProperties.put(Metacard.ID, metacard.getId());
    }
    if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) {
        requestProperties.put(Metacard.RESOURCE_URI, metacard.getResourceURI());
    }

    return new ResourceInfo(metacard, resourceUri);
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

private String buildLinkSignature(final String linkFunctionName, final URI responseSchemaUri,
        final URI requestSchemaUri, final URI thisSchemaUri) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    final StringBuilder signatureBuilder = new StringBuilder();

    if (responseSchemaUri != null) {
        final Prototype responsePrototype = schemaLoader.getPrototype(responseSchemaUri);
        final String responseSchemaName = responsePrototype.getUniqueName().getLocalName();
        signatureBuilder.append(responseSchemaName);
    } else {//from   w  ww.  j a  v a2  s .  co m
        signatureBuilder.append("void");
    }

    signatureBuilder.append(" ");

    signatureBuilder.append(linkFunctionName).append(" ( ");

    if (requestSchemaUri != null && !requestSchemaUri.equals(thisSchemaUri)) {
        final Prototype requestPrototype = schemaLoader.getPrototype(requestSchemaUri);
        final String requestSchemaName = requestPrototype.getUniqueName().getLocalName();

        signatureBuilder.append(requestSchemaName);

        signatureBuilder.append(" ");

        final String parameterName = Character.toLowerCase(requestSchemaName.charAt(0))
                + requestSchemaName.substring(1);
        signatureBuilder.append(parameterName);
    }

    signatureBuilder.append(" ) ");

    final String signature = signatureBuilder.toString();
    return signature;
}

From source file:org.wrml.runtime.schema.Prototype.java

/**
 * Creates a new Prototype to represent the identified schema.
 *
 * @param schemaLoader The schema loader for this prototype's schema.
 * @param schemaUri    The schema identifier.
 * @throws PrototypeException Thrown if there are problems with the initial prototyping of the schema.
 *//*from ww  w.j  ava2 s .c  o  m*/
Prototype(final SchemaLoader schemaLoader, final URI schemaUri) throws PrototypeException {

    LOGGER.debug("Creating Prototype for schema ID: {}", new Object[] { schemaUri });

    _SchemaLoader = schemaLoader;
    if (_SchemaLoader == null) {

        throw new PrototypeException("The SchemaLoader parameter value cannot be *null*.", null, this);
    }

    _SchemaUri = schemaUri;
    if (_SchemaUri == null) {
        throw new PrototypeException("The undefined (aka *null*) schema can not be prototyped.", null, this);
    }

    if (schemaUri.equals(schemaLoader.getResourceTemplateSchemaUri())) {
        LOGGER.debug("Creating Prototype for ResourceTemplate");
    }

    _UniqueName = new UniqueName(_SchemaUri);

    //
    // Use the SchemaLoader and the schema uri to get the schema's Java Class
    // representation.
    //
    final Class<?> schemaInterface = getSchemaInterface();

    if (ValueType.JAVA_TYPE_ABSTRACT.equals(schemaInterface)) {
        _IsAbstract = true;
    } else if (Document.class.equals(schemaInterface)) {
        _IsDocument = true;
    }

    //
    // Introspect the associated class, extracting metadata from the parent
    // schema's Java interfaces (up to but not including the Model
    // interface).
    //

    _SchemaBean = new JavaBean(schemaInterface, ValueType.JAVA_TYPE_MODEL, LinkSlot.class);
    _AllBaseSchemaUris = new LinkedHashSet<>();
    _BaseSchemaUris = new LinkedHashSet<>();
    _AllSlotNames = new TreeSet<>();
    _ProtoSlots = new TreeMap<>();
    _CollectionPropertyProtoSlots = new TreeMap<>();
    _LinkRelationUris = new TreeMap<>();

    _LinkProtoSlots = new TreeMap<>();
    _SlotAliases = new TreeMap<>();
    _SearchableSlots = new TreeSet<>();

    // initBaseSchemas(...)
    {

        //
        // Use Java reflection to get all implemented interfaces and then turn
        // them into schema ids. With reflection we get de-duplication and
        // recursive traversal for free.
        //

        final List<Class<?>> allBaseInterfaces = ClassUtils.getAllInterfaces(schemaInterface);
        // Loop backwards to achieve desired key mapping precedence/overriding
        for (final Class<?> baseInterface : allBaseInterfaces) {

            if (ValueType.isSchemaInterface(baseInterface) && (baseInterface != ValueType.JAVA_TYPE_MODEL)) {

                final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface);
                _AllBaseSchemaUris.add(baseSchemaUri);

                if (Document.class.equals(baseInterface)) {
                    _IsDocument = true;
                }

                if (AggregateDocument.class.equals(baseInterface)) {
                    _IsAggregate = true;
                }

            }

        }

        // Store the immediate base schemas as well

        final Class<?>[] baseInterfaces = schemaInterface.getInterfaces();
        if (baseInterfaces != null) {

            for (final Class<?> baseInterface : baseInterfaces) {
                if (ValueType.isSchemaInterface(baseInterface)
                        && (baseInterface != ValueType.JAVA_TYPE_MODEL)) {
                    final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface);
                    _BaseSchemaUris.add(baseSchemaUri);
                }

                if (ValueType.JAVA_TYPE_ABSTRACT.equals(baseInterface)) {
                    _IsAbstract = true;
                }
            }

        }

    } // End of base schema init

    // initKeys(...)
    {
        final WRML wrml = schemaInterface.getAnnotation(WRML.class);
        if (wrml != null) {
            final String[] keySlotNameArray = wrml.keySlotNames();

            if ((keySlotNameArray != null) && (keySlotNameArray.length > 0)) {

                _KeySlotNames = new TreeSet<>(Arrays.asList(keySlotNameArray));

                if (_KeySlotNames.size() == 1) {
                    final String keySlotName = _KeySlotNames.first();
                    final Property property = _SchemaBean.getProperties().get(keySlotName);
                    if (property != null) {
                        _KeyType = property.getType();
                    } else {
                        throw new PrototypeException("The named key slot, \"" + keySlotName
                                + "\", is not defined for Schema: " + schemaUri + ".", null, this);
                    }
                } else {

                    // Schemas with Keys that use more than one slot value to
                    // determine uniqueness use the CompositeKey type (at
                    // runtime) as their key object.
                    //
                    _KeyType = ValueType.JAVA_TYPE_COMPOSITE_KEY;
                }

            }

            final String[] comparableSlotNameArray = wrml.comparableSlotNames();

            if ((comparableSlotNameArray != null) && (comparableSlotNameArray.length > 0)) {

                _ComparableSlotNames = new LinkedHashSet<String>(Arrays.asList(comparableSlotNameArray));
            }

            final String titleSlotName = wrml.titleSlotName();
            if (StringUtils.isNotBlank(titleSlotName)) {
                _TitleSlotName = titleSlotName;
            }

        }

    } // End of the key initialization

    // initMiscAnnotations(...)
    {

        final Description schemaDescription = schemaInterface.getAnnotation(Description.class);
        if (schemaDescription != null) {
            _Description = schemaDescription.value();
        } else {
            _Description = null;
        }

        final Title schemaTitle = schemaInterface.getAnnotation(Title.class);
        if (schemaTitle != null) {
            _Title = schemaTitle.value();
        } else {
            _Title = schemaInterface.getSimpleName();
        }

        final ThumbnailImage thumbnailImage = schemaInterface.getAnnotation(ThumbnailImage.class);
        if (thumbnailImage != null) {
            _ThumbnailLocation = URI.create(thumbnailImage.value());
        } else {
            _ThumbnailLocation = null;
        }

        _ReadOnly = (schemaInterface.getAnnotation(ReadOnly.class) != null) ? true : false;

        final Version schemaVersion = schemaInterface.getAnnotation(Version.class);
        if (schemaVersion != null) {
            _Version = schemaVersion.value();
        } else {
            // TODO: Look for the "static final long serialVersionUID" ?
            _Version = 1L;
        }

        final Tags tags = schemaInterface.getAnnotation(Tags.class);
        if (tags != null) {
            final String[] tagArray = tags.value();

            if ((tagArray != null) && (tagArray.length > 0)) {

                _Tags = new TreeSet<String>(Arrays.asList(tagArray));
            }
        }

    } // End of annotation-based initialization

    // initPropertySlots(...)
    {
        final Map<String, Property> properties = _SchemaBean.getProperties();

        for (final String slotName : properties.keySet()) {
            final Property property = properties.get(slotName);

            final PropertyProtoSlot propertyProtoSlot;

            final CollectionSlot collectionSlot = property.getAnnotation(CollectionSlot.class);
            if (collectionSlot != null) {
                propertyProtoSlot = new CollectionPropertyProtoSlot(this, slotName, property);
            } else {
                propertyProtoSlot = new PropertyProtoSlot(this, slotName, property);
            }

            addProtoSlot(propertyProtoSlot);
        }
    }

    // initLinkSlots(...)
    {

        //
        // Map the the schema bean's "other" (non-Property) methods.
        //

        final SortedMap<String, SortedSet<JavaMethod>> otherMethods = _SchemaBean.getOtherMethods();
        final Set<String> otherMethodNames = otherMethods.keySet();

        for (final String methodName : otherMethodNames) {

            final SortedSet<JavaMethod> methodSet = otherMethods.get(methodName);
            if (methodSet.size() != 1) {
                throw new PrototypeException("The link method: " + methodName + " cannot be overloaded.", this);
            }

            final JavaMethod javaMethod = methodSet.first();
            final Method method = javaMethod.getMethod();

            final LinkSlot linkSlot = method.getAnnotation(LinkSlot.class);
            if (linkSlot == null) {
                throw new PrototypeException("The method: " + javaMethod + " is not a link method", null, this);
            }

            final String relationUriString = linkSlot.linkRelationUri();
            final URI linkRelationUri = URI.create(relationUriString);

            if (_LinkProtoSlots.containsKey(linkRelationUri)) {
                throw new PrototypeException(
                        "A schema cannot use the same link relation for more than one method. Duplicate link relation: "
                                + linkRelationUri + " found in link method: " + javaMethod,
                        this);
            }

            final org.wrml.model.rest.Method relMethod = linkSlot.method();

            String slotName = methodName;
            if (relMethod == org.wrml.model.rest.Method.Get && slotName.startsWith(JavaBean.GET)) {
                slotName = slotName.substring(3);
                slotName = Character.toLowerCase(slotName.charAt(0)) + slotName.substring(1);
            }
            _LinkRelationUris.put(slotName, linkRelationUri);

            if (_ProtoSlots.containsKey(slotName)) {
                throw new PrototypeException(
                        "A schema cannot use the same name for more than one slot. Duplicate slot name: "
                                + slotName + " found in link method: " + javaMethod,
                        this);
            }

            final LinkProtoSlot linkProtoSlot = new LinkProtoSlot(this, slotName, javaMethod);

            if ((linkProtoSlot.isEmbedded() || isAggregate())
                    && (relMethod == org.wrml.model.rest.Method.Get)) {
                _ContainsEmbeddedLink = true;
            }

            _LinkProtoSlots.put(linkRelationUri, linkProtoSlot);

            addProtoSlot(linkProtoSlot);

        }

    } // End of link slot init

    if (!_SlotAliases.isEmpty()) {
        for (final String alias : _SlotAliases.keySet()) {
            final ProtoSlot protoSlot = _ProtoSlots.get(alias);
            protoSlot.setAlias(true);
            final String realName = _SlotAliases.get(alias);
            protoSlot.setRealName(realName);

        }
    }

}

From source file:org.entrystore.repository.impl.ContextManagerImpl.java

/**
 * intersection for all entries//from   ww  w.j a  v  a 2s. co m
 * @param intersectionEntries
 * @param entries
 * @param mdEntries
 * @param contextList
 * @return
 */
private List<Entry> intersectEntriesFromContexts(List<Entry> intersectionEntries, List<URI> contextList) {
    if (contextList == null) {
        return intersectionEntries;
    }

    // filter the list so that only entrys wich belong to one of the specified contexts are included
    List<Entry> resultList = new ArrayList<Entry>();
    if (intersectionEntries != null) {
        for (URI u : contextList) {
            for (Entry e : intersectionEntries) {
                if (u.equals(e.getContext().getURI())) {
                    resultList.add(e);
                }
            }
        }
    }

    return resultList;
}

From source file:com.mellanox.r4h.MiniDFSCluster.java

public static void copyNameDirs(Collection<URI> srcDirs, Collection<URI> dstDirs, Configuration dstConf)
        throws IOException {
    URI srcDir = Lists.newArrayList(srcDirs).get(0);
    FileSystem dstFS = FileSystem.getLocal(dstConf).getRaw();
    for (URI dstDir : dstDirs) {
        Preconditions.checkArgument(!dstDir.equals(srcDir), "src and dst are the same: " + dstDir);
        File dstDirF = new File(dstDir);
        if (dstDirF.exists()) {
            if (!FileUtil.fullyDelete(dstDirF)) {
                throw new IOException("Unable to delete: " + dstDirF);
            }/*from  w w w .j av  a2  s . c om*/
        }
        LOG.info("Copying namedir from primary node dir " + srcDir + " to " + dstDir);
        FileUtil.copy(new File(srcDir), dstFS, new Path(dstDir), false, dstConf);
    }
}

From source file:org.entrystore.repository.impl.ContextManagerImpl.java

/**
 * @see org.entrystore.repository.ContextManager#exportContext(org.entrystore.repository.Entry, java.io.File, java.util.Set, boolean)
 *//*from   www  . j av a  2  s .  c om*/
public void exportContext(Entry contextEntry, File destFile, Set<URI> users, boolean metadataOnly,
        Class<? extends RDFWriter> writer) throws RepositoryException {
    String contextResourceURI = contextEntry.getResourceURI().toString();
    if (!contextResourceURI.endsWith("/")) {
        contextResourceURI += "/";
    }
    String contextEntryURI = contextEntry.getEntryURI().toString();
    String contextMetadataURI = contextEntry.getLocalMetadataURI().toString();
    String contextRelationURI = contextEntry.getRelationURI().toString();

    synchronized (this.entry.repository) {
        RepositoryConnection rc = null;
        BufferedOutputStream out = null;

        try {
            try {
                out = new BufferedOutputStream(new FileOutputStream(destFile));
            } catch (FileNotFoundException e) {
                log.error(e.getMessage());
                throw new RepositoryException(e);
            }

            rc = entry.getRepository().getConnection();

            RepositoryResult<org.openrdf.model.Resource> availableNGs = rc.getContextIDs();
            List<org.openrdf.model.Resource> filteredNGs = new ArrayList<org.openrdf.model.Resource>();
            while (availableNGs.hasNext()) {
                org.openrdf.model.Resource ng = availableNGs.next();
                String ngURI = ng.stringValue();
                if (metadataOnly) {
                    if (ngURI.startsWith(contextResourceURI)
                            && (ngURI.contains("/metadata/") || ngURI.contains("/cached-external-metadata/"))) {
                        filteredNGs.add(ng);
                    }
                } else {
                    if (ngURI.startsWith(contextResourceURI) || ngURI.equals(contextEntryURI)
                            || ngURI.equals(contextMetadataURI) || ngURI.equals(contextRelationURI)) {
                        filteredNGs.add(ng);
                    }
                }
            }

            RDFHandler rdfWriter = null;
            try {
                Constructor<? extends RDFWriter> constructor = writer.getConstructor(OutputStream.class);
                rdfWriter = (RDFWriter) constructor.newInstance(out);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            if (rdfWriter == null) {
                log.error("Unable to create an RDF writer, format not supported");
                return;
            }

            Map<String, String> namespaces = NS.getMap();
            for (String nsName : namespaces.keySet()) {
                rdfWriter.handleNamespace(nsName, namespaces.get(nsName));
            }

            rdfWriter.startRDF();
            RepositoryResult<Statement> rr = rc.getStatements(null, null, null, false,
                    filteredNGs.toArray(new org.openrdf.model.Resource[filteredNGs.size()]));
            while (rr.hasNext()) {
                Statement s = rr.next();
                org.openrdf.model.URI p = s.getPredicate();
                rdfWriter.handleStatement(s);
                if (!metadataOnly) {
                    if (p.equals(RepositoryProperties.Creator) || p.equals(RepositoryProperties.Contributor)
                            || p.equals(RepositoryProperties.Read) || p.equals(RepositoryProperties.Write)
                            || p.equals(RepositoryProperties.DeletedBy)) {
                        users.add(URI.create(s.getObject().stringValue()));
                    }
                }
            }
            rdfWriter.endRDF();
        } catch (RepositoryException e) {
            log.error("Error when exporting context", e);
            throw e;
        } catch (RDFHandlerException e) {
            log.error(e.getMessage(), e);
            throw new RepositoryException(e);
        } finally {
            rc.close();
            try {
                out.flush();
                out.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.wrml.runtime.rest.DefaultApiLoader.java

@Override
public Dimensions buildDocumentDimensions(final Method method, final URI uri,
        final DimensionsBuilder dimensionsBuilder) {

    if (method == null) {
        throw new NullPointerException("The request method cannot be null.");
    }//  w ww . j a va2s  .c  o  m

    if (uri == null) {
        throw new NullPointerException("The request method cannot be null.");
    }

    URI schemaUri = dimensionsBuilder.getSchemaUri();

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    ApiNavigator apiNavigator = null;
    if (!schemaLoader.getApiSchemaUri().equals(schemaUri)) {
        apiNavigator = getParentApiNavigator(uri);
    }

    if (apiNavigator != null) {
        final Resource resource = apiNavigator.getResource(uri);
        // Is the method allowed?
        final Set<URI> schemaUris = resource.getResponseSchemaUris(method);

        final URI documentSchemaUriConstant = schemaLoader.getDocumentSchemaUri();
        final URI modelSchemaUriConstant = schemaLoader.getTypeUri(Model.class);

        if (schemaUris != null) {

            if (schemaUri != null && schemaUris.isEmpty()) {
                // error, method not supported
                throw new ApiLoaderException(
                        "The method " + "[" + method + "]" + " is not supported by the api.", null, this);
            } else if (!schemaUris.isEmpty()
                    && (schemaUri == null || schemaUri.equals(documentSchemaUriConstant)
                            || schemaUri.equals(modelSchemaUriConstant))) {
                schemaUri = schemaUris.iterator().next();
            }

            if (schemaUri != null && !schemaUris.contains(schemaUri)
                    && !schemaUri.equals(documentSchemaUriConstant)
                    && !schemaUri.equals(modelSchemaUriConstant)) {
                // Error, unsupported schema id
                throw new ApiLoaderException(
                        "The schema " + "[" + schemaUri + "]" + " is not supported by the api.", null, this);
            }
        }

        if (schemaUri == null || schemaUri.equals(documentSchemaUriConstant)
                || schemaUri.equals(modelSchemaUriConstant)) {
            schemaUri = resource.getDefaultSchemaUri();
        }
    }

    dimensionsBuilder.setSchemaUri(schemaUri);

    final String queryPart = uri.getQuery();
    if (StringUtils.isNotEmpty(queryPart)) {
        final Map<String, String> queryParameters = dimensionsBuilder.getQueryParameters();
        if (queryParameters.isEmpty()) {
            final String[] queryParams = queryPart.split("&");
            for (String queryParam : queryParams) {
                final String[] queryParamNameValuePair = queryParam.split("=");
                final String queryParamName = queryParamNameValuePair[0];
                final String queryParamValue = queryParamNameValuePair[1];
                queryParameters.put(queryParamName, queryParamValue);
            }
        }
    }

    return dimensionsBuilder.toDimensions();
}

From source file:org.entrystore.repository.impl.ContextManagerImpl.java

public void importContext(Entry contextEntry, File srcFile) throws RepositoryException, IOException {
    Date before = new Date();

    File unzippedDir = FileOperations.createTempDirectory("scam_import", null);
    FileOperations.unzipFile(srcFile, unzippedDir);

    File propFile = new File(unzippedDir, "export.properties");
    log.info("Loading property file from " + propFile.toString());
    Properties props = new Properties();
    props.load(new FileInputStream(propFile));
    String srcScamBaseURI = props.getProperty("scamBaseURI");
    String srcContextEntryURI = props.getProperty("contextEntryURI");
    String srcContextResourceURI = props.getProperty("contextResourceURI");
    String srcContextMetadataURI = props.getProperty("contextMetadataURI");
    String srcContextRelationURI = props.getProperty("contextRelationURI");
    String srcContainedUsers = props.getProperty("containedUsers");

    if (srcScamBaseURI == null || srcContextEntryURI == null || srcContextResourceURI == null
            || srcContainedUsers == null) {
        String msg = "Property file of import ZIP did not contain all necessary properties, aborting import";
        log.error(msg);//ww w .j a  v  a 2  s . c om
        throw new org.entrystore.repository.RepositoryException(msg);
    }

    log.info("scamBaseURI: " + srcScamBaseURI);
    log.info("contextEntryURI: " + srcContextEntryURI);
    log.info("contextResourceURI: " + srcContextResourceURI);
    log.info("contextMetadataURI: " + srcContextMetadataURI);
    log.info("contextRelationURI: " + srcContextRelationURI);
    log.info("containedUsers: " + srcContainedUsers);

    List<String> containedUsers = Arrays.asList(srcContainedUsers.split(","));
    Map<String, String> id2name = new HashMap<String, String>();
    for (String u : containedUsers) {
        String[] uS = u.split(":");
        if (uS.length == 1) {
            id2name.put(uS[0], null);
        } else if (uS.length == 2) {
            id2name.put(uS[0], uS[1]);
        }
    }

    // remove entries from context

    log.info("Removing old entries from context...");
    Context cont = getContext(contextEntry.getId());
    Set<URI> entries = cont.getEntries();
    for (URI entryURI : entries) {
        String eId = cont.getByEntryURI(entryURI).getId();
        if (!eId.startsWith("_")) {
            log.info("Removing " + entryURI);
            try {
                cont.remove(entryURI);
            } catch (DisallowedException de) {
                log.warn(de.getMessage());
            }
        }
    }

    // copy resources/files to data dir of context

    File dstDir = new File(entry.getRepositoryManager().getConfiguration().getString(Settings.DATA_FOLDER),
            contextEntry.getId());
    if (!dstDir.exists()) {
        dstDir.mkdirs();
    }
    File resourceDir = new File(unzippedDir, "resources");
    if (resourceDir != null && resourceDir.exists() && resourceDir.isDirectory()) {
        for (File src : resourceDir.listFiles()) {
            File dst = new File(dstDir, src.getName());
            log.info("Copying " + src + " to " + dst);
            FileOperations.copyFile(src, dst);
        }
    }

    // load all statements from file

    long amountTriples = 0;
    long importedTriples = 0;
    File tripleFile = new File(unzippedDir, "triples.rdf");
    log.info("Loading quadruples from " + tripleFile.toString());
    InputStream rdfInput = new BufferedInputStream(new FileInputStream(tripleFile));

    PrincipalManager pm = entry.getRepositoryManager().getPrincipalManager();

    synchronized (this.entry.repository) {
        log.info("Importing context from stream");
        RepositoryConnection rc = null;
        try {
            rc = entry.getRepository().getConnection();
            rc.setAutoCommit(false);

            TriGParser parser = new TriGParser();
            parser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
            StatementCollector collector = new StatementCollector();
            parser.setRDFHandler(collector);
            parser.parse(rdfInput, srcScamBaseURI);

            String oldBaseURI = srcScamBaseURI;
            if (!oldBaseURI.endsWith("/")) {
                oldBaseURI += "/";
            }
            String newBaseURI = entry.getRepositoryManager().getRepositoryURL().toString();
            if (!newBaseURI.endsWith("/")) {
                newBaseURI += "/";
            }
            String oldContextID = srcContextResourceURI.substring(srcContextResourceURI.lastIndexOf("/") + 1);
            String newContextID = contextEntry.getId();

            String oldContextResourceURI = srcContextResourceURI;
            String oldContextEntryURI = srcContextEntryURI;
            String oldContextMetadataURI = srcContextMetadataURI;
            String oldContextRelationURI = srcContextRelationURI;
            String oldContextNS = oldContextResourceURI;
            if (!oldContextNS.endsWith("/")) {
                oldContextNS += "/";
            }
            String newContextNS = contextEntry.getResourceURI().toString();
            if (!newContextNS.endsWith("/")) {
                newContextNS += "/";
            }

            log.info("Old context ID: " + oldContextID);
            log.info("New context ID: " + newContextID);
            log.info("Old context resource URI: " + oldContextResourceURI);
            log.info("New context resource URI: " + contextEntry.getResourceURI().toString());
            log.info("Old context entry URI: " + oldContextEntryURI);
            log.info("New context entry URI: " + contextEntry.getEntryURI().toString());
            log.info("Old context metadata URI: " + oldContextMetadataURI);
            log.info("New context metadata URI: " + contextEntry.getLocalMetadataURI().toString());
            log.info("Old context relation URI: " + oldContextRelationURI);
            log.info("New context relation URI: " + contextEntry.getRelationURI().toString());

            // iterate over all statements and add them to the reposivory

            ValueFactory vf = rc.getValueFactory();
            for (Statement s : collector.getStatements()) {
                amountTriples++;
                org.openrdf.model.Resource context = s.getContext();
                if (context == null) {
                    log.warn("No named graph information provided, ignoring triple");
                    continue;
                }

                org.openrdf.model.Resource subject = s.getSubject();
                org.openrdf.model.URI predicate = s.getPredicate();
                Value object = s.getObject();

                if (predicate.equals(RepositoryProperties.Creator)
                        || predicate.equals(RepositoryProperties.Contributor)
                        || predicate.equals(RepositoryProperties.Read)
                        || predicate.equals(RepositoryProperties.Write)
                        || predicate.equals(RepositoryProperties.DeletedBy)) {
                    String oldUserID = object.stringValue()
                            .substring(object.stringValue().lastIndexOf("/") + 1);
                    log.info("Old user URI: " + object);
                    log.info("Old user ID: " + oldUserID);
                    String oldUserName = id2name.get(oldUserID);
                    URI newUserURI = null;
                    Entry pE = null;
                    if (oldUserName == null) {
                        pE = pm.get(oldUserID);
                    } else {
                        pE = pm.getPrincipalEntry(oldUserName);
                    }
                    if (pE != null) {
                        newUserURI = pE.getResourceURI();
                    }
                    if (newUserURI == null) {
                        log.info("Unable to detect principal for ID " + oldUserID + ", skipping");
                        continue;
                    }
                    object = vf.createURI(newUserURI.toString());
                    log.info("Created principal URI for user " + oldUserID + ":" + oldUserName + ": "
                            + object.stringValue());
                }

                if (subject instanceof org.openrdf.model.URI) {
                    String sS = subject.stringValue();
                    if (sS.startsWith(oldContextNS)) {
                        subject = vf.createURI(sS.replace(oldContextNS, newContextNS));
                    } else if (sS.equals(oldContextEntryURI)) {
                        subject = vf.createURI(contextEntry.getEntryURI().toString());
                    } else if (sS.equals(oldContextResourceURI)) {
                        subject = vf.createURI(contextEntry.getResourceURI().toString());
                    } else if (sS.equals(oldContextMetadataURI)) {
                        subject = vf.createURI(contextEntry.getLocalMetadataURI().toString());
                    } else if (sS.equals(oldContextRelationURI)) {
                        subject = vf.createURI(contextEntry.getRelationURI().toString());
                    }
                }

                if (object instanceof org.openrdf.model.URI) {
                    String oS = object.stringValue();
                    if (oS.startsWith(oldContextNS)) {
                        object = vf.createURI(oS.replace(oldContextNS, newContextNS));
                    } else if (oS.equals(oldContextEntryURI)) {
                        object = vf.createURI(contextEntry.getEntryURI().toString());
                    } else if (oS.equals(oldContextResourceURI)) {
                        object = vf.createURI(contextEntry.getResourceURI().toString());
                    } else if (oS.equals(oldContextMetadataURI)) {
                        object = vf.createURI(contextEntry.getLocalMetadataURI().toString());
                    } else if (oS.equals(oldContextRelationURI)) {
                        object = vf.createURI(contextEntry.getRelationURI().toString());
                    }
                }

                if (context instanceof org.openrdf.model.URI) {
                    String cS = context.stringValue();

                    //                  // dirty hack to skip metadata on portfolio
                    //                  if (cS.contains("/_contexts/metadata/")) {
                    //                     log.info("Skipping metadata triple for portfolio: " + s.toString());
                    //                     continue;
                    //                  }

                    if (cS.startsWith(oldContextNS)) {
                        context = vf.createURI(cS.replace(oldContextNS, newContextNS));
                    } else if (cS.equals(oldContextEntryURI)) {
                        context = vf.createURI(contextEntry.getEntryURI().toString());
                    } else if (cS.equals(oldContextResourceURI)) {
                        context = vf.createURI(contextEntry.getResourceURI().toString());
                    } else if (cS.equals(oldContextMetadataURI)) {
                        context = vf.createURI(contextEntry.getLocalMetadataURI().toString());
                    } else if (cS.equals(oldContextRelationURI)) {
                        context = vf.createURI(contextEntry.getRelationURI().toString());
                    }
                }

                // we check first whether such a stmnt already exists 
                Statement newStmnt = vf.createStatement(subject, predicate, object, context);
                if (!rc.hasStatement(newStmnt, false, context)) {
                    importedTriples++;
                    log.info("Adding statement to repository: " + newStmnt.toString());
                    rc.add(newStmnt, context);
                } else {
                    log.warn("Statement already exists, skipping: " + newStmnt.toString());
                }
            }

            rc.commit();
        } catch (Exception e) {
            rc.rollback();
            log.error(e.getMessage(), e);
        } finally {
            if (rc != null) {
                rc.close();
            }
        }
    }

    // clean up temp files

    log.info("Removing temporary files");
    for (File f : unzippedDir.listFiles()) {
        if (f.isDirectory()) {
            FileOperations.deleteAllFilesInDir(f);
        }
        f.delete();
    }
    unzippedDir.delete();

    // reindex the context to get everything reloaded

    log.info("Reindexing " + cont.getEntry().getEntryURI());
    cont.reIndex();

    log.info("Import finished in " + (new Date().getTime() - before.getTime()) + " ms");
    log.info("Imported " + importedTriples + " triples");
    log.info("Skipped " + (amountTriples - importedTriples) + " triples");
}