Example usage for java.net URI relativize

List of usage examples for java.net URI relativize

Introduction

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

Prototype

public URI relativize(URI uri) 

Source Link

Document

Relativizes the given URI against this URI.

Usage

From source file:com.hazelcast.stabilizer.Utils.java

public static byte[] zip(List<File> roots) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Deque<File> queue = new LinkedList<File>();
    ZipOutputStream zout = new ZipOutputStream(out);

    Set<String> names = new HashSet<String>();

    try {/* ww w.  j a v a  2 s. c o  m*/
        for (File root : roots) {
            URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
            queue.push(root);
            while (!queue.isEmpty()) {
                File file = queue.pop();
                if (file.getName().equals(".DS_Store")) {
                    continue;
                }

                //                    log.finest("Zipping: " + file.getAbsolutePath());

                if (file.isDirectory()) {
                    String name = base.relativize(file.toURI()).getPath();
                    name = name.endsWith("/") ? name : name + "/";

                    if (names.add(name)) {
                        zout.putNextEntry(new ZipEntry(name));
                    }

                    for (File kid : file.listFiles()) {
                        queue.push(kid);
                    }
                } else {
                    String name = base.relativize(file.toURI()).getPath();
                    zout.putNextEntry(new ZipEntry(name));
                    copy(file, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        zout.close();
    }

    return out.toByteArray();
}

From source file:org.apache.hadoop.mapred.lib.MobiusDelegatingInputFormat.java

public Class<AbstractMobiusMapper> getMapper(InputSplit split, JobConf conf) throws IOException {
    TaggedInputSplit taggedSplit = (TaggedInputSplit) split;
    InputSplit inputSplit = taggedSplit.getInputSplit();
    URI currentFileURI = MultiInputsHelpersRepository.getInstance(conf).getURIBySplit(inputSplit, conf);

    try {/*from  w  w  w .  ja  va 2  s  . c  o  m*/
        String[] pathToMapperMappings = conf.get("mapred.input.dir.mappers").split(",");
        for (String aPathToMapper : pathToMapperMappings) {
            //System.out.println("aPathToMapper:"+aPathToMapper);
            //System.out.println("currentFileURI:"+currentFileURI.toString());

            String[] data = aPathToMapper.split(";");
            URI path = new URI(data[0]);
            URI relative = path.relativize(currentFileURI);

            //System.out.println("relative:"+relative);

            String mapperClassName = data[1];
            if (currentFileURI.equals(path) || !relative.equals(currentFileURI)) {
                return (Class<AbstractMobiusMapper>) Class.forName(mapperClassName);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.igormaznitsa.nbmindmap.nb.refactoring.elements.MoveFileActionPlugin.java

@Override
protected Problem processFile(final Project project, final int level, final File projectFolder,
        final FileObject fileObject) {
    final MMapURI fileAsURI = MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null);

    final Lookup targetLookup = this.refactoring.getTarget();
    if (targetLookup == null) {
        return new Problem(true, BUNDLE.getString("MoveFileActionPlugin.cantFindLookup"));
    }/*  w w  w.j  a  v a 2 s.com*/

    final URL targetURL = targetLookup.lookup(URL.class);

    if (targetURL != null) {
        try {
            URI baseURI = targetURL.toURI();
            if (baseURI.isAbsolute()) {
                final URI projectURI = Utilities.toURI(projectFolder);
                baseURI = projectURI.relativize(baseURI);
            }

            final MMapURI newFileAsURI = MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null)
                    .replaceBaseInPath(true, baseURI, level);

            for (final FileObject mmap : allMapsInProject(project)) {
                try {
                    if (doesMindMapContainFileLink(project, mmap, fileAsURI)) {
                        final MoveElement element = new MoveElement(new MindMapLink(mmap), projectFolder,
                                MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null));
                        element.setTarget(newFileAsURI);
                        addElement(element);
                    }
                } catch (Exception ex) {
                    ErrorManager.getDefault().notify(ex);
                    return new Problem(true, BUNDLE.getString("Refactoring.CantProcessMindMap"));
                }
            }
        } catch (URISyntaxException ex) {
            LOGGER.error("Can't make new file uri for " + fileObject.getPath(), ex); //NOI18N
            return new Problem(true, BUNDLE.getString("MoveFileActionPlugin.cantMakeURIForFile")); //NOI18N
        }
        return null;
    } else {
        return new Problem(true, BUNDLE.getString("MoveFileActionPlugin.cantFindURL"));
    }
}

From source file:pcgen.system.RecentFileList.java

private void updateRecentFileProp() {
    URI userdir = new File(ConfigurationSettings.getUserDir()).toURI();

    List<String> uris = new ArrayList<>(fileList.size());
    fileList.stream().map(file -> userdir.relativize(file.toURI()).toString()).forEach(uris::add);
    PCGenSettings.getInstance().setStringArray(contextProp, uris);
}

From source file:org.wrml.mojo.schema.builder.SchemaBuilderMojo.java

private URI createModelUri(File sourceFile, URI rootUri) {

    URI relativeUri = rootUri.relativize(sourceFile.toPath().toUri());
    String modelUriString = SystemApi.Schema.getUri().toString() + "/" + relativeUri.toString();
    modelUriString = modelUriString.substring(0, modelUriString.lastIndexOf("."));
    getLog().info("Model URI created from " + relativeUri + ", and root " + rootUri + ", is " + modelUriString);
    return URI.create(modelUriString);
}

From source file:com.microsoftopentechnologies.windowsazurestorage.service.UploadService.java

/**
 * Convert the path on local file sytem to relative path on azure storage
 *
 * @param path       the local path//from w w  w . jav  a  2  s. c o  m
 * @param embeddedVP the embedded virtual path
 * @return
 */
protected String getItemPath(final FilePath path, final String embeddedVP)
        throws IOException, InterruptedException {
    final URI workspaceURI = serviceData.getRemoteWorkspace().toURI();

    // Remove the workspace bit of this path
    final URI srcURI = workspaceURI.relativize(path.toURI());
    final String srcURIPath = srcURI.getPath();
    String prefix = StringUtils.isBlank(serviceData.getVirtualPath()) ? "" : serviceData.getVirtualPath();
    if (!StringUtils.isBlank(embeddedVP)) {
        prefix += embeddedVP;
    }

    return prefix + srcURIPath;
}

From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java

/**
 * Uploads files to Windows Azure Storage.
 *
 * @param run environment of build/*from  ww  w .  j  av  a2  s . c o  m*/
 * @param listener logging
 * @param launcher env vars for remote builds
 * @param strAcc storage account information.
 * @param expContainerName container name.
 * @param cntPubAccess denotes if container is publicly accessible.
 * @param expFP File Path in ant glob syntax relative to CI tool workspace.
 * @param expVP Virtual Path of blob container.
 * @param excludeFP File Path in ant glob syntax to exclude from upload
 * @param uploadType upload file type
 * @param individualBlobs blobs from build
 * @param archiveBlobs blobs from build in archive files
 * @param cleanUpContainer if container is cleaned
 * @return filesUploaded number of files that are uploaded.
 * @throws WAStorageException throws exception
 */
public static int upload(Run<?, ?> run, Launcher launcher, TaskListener listener, StorageAccountInfo strAcc,
        String expContainerName, boolean cntPubAccess, boolean cleanUpContainer, String expFP, String expVP,
        String excludeFP, UploadType uploadType, List<AzureBlob> individualBlobs, List<AzureBlob> archiveBlobs,
        FilePath workspace) throws WAStorageException {

    int filesUploaded = 0; // Counter to track no. of files that are uploaded

    try {
        FilePath workspacePath = new FilePath(launcher.getChannel(), workspace.getRemote());

        listener.getLogger().println(Messages.WAStoragePublisher_uploading());

        CloudBlobContainer container = WAStorageClient.getBlobContainerReference(strAcc, expContainerName, true,
                true, cntPubAccess);

        // Delete previous contents if cleanup is needed
        if (cleanUpContainer) {
            deleteContents(container);
        }

        final String zipFolderName = "artifactsArchive";
        final String zipName = "archive.zip";
        // Make sure we exclude the tempPath from archiving.
        String excludesWithoutZip = "**/" + zipFolderName + "*/" + zipName;
        if (excludeFP != null) {
            excludesWithoutZip = excludeFP + "," + excludesWithoutZip;
        }
        String archiveIncludes = "";

        StringTokenizer strTokens = new StringTokenizer(expFP, fpSeparator);
        while (strTokens.hasMoreElements()) {
            String fileName = strTokens.nextToken();

            String embeddedVP = null;

            if (fileName != null && fileName.contains("::")) {
                int embVPSepIndex = fileName.indexOf("::");

                // Separate fileName and Virtual directory name
                if (fileName.length() > embVPSepIndex + 1) {
                    embeddedVP = fileName.substring(embVPSepIndex + 2, fileName.length());

                    if (Utils.isNullOrEmpty(embeddedVP)) {
                        embeddedVP = null;
                    } else if (!embeddedVP.endsWith(Constants.FWD_SLASH)) {
                        embeddedVP = embeddedVP + Constants.FWD_SLASH;
                    }
                }
                fileName = fileName.substring(0, embVPSepIndex);
            }

            archiveIncludes += "," + fileName;

            // List all the paths without the zip archives.
            FilePath[] paths = workspacePath.list(fileName, excludesWithoutZip);
            filesUploaded += paths.length;

            URI workspaceURI = workspacePath.toURI();

            if (uploadType == UploadType.INVALID) {
                // no files are uploaded
                return 0;
            }

            if (paths.length != 0 && uploadType != UploadType.ZIP) {
                for (FilePath src : paths) {
                    // Remove the workspace bit of this path
                    URI srcURI = workspaceURI.relativize(src.toURI());

                    CloudBlockBlob blob;
                    String srcPrefix = srcURI.getPath();
                    if (Utils.isNullOrEmpty(expVP) && Utils.isNullOrEmpty(embeddedVP)) {
                        blob = container.getBlockBlobReference(srcPrefix);
                    } else {
                        String prefix = expVP;

                        if (!Utils.isNullOrEmpty(embeddedVP)) {
                            if (Utils.isNullOrEmpty(expVP)) {
                                prefix = embeddedVP;
                            } else {
                                prefix = expVP + embeddedVP;
                            }
                        }
                        blob = container.getBlockBlobReference(prefix + srcPrefix);
                    }

                    String uploadedFileHash = upload(listener, blob, src);
                    individualBlobs.add(new AzureBlob(blob.getName(),
                            blob.getUri().toString().replace("http://", "https://"), uploadedFileHash,
                            src.length()));
                }
            }
        }

        if (filesUploaded != 0 && (uploadType != UploadType.INDIVIDUAL)) {
            // Create a temp dir for the upload
            FilePath tempPath = workspacePath.createTempDir(zipFolderName, null);

            Glob globScanner = new Glob(archiveIncludes, excludesWithoutZip);

            FilePath zipPath = tempPath.child(zipName);
            workspacePath.zip(zipPath.write(), globScanner);

            // When uploading the zip, do not add in the tempDir to the block
            // blob reference.
            String blobURI = zipPath.getName();

            if (!Utils.isNullOrEmpty(expVP)) {
                blobURI = expVP + blobURI;
            }

            CloudBlockBlob blob = container.getBlockBlobReference(blobURI);

            String uploadedFileHash = upload(listener, blob, zipPath);
            // Make sure to note the new blob as an archive blob,
            // so that it can be specially marked on the azure storage page.
            archiveBlobs
                    .add(new AzureBlob(blob.getName(), blob.getUri().toString().replace("http://", "https://"),
                            uploadedFileHash, zipPath.length()));

            tempPath.deleteRecursive();
        }

    } catch (StorageException | IOException | InterruptedException | URISyntaxException e) {
        throw new WAStorageException(e.getMessage(), e.getCause());
    }
    return filesUploaded;
}

From source file:com.qwazr.extractor.UriInfoImpl.java

public UriInfoImpl(final URI base, final URI child) {
    baseUri = base;/*w ww  .  ja  va 2 s  .c om*/
    absoluteUri = child.isAbsolute() ? child : base.resolve(child);
    relativeUri = base.relativize(child);
}

From source file:com.terradue.dsi.UploadAppliance.java

private void addToZip(ZipOutputStream os, URI base, File file) throws IOException {
    String name = base.relativize(file.toURI()).getPath();

    if (file.isDirectory()) {
        name = name.endsWith("/") ? name : name + "/";
    }/*w w  w  .  j av  a2 s .  co m*/

    ZipEntry entry = new ZipEntry(name);
    entry.setSize(file.length());
    os.putNextEntry(entry);

    if (file.isDirectory()) {
        logger.info(" creating: {}", name);

        for (File kid : file.listFiles()) {
            addToZip(os, base, kid);
        }
    } else {
        logger.info("deflating: {}", name);

        FileInputStream input = new FileInputStream(file);

        long compressed = 0;
        int length = 0;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

        try {
            while (EOF != (length = input.read(buffer))) {
                os.write(buffer, 0, length);

                compressed += length;
                System.out.printf("%s%%\r", ((compressed * 100) / file.length()));
            }
        } finally {
            closeQuietly(input);
        }
    }

    os.closeEntry();
}

From source file:stargate.drivers.temporalstorage.hdfs.HDFSTemporalStorageDriver.java

@Override
public Collection<URI> listDirectory(URI path) throws IOException, FileNotFoundException {
    if (path == null) {
        throw new IllegalArgumentException("path is null");
    }//from   ww  w.  jav a  2  s  . c  o  m

    Path hdfsPath = getAbsPath(path);
    if (!this.filesystem.exists(hdfsPath)) {
        throw new FileNotFoundException("directory (" + hdfsPath.toString() + ") not exist");
    }

    FileStatus[] listStatus = this.filesystem.listStatus(hdfsPath);
    List<URI> entries = new ArrayList<URI>();
    if (listStatus != null && listStatus.length > 0) {
        for (FileStatus status : listStatus) {
            URI entryPath = status.getPath().toUri();
            URI relativePath = entryPath.relativize(this.rootPath.toUri());

            entries.add(relativePath);
        }
    }

    return entries;
}