Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

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

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processOneUploadedResourceFile() throws IOException, WorkspaceNodeNotFoundException,
        URISyntaxException, WorkspaceException, NodeNotFoundException, TypeCheckerException {

    final String filename = "someFile.txt";
    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final File uploadedFile = new File(workspaceUploadDirectory, filename);
    final URI uploadedFileURI = uploadedFile.toURI();
    final URL uploadedFileURL = uploadedFileURI.toURL();
    final WorkspaceNodeType fileNodeType = WorkspaceNodeType.RESOURCE_WRITTEN;
    final String fileMimetype = "text/plain";

    final WorkspaceNode uploadedNode = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode.setName(filename);/*  ww  w .j  a va2  s. c  o m*/
    uploadedNode.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode.setType(fileNodeType);
    uploadedNode.setFormat(fileMimetype);
    uploadedNode.setWorkspaceURL(uploadedFileURL);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();
    uploadedNodes.add(uploadedNode);

    //only one file in the collection, so only one loop cycle

    final Collection<ImportProblem> failedLinks = new ArrayList<>();

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //loop

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI));
            oneOf(mockFile1).getName();
            will(returnValue(filename));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL, filename);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype);
            will(returnValue(fileNodeType));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null,
                    uploadedFileURL, null, null, fileMimetype, fileNodeType, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode);

            //check links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should be empty", result.isEmpty());
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processOneUploadedResourceFile_IsInOrphansDirectory()
        throws IOException, WorkspaceNodeNotFoundException, URISyntaxException, WorkspaceException,
        NodeNotFoundException, TypeCheckerException {

    final String filename = "someFile.txt";
    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final File uploadedFile = new File(workspaceUploadDirectory, filename);
    final URI uploadedFileURI = uploadedFile.toURI();
    final URL uploadedFileURL = uploadedFileURI.toURL();
    final WorkspaceNodeType fileNodeType = WorkspaceNodeType.RESOURCE_WRITTEN;
    final String fileMimetype = "text/plain";

    final WorkspaceNode uploadedNode = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode.setName(filename);/*from   ww  w. j a va  2  s .  c om*/
    uploadedNode.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode.setType(fileNodeType);
    uploadedNode.setFormat(fileMimetype);
    uploadedNode.setWorkspaceURL(uploadedFileURL);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();
    uploadedNodes.add(uploadedNode);

    //only one file in the collection, so only one loop cycle

    final Collection<ImportProblem> failedLinks = new ArrayList<>();

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //loop

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI));
            oneOf(mockFile1).getName();
            will(returnValue(filename));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL, filename);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype);
            will(returnValue(fileNodeType));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.TRUE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, uploadedFileURI,
                    uploadedFileURL, null, null, fileMimetype, fileNodeType, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode);

            //check links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should be empty", result.isEmpty());
}

From source file:org.gvnix.web.theme.roo.addon.ThemeOperationsImpl.java

/**
 * This method will copy the contents of a bundle to a local directory if
 * the resource does not already exist in the target directory
 * /*w  w  w.  j  ava2  s. c  o  m*/
 * TODO Duplicated code When finding bundle use URL and when finding local
 * files use URI Avoid error "unknown protocol: bundle" on commands
 * 
 * @param sourceDirectory source directory. URI syntax:
 *        [scheme:][//authority][path][?query][#fragment]
 * @param targetDirectory target directory
 * @param overwrite if true copy to target dir overwriting destination file
 * @see JspOperationsImpl#copyDirectoryContents(String, String)
 */
@SuppressWarnings("unchecked")
private void copyRecursivelyURI(URI sourceDirectory, File targetDirectory, boolean overwrite) {
    Validate.notNull(sourceDirectory, "Source URI required");
    Validate.notNull(targetDirectory, "Target directory required");

    // if source and target are the same dir, do nothing
    if (targetDirectory.toURI().equals(sourceDirectory)) {
        return;
    }

    if (!targetDirectory.exists()) {
        fileManager.createDirectory(targetDirectory.getAbsolutePath());
    }

    // Set of resource URLs to be copied to target dir
    Set<URI> uris = new HashSet<URI>();

    // if source URI schema is file:// , source files are in a local
    // repository
    if ("file".equals(sourceDirectory.getScheme())) {
        uris = FileUtils.findFilesURI(new File(sourceDirectory));
    }

    // if source URI schema is bundle:// , we can access to that bundle
    // (note the authority contains the bundle ID) and copy Theme
    // artefacts. URI example
    // bundle://8.0:0/org/gvnix/web/theme/roo/addon/themes/theme-cit/
    else if ("bundle".equals(sourceDirectory.getScheme())) {
        String uriAuthority = sourceDirectory.getAuthority();
        long bundleId = Long.parseLong(uriAuthority.substring(0, uriAuthority.indexOf(".")));

        // iterate over bundle entries in the given URI path and add them
        // to URLs to be copied to target dir
        Enumeration<URL> entries = context.getBundle(bundleId).findEntries(sourceDirectory.getPath(), "*.*",
                true);
        while (entries.hasMoreElements()) {
            try {
                uris.add(entries.nextElement().toURI());
            } catch (URISyntaxException e) {
                throw new IllegalStateException(
                        "Encountered an error during copying of resources for MVC Theme addon.", e);
            }
        }
    }
    // it shouldn't occur
    else {
        throw new IllegalArgumentException("Could not determine schema for resources for source dir '"
                .concat(sourceDirectory.toString()).concat("'"));
    }

    Validate.notNull(uris, "No resources found to copy in '".concat(sourceDirectory.toString()).concat("'"));

    // iterate over Theme resources and copy them with same dir layout
    for (URI uri : uris) {
        // Remove source directory prefix from absolute url: relative file
        // path
        String filePath = uri.toString().substring(sourceDirectory.toString().length());
        if (isVersionControlSystemFile(filePath)) {
            // nothing to do if the URL is of a file from a Version Control
            // System
            continue;
        }
        File targetFile = new File(targetDirectory, filePath);

        try {
            // only copy files and if target file doesn't exist or overwrite
            // flag is true
            if (!targetFile.exists()) {

                // create file using FileManager to fire creation events
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = uri.toURL().openStream();
                    outputStream = fileManager.createFile(targetFile.getAbsolutePath()).getOutputStream();
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
            // if file exists and overwrite is true, update the file
            else if (overwrite) {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = uri.toURL().openStream();
                    outputStream = fileManager.updateFile(targetFile.getAbsolutePath()).getOutputStream();
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Encountered an error during copying of resources for MVC Theme addon.", e);
        }
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the final {@linkplain URI#isAbsolute() absolute} {@link URL} for the
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxied} file by resolving the
 * relative {@linkplain #getProxiedFileLocalURI(Page.Request, Channel.Mode, boolean) proxied file local URI} against
 * the {@linkplain #getProxiedBaseURI(Page.Request) base URI}, and if the result isn't absolute, against the
 * {@linkplain ConfigManager#getContextResourceLocalHostURI(UriInfo, String, Map, String, boolean) local host context}
 * ./*from  w  ww.  jav a 2s. co  m*/
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param validate Should any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent folder} or
 * {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions be evaluated?
 * @return The proxied file {@link URL}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 * @see #PROXIED_FILE_URL_HOOK
 */
protected URL getProxiedFileURL(final Page.Request pageRequest, final Mode mode, final boolean validate)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final Object[] context = new Object[] { mode, Boolean.valueOf(validate) };
    URL proxiedFileURL = PROXIED_FILE_URL_HOOK.value(plugins, context, pageRequest);
    if (proxiedFileURL == null) {

        try {
            final URI proxiedFileLocalURI = getProxiedFileLocalURI(pageRequest, mode, validate);
            final URI baseURI = getProxiedBaseURI(pageRequest);
            if (proxiedFileLocalURI != null) {

                final URI proxiedFileURI = baseURI.resolve(proxiedFileLocalURI);
                if (proxiedFileURI.isAbsolute()) {
                    proxiedFileURL = proxiedFileURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager
                            .getContextResourceLocalHostURI(pageRequest.getUriInfo(), proxiedFileURI.getPath(),
                                    NetUtil.getQueryParams(proxiedFileURI), proxiedFileURI.getFragment(), true)
                            .toURL();
                }

            } else {

                if (baseURI.isAbsolute()) {
                    proxiedFileURL = baseURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager.getContextResourceLocalHostURI(pageRequest.getUriInfo(),
                            baseURI.getPath(), NetUtil.getQueryParams(baseURI), baseURI.getFragment(), true)
                            .toURL();
                }

            }
        } catch (MalformedURLException mue) {
            throw new WWWEEEPortal.SoftwareException(mue);
        }

    }
    proxiedFileURL = PROXIED_FILE_URL_HOOK
            .requireFilteredResult(PROXIED_FILE_URL_HOOK.filter(plugins, context, pageRequest, proxiedFileURL));
    return proxiedFileURL;
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processTwoUploadedFiles() throws IOException, WorkspaceNodeNotFoundException, URISyntaxException,
        WorkspaceException, NodeNotFoundException, TypeCheckerException {

    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final String filename1 = "someFile.txt";
    final File uploadedFile1 = new File(workspaceUploadDirectory, filename1);
    final URI uploadedFileURI1 = uploadedFile1.toURI();
    final URL uploadedFileURL1 = uploadedFileURI1.toURL();
    final WorkspaceNodeType fileNodeType1 = WorkspaceNodeType.RESOURCE_WRITTEN;
    final String fileMimetype1 = "text/plain";

    final String filename2 = "someOtherFile.jpg";
    final File uploadedFile2 = new File(workspaceUploadDirectory, filename2);
    final URI uploadedFileURI2 = uploadedFile2.toURI();
    final URL uploadedFileURL2 = uploadedFileURI2.toURL();
    final WorkspaceNodeType fileNodeType2 = WorkspaceNodeType.RESOURCE_IMAGE;
    final String fileMimetype2 = "image/jpeg";

    final WorkspaceNode uploadedNode1 = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode1.setName(filename1);//from w ww  . ja  v a 2 s .c  o  m
    uploadedNode1.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode1.setType(fileNodeType1);
    uploadedNode1.setFormat(fileMimetype1);
    uploadedNode1.setWorkspaceURL(uploadedFileURL1);

    final WorkspaceNode uploadedNode2 = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode2.setName(filename2);
    uploadedNode2.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode2.setType(fileNodeType2);
    uploadedNode2.setFormat(fileMimetype2);
    uploadedNode2.setWorkspaceURL(uploadedFileURL2);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);
    uploadedFiles.add(mockFile2);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();
    uploadedNodes.add(uploadedNode1);
    uploadedNodes.add(uploadedNode2);

    //two files in the collection, so two loop cycles

    final Collection<ImportProblem> failedLinks = new ArrayList<>();

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //first loop cycle

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI1));
            oneOf(mockFile1).getName();
            will(returnValue(filename1));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL1, filename1);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename1));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype1));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype1);
            will(returnValue(fileNodeType1));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null,
                    uploadedFileURL1, null, null, fileMimetype1, fileNodeType1, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode1));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode1);

            //second loop cycle

            oneOf(mockFile2).toURI();
            will(returnValue(uploadedFileURI2));
            oneOf(mockFile2).getName();
            will(returnValue(filename2));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL2, filename2);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile2).getName();
            will(returnValue(filename2));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype2));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype2);
            will(returnValue(fileNodeType2));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile2);
            will(returnValue(Boolean.FALSE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null,
                    uploadedFileURL2, null, null, fileMimetype2, fileNodeType2, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode2));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode2);

            //check links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should be empty", result.isEmpty());
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processTwoUploadedFiles_LinkingFailed() throws IOException, WorkspaceNodeNotFoundException,
        URISyntaxException, WorkspaceException, NodeNotFoundException, TypeCheckerException {

    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final String filename1 = "someFile.txt";
    final File uploadedFile1 = new File(workspaceUploadDirectory, filename1);
    final URI uploadedFileURI1 = uploadedFile1.toURI();
    final URL uploadedFileURL1 = uploadedFileURI1.toURL();
    final WorkspaceNodeType fileNodeType1 = WorkspaceNodeType.RESOURCE_WRITTEN;
    final String fileMimetype1 = "text/plain";

    final String filename2 = "someOtherFile.jpg";
    final File uploadedFile2 = new File(workspaceUploadDirectory, filename2);
    final URI uploadedFileURI2 = uploadedFile2.toURI();
    final URL uploadedFileURL2 = uploadedFileURI2.toURL();
    final WorkspaceNodeType fileNodeType2 = WorkspaceNodeType.RESOURCE_IMAGE;
    final String fileMimetype2 = "image/jpeg";

    final WorkspaceNode uploadedNode1 = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode1.setName(filename1);//w  ww.j a va 2  s  . c om
    uploadedNode1.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode1.setType(fileNodeType1);
    uploadedNode1.setFormat(fileMimetype1);
    uploadedNode1.setWorkspaceURL(uploadedFileURL1);

    final WorkspaceNode uploadedNode2 = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode2.setName(filename2);
    uploadedNode2.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode2.setType(fileNodeType2);
    uploadedNode2.setFormat(fileMimetype2);
    uploadedNode2.setWorkspaceURL(uploadedFileURL2);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);
    uploadedFiles.add(mockFile2);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();
    uploadedNodes.add(uploadedNode1);
    uploadedNodes.add(uploadedNode2);

    //two files in the collection, so two loop cycles

    final Collection<ImportProblem> failedLinks = new ArrayList<>();
    failedLinks.add(mockUploadProblem);

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //first loop cycle

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI1));
            oneOf(mockFile1).getName();
            will(returnValue(filename1));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL1, filename1);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename1));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype1));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype1);
            will(returnValue(fileNodeType1));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null,
                    uploadedFileURL1, null, null, fileMimetype1, fileNodeType1, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode1));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode1);

            //second loop cycle

            oneOf(mockFile2).toURI();
            will(returnValue(uploadedFileURI2));
            oneOf(mockFile2).getName();
            will(returnValue(filename2));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL2, filename2);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile2).getName();
            will(returnValue(filename2));

            oneOf(mockTypecheckedResults).getCheckedMimetype();
            will(returnValue(fileMimetype2));
            oneOf(mockNodeUtil).convertMimetype(fileMimetype2);
            will(returnValue(fileNodeType2));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile2);
            will(returnValue(Boolean.FALSE));

            oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null,
                    uploadedFileURL2, null, null, fileMimetype2, fileNodeType2, WorkspaceNodeStatus.UPLOADED,
                    Boolean.FALSE);
            will(returnValue(uploadedNode2));

            oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode2);

            //check links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertFalse("Collection with failed uploads should not be empty", result.isEmpty());
    assertTrue("Collection with failed uploads different from expected", result.containsAll(failedLinks));
}

From source file:org.mobicents.servlet.restcomm.cache.DiskCache.java

private URI cache(final Object message) throws IOException, URISyntaxException {
    final DiskCacheRequest request = (DiskCacheRequest) message;

    if (request.hash() == null) {
        if (request.uri().getScheme().equalsIgnoreCase("file")) {
            File origFile = new File(request.uri());
            File destFile = new File(location + origFile.getName());
            if (!destFile.exists())
                FileUtils.moveFile(origFile, destFile);

            return URI.create(this.uri + destFile.getName());

        } else {// ww  w .ja  v a  2 s .  c o m
            //Handle all the rest
            // This is a request to cache a URI
            String hash = null;
            URI uri = null;
            if (request.uri().toString().contains("hash")) {
                String fragment = request.uri().getFragment();
                hash = fragment.replace("hash=", "");
                String uriStr = ((request.uri().toString()).replace(fragment, "")).replace("#", "");
                uri = URI.create(uriStr);
            } else {
                uri = request.uri();
                hash = new Sha256Hash(uri.toString()).toHex();
            }

            final String extension = extension(uri).toLowerCase();
            final File path = new File(location + hash + "." + extension);
            if (!path.exists()) {
                final File tmp = new File(path + "." + "tmp");
                InputStream input = null;
                OutputStream output = null;
                HttpClient client = null;
                HttpResponse httpResponse = null;
                try {
                    if (request.uri().getScheme().equalsIgnoreCase("https")) {
                        //Handle the HTTPS URIs
                        client = CustomHttpClientBuilder.build(RestcommConfiguration.getInstance().getMain());
                        URI result = new URIBuilder().setScheme(uri.getScheme()).setHost(uri.getHost())
                                .setPort(uri.getPort()).setPath(uri.getPath()).build();

                        HttpGet httpRequest = new HttpGet(result);
                        httpResponse = client.execute((HttpUriRequest) httpRequest);
                        int code = httpResponse.getStatusLine().getStatusCode();

                        if (code >= 400) {
                            String requestUrl = httpRequest.getRequestLine().getUri();
                            String errorReason = httpResponse.getStatusLine().getReasonPhrase();
                            String httpErrorMessage = String.format(
                                    "Error while fetching http resource: %s \n Http error code: %d \n Http error message: %s",
                                    requestUrl, code, errorReason);
                            logger.warning(httpErrorMessage);
                        }
                        input = httpResponse.getEntity().getContent();
                    } else {
                        input = uri.toURL().openStream();
                    }
                    output = new FileOutputStream(tmp);
                    final byte[] buffer = new byte[4096];
                    int read = 0;
                    do {
                        read = input.read(buffer, 0, 4096);
                        if (read > 0) {
                            output.write(buffer, 0, read);
                        }
                    } while (read != -1);
                    tmp.renameTo(path);
                } finally {
                    if (input != null) {
                        input.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                    if (httpResponse != null) {
                        ((CloseableHttpResponse) httpResponse).close();
                        httpResponse = null;
                    }
                    if (client != null) {
                        HttpClientUtils.closeQuietly(client);
                        client = null;
                    }
                }
            }
            URI result = URI.create(this.uri + hash + "." + extension);
            return result;
        }
    } else {
        // This is a check cache request
        final String extension = "wav";
        final String hash = request.hash();
        final String filename = hash + "." + extension;
        Path p = Paths.get(location + filename);

        if (Files.exists(p)) {
            // return URI.create(matchedFile.getAbsolutePath());
            return URI.create(this.uri + filename);
        } else {
            throw new FileNotFoundException(filename);
        }
    }
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processOneUploadedMetadataFile_ValidatorException() throws MalformedURLException,
        WorkspaceNodeNotFoundException, NodeNotFoundException, TypeCheckerException, IOException,
        MetadataException, CMDIValidatorInitException, MetadataValidationException, WorkspaceException {

    final String filename = "someFile.cmdi";
    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final File uploadedFile = new File(workspaceUploadDirectory, filename);
    final URI uploadedFileURI = uploadedFile.toURI();
    final URI uploadedFileArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final URL uploadedFileURL = uploadedFileURI.toURL();
    final WorkspaceNodeType fileType = WorkspaceNodeType.METADATA;
    final String fileMimetype = "text/x-cmdi-xml";

    final WorkspaceNode uploadedNode = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode.setName(filename);/*from w w  w . j  a v  a  2s  .c om*/
    uploadedNode.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode.setType(fileType);
    uploadedNode.setFormat(fileMimetype);
    uploadedNode.setWorkspaceURL(uploadedFileURL);
    uploadedNode.setArchiveURI(uploadedFileArchiveURI);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();

    final String expectedErrorMessage = "Problems with the metadata validation when processing [" + filename
            + "]";

    //only one file in the collection, so only one loop cycle

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //loop

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI));
            oneOf(mockFile1).getName();
            will(returnValue(filename));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL, filename);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockMetadataAPI).getMetadataDocument(uploadedFileURL);
            will(returnValue(mockMetadataDocument));

            oneOf(mockWorkspaceFileValidator).triggerSchemaValidationForFile(workspaceID, mockFile1);
            will(throwException(mockCMDIValidatorInitException));
            ignoring(mockCMDIValidatorInitException);
            oneOf(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));
            oneOf(mockWorkspaceFileHandler).deleteFile(mockFile1);

            //still calls method to process links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should be empty", result.size() == 1);

    ImportProblem problem = result.iterator().next();

    assertTrue("Upload problem different from expected", problem instanceof FileImportProblem);
    assertEquals("File added to the upload problem is different from expected", mockFile1,
            ((FileImportProblem) problem).getProblematicFile());
    assertEquals("Reason for failure of file upload is different from expected", expectedErrorMessage,
            ((FileImportProblem) problem).getErrorMessage());
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processOneUploadedMetadataFile_MetadataFileNotValid()
        throws IOException, WorkspaceNodeNotFoundException, URISyntaxException, WorkspaceException,
        NodeNotFoundException, TypeCheckerException, Exception {

    final String filename = "someFile.cmdi";
    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final File uploadedFile = new File(workspaceUploadDirectory, filename);
    final URI uploadedFileURI = uploadedFile.toURI();
    final URI uploadedFileArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final URL uploadedFileURL = uploadedFileURI.toURL();
    final WorkspaceNodeType fileType = WorkspaceNodeType.METADATA;
    final String fileMimetype = "text/x-cmdi-xml";

    final WorkspaceNode uploadedNode = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode.setName(filename);//from  ww  w.jav  a  2 s.  c  o m
    uploadedNode.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode.setType(fileType);
    uploadedNode.setFormat(fileMimetype);
    uploadedNode.setWorkspaceURL(uploadedFileURL);
    uploadedNode.setArchiveURI(uploadedFileArchiveURI);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);

    final Collection<MetadataValidationIssue> issues = new ArrayList<>();
    issues.add(mockValidationIssue1);

    final String validationIssuesString = "Metadata file [" + filename + "] is invalid";

    final MetadataValidationException expectedException = new MetadataValidationException(
            validationIssuesString, workspaceID, null);
    expectedException.addValidationIssues(issues);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();

    final String expectedErrorMessage = "Metadata file [" + filename + "] is invalid";

    //only one file in the collection, so only one loop cycle

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //loop

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI));
            oneOf(mockFile1).getName();
            will(returnValue(filename));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL, filename);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));
            oneOf(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockMetadataAPI).getMetadataDocument(uploadedFileURL);
            will(returnValue(mockMetadataDocument));

            oneOf(mockWorkspaceFileValidator).triggerSchemaValidationForFile(workspaceID, mockFile1);
            will(throwException(expectedException));
            oneOf(mockWorkspaceFileValidator)
                    .validationIssuesToString(with(equivalentValidationIssueCollection(issues)));
            will(returnValue(validationIssuesString));
            oneOf(mockWorkspaceFileValidator)
                    .validationIssuesContainErrors(with(equivalentValidationIssueCollection(issues)));
            will(returnValue(Boolean.TRUE));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));
            oneOf(mockWorkspaceFileHandler).deleteFile(mockFile1);

            //still calls method to process links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should be empty", result.size() == 1);

    ImportProblem problem = result.iterator().next();

    assertTrue("Upload problem different from expected", problem instanceof FileImportProblem);
    assertEquals("File added to the upload problem is different from expected", mockFile1,
            ((FileImportProblem) problem).getProblematicFile());
    assertEquals("Reason for failure of file upload is different from expected", expectedErrorMessage,
            ((FileImportProblem) problem).getErrorMessage());
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java

@Test
public void processOneUploadedMetadataFile_withOneValidationIssue_Error()
        throws IOException, WorkspaceNodeNotFoundException, URISyntaxException, WorkspaceException,
        NodeNotFoundException, TypeCheckerException, Exception {

    final String filename = "someFile.cmdi";
    final URI workspaceTopNodeArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi");
    final File uploadedFile = new File(workspaceUploadDirectory, filename);
    final URI uploadedFileURI = uploadedFile.toURI();
    final URI uploadedFileArchiveURI = URI
            .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString());
    final URL uploadedFileURL = uploadedFileURI.toURL();
    final WorkspaceNodeType fileType = WorkspaceNodeType.METADATA;
    final String fileMimetype = "text/x-cmdi-xml";

    final WorkspaceNode uploadedNode = new LamusWorkspaceNode(workspaceID, null, null);
    uploadedNode.setName(filename);/*from   w w w .  ja va  2 s  . c om*/
    uploadedNode.setStatus(WorkspaceNodeStatus.UPLOADED);
    uploadedNode.setType(fileType);
    uploadedNode.setFormat(fileMimetype);
    uploadedNode.setWorkspaceURL(uploadedFileURL);
    uploadedNode.setArchiveURI(uploadedFileArchiveURI);

    final Collection<File> uploadedFiles = new ArrayList<>();
    uploadedFiles.add(mockFile1);

    final Collection<MetadataValidationIssue> issues = new ArrayList<>();
    issues.add(mockValidationIssue1);

    final String assertionErrorMessage = "[CMDI Archive Restriction] the CMD profile of this record is not allowed in the archive.";
    final String validationIssuesString = "Validation issue for file '" + filename + "' - "
            + MetadataValidationIssueSeverity.ERROR.toString() + ": " + assertionErrorMessage + ".\n";

    final MetadataValidationException expectedException = new MetadataValidationException(
            validationIssuesString, workspaceID, null);
    expectedException.addValidationIssues(issues);

    final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>();

    //only one file in the collection, so only one loop cycle

    context.checking(new Expectations() {
        {

            oneOf(mockWorkspaceDao).getWorkspace(workspaceID);
            will(returnValue(mockWorkspace));
            oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID);
            will(returnValue(mockWorkspaceTopNode));
            oneOf(mockWorkspaceTopNode).getArchiveURI();
            will(returnValue(workspaceTopNodeArchiveURI));
            oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI);
            will(returnValue(workspaceTopNodeArchiveFile));

            //loop

            allowing(mockFile1).getName();
            will(returnValue(filename));

            oneOf(mockFile1).toURI();
            will(returnValue(uploadedFileURI));
            oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL, filename);
            will(returnValue(mockTypecheckedResults));

            oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)),
                    with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class)));
            will(returnValue(Boolean.TRUE));

            oneOf(mockMetadataAPI).getMetadataDocument(uploadedFileURL);
            will(returnValue(mockMetadataDocument));

            oneOf(mockWorkspaceFileValidator).triggerSchemaValidationForFile(workspaceID, mockFile1);

            oneOf(mockWorkspaceFileValidator).triggerSchematronValidationForFile(workspaceID, mockFile1);
            will(throwException(expectedException));
            oneOf(mockWorkspaceFileValidator)
                    .validationIssuesToString(with(equivalentValidationIssueCollection(issues)));
            will(returnValue(validationIssuesString));
            oneOf(mockWorkspaceFileValidator)
                    .validationIssuesContainErrors(with(equivalentValidationIssueCollection(issues)));
            will(returnValue(Boolean.TRUE));

            oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1);
            will(returnValue(Boolean.FALSE));
            oneOf(mockWorkspaceFileHandler).deleteFile(mockFile1);

            //still calls method to process links
            oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes);
        }
    });

    Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles);

    assertNotNull("Collection with failed uploads should not be null", result);
    assertTrue("Collection with failed uploads should have one element", result.size() == 1);

    ImportProblem problem = result.iterator().next();

    assertTrue("Upload problem different from expected", problem instanceof FileImportProblem);
    assertEquals("File added to the upload problem is different from expected", mockFile1,
            ((FileImportProblem) problem).getProblematicFile());
    assertEquals("Reason for failure of file upload is different from expected", validationIssuesString.trim(),
            ((FileImportProblem) problem).getErrorMessage().trim());
}