Example usage for org.apache.commons.lang3 StringUtils substringAfterLast

List of usage examples for org.apache.commons.lang3 StringUtils substringAfterLast

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringAfterLast.

Prototype

public static String substringAfterLast(final String str, final String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.structr.schema.SchemaService.java

private static void updateIndexConfiguration(final Map<String, Map<String, PropertyKey>> removedClasses) {

    final Thread indexUpdater = new Thread(new Runnable() {

        @Override/*from   ww  w. j  av a 2s  .  co  m*/
        public void run() {

            // critical section, only one thread should update the index at a time
            if (updating.compareAndSet(false, true)) {

                try {

                    final DatabaseService graphDb = StructrApp.getInstance().getDatabaseService();

                    final Map<String, Map<String, Boolean>> schemaIndexConfig = new HashMap();
                    final Map<String, Map<String, Boolean>> removedClassesConfig = new HashMap();

                    for (final Entry<String, Map<String, PropertyKey>> entry : StructrApp.getConfiguration()
                            .getTypeAndPropertyMapping().entrySet()) {

                        final Class type = getType(entry.getKey());
                        if (type != null) {

                            final String typeName = type.getSimpleName();

                            final Boolean alreadySeenType = schemaIndexConfig.containsKey(typeName);
                            final Map<String, Boolean> typeConfig = (alreadySeenType
                                    ? schemaIndexConfig.get(typeName)
                                    : new HashMap());

                            if (!alreadySeenType) {
                                schemaIndexConfig.put(typeName, typeConfig);
                            }

                            for (final PropertyKey key : entry.getValue().values()) {

                                boolean createIndex = key.isIndexed() || key.isIndexedWhenEmpty();

                                createIndex &= !NonIndexed.class.isAssignableFrom(type);
                                createIndex &= NodeInterface.class.equals(type) || !GraphObject.id.equals(key);

                                typeConfig.put(key.dbName(), createIndex);
                            }
                        }
                    }

                    for (final Entry<String, Map<String, PropertyKey>> entry : removedClasses.entrySet()) {

                        final String typeName = StringUtils.substringAfterLast(entry.getKey(), ".");

                        final Map<String, Boolean> typeConfig = new HashMap();
                        removedClassesConfig.put(typeName, typeConfig);

                        for (final PropertyKey key : entry.getValue().values()) {

                            final boolean wasIndexed = key.isIndexed() || key.isIndexedWhenEmpty();
                            final boolean wasIdIndex = GraphObject.id.equals(key);
                            final boolean dropIndex = wasIndexed && !wasIdIndex;

                            typeConfig.put(key.dbName(), dropIndex);
                        }
                    }

                    graphDb.updateIndexConfiguration(schemaIndexConfig, removedClassesConfig);

                } finally {

                    updating.set(false);
                }
            }
        }
    });

    indexUpdater.setName("indexUpdater");
    indexUpdater.setDaemon(true);
    indexUpdater.start();
}

From source file:org.structr.schema.SchemaService.java

private static Class getType(final String name) {

    try {/*from   w ww. j  av a2 s  .c  o m*/
        return Class.forName(name);
    } catch (ClassNotFoundException ignore) {
    }

    // fallback: use dynamic class from simple name
    return StructrApp.getConfiguration().getNodeEntityClass(StringUtils.substringAfterLast(name, "."));
}

From source file:org.structr.web.common.TestHelper.java

public static void testViews(final App app, final InputStream specificationSource,
        final Map<String, List<String>> additionalRequiredAttributes) {

    final Map<String, Map<String, List<String>>> viewMap = new LinkedHashMap<>();
    final Map<String, List<String>> requiredAttributes = new LinkedHashMap<>();
    final Map<String, List<String>> baseMap = new LinkedHashMap<>();
    boolean fail = false;

    baseMap.put("ui", Arrays.asList("id", "type", "name", "owner", "createdBy", "hidden", "createdDate",
            "lastModifiedDate", "visibleToPublicUsers", "visibleToAuthenticatedUsers"));
    baseMap.put("_html_", Arrays.asList("_html_data", "_html_is", "_html_properties"));
    baseMap.put("public", Arrays.asList("id", "type"));

    requiredAttributes.put("DynamicResourceAccess", Arrays.asList("signature", "i:flags"));
    requiredAttributes.put("Localization", Arrays.asList("locale"));
    requiredAttributes.put("ResourceAccess", Arrays.asList("signature", "i:flags"));

    // insert required attributes specified by test class
    if (additionalRequiredAttributes != null) {

        for (final Entry<String, List<String>> entry : additionalRequiredAttributes.entrySet()) {

            final String key = entry.getKey();
            final List<String> add = entry.getValue();

            List<String> list = requiredAttributes.get(key);
            if (list != null) {

                list.addAll(add);/*from  w w w  .ja  va 2  s  .  c  om*/

            } else {

                requiredAttributes.put(key, add);
            }
        }
    }

    // load specs
    try (final InputStream is = specificationSource) {

        // build view map from specification
        for (final String line : IOUtils.readLines(is, "utf-8")) {

            if (StringUtils.isNotBlank(line) && line.contains("=") && !line.trim().startsWith("#")) {

                // format is Type.viewName = list of property names
                final String[] parts = line.split("=");
                final String[] keyParts = parts[0].split("\\.");
                final String type = keyParts[0];
                final String viewName = keyParts[1];

                Map<String, List<String>> typeMap = viewMap.get(type);
                if (typeMap == null) {

                    typeMap = new LinkedHashMap<>();
                    viewMap.put(type, typeMap);
                }

                // "empty"views are possible too
                if (parts.length == 2) {

                    final String[] valueParts = parts[1].split(",");
                    final List<String> list = new LinkedList<>(Arrays.asList(valueParts));
                    final List<String> base = baseMap.get(viewName);

                    // common properties
                    if (base != null) {

                        list.addAll(base);
                    }

                    typeMap.put(viewName, list);
                }
            }
        }

    } catch (IOException ioex) {
        throw new AssertionError("Unable to load view specification: " + ioex.getMessage());
    }

    // create test user
    try (final Tx tx = app.tx()) {

        app.create(User.class, new NodeAttribute<>(StructrApp.key(User.class, "name"), "admin"),
                new NodeAttribute<>(StructrApp.key(User.class, "password"), "admin"),
                new NodeAttribute<>(StructrApp.key(User.class, "isAdmin"), true));

        tx.success();

    } catch (FrameworkException fex) {
        fex.printStackTrace();
        throw new AssertionError("Unexpected exception");
    }

    // create an instance of each of the internal types and check the views
    for (final Entry<String, Map<String, List<String>>> entry : viewMap.entrySet()) {

        final String typeName = entry.getKey();
        final Map<String, List<String>> typeMap = entry.getValue();
        final Class type = SchemaHelper.getEntityClassForRawType(typeName);

        if (type != null) {

            // only test node types for now..
            if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()
                    && !RelationshipInterface.class.isAssignableFrom(type)) {

                final String body = createPostBody(requiredAttributes.get(typeName));

                // create entity
                final String uuid = StringUtils.substringAfterLast(
                        RestAssured.given().header("X-User", "admin").header("X-Password", "admin")
                                //.filter(RequestLoggingFilter.logRequestTo(System.out))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(401))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(403))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(404))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(422))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(500)).body(body)
                                .expect().statusCode(201).when().post("/" + typeName).header("Location"),
                        "/");

                for (final Entry<String, List<String>> view : typeMap.entrySet()) {

                    final String viewName = view.getKey();
                    final List<String> keys = view.getValue();

                    // check entity
                    final Map<String, Object> result = RestAssured.given().header("X-User", "admin")
                            .header("X-Password", "admin").expect().statusCode(200).when()
                            .get("/" + typeName + "/" + uuid + "/" + viewName).andReturn().body().as(Map.class);

                    final Map<String, Object> item = (Map<String, Object>) result.get("result");
                    final Set<String> expectedKeys = new TreeSet<>(keys);
                    final Set<String> itemKeySet = item.keySet();

                    expectedKeys.removeAll(itemKeySet);

                    if (!expectedKeys.isEmpty()) {

                        System.out.println(type.getSimpleName() + "." + viewName
                                + " is missing the following keys: " + expectedKeys);
                        fail = true;
                    }

                    expectedKeys.clear();
                    expectedKeys.addAll(keys);

                    itemKeySet.removeAll(expectedKeys);

                    if (!itemKeySet.isEmpty()) {

                        System.out.println(type.getSimpleName() + "." + viewName
                                + " contains keys that are not listed in the specification: " + itemKeySet);
                        fail = true;
                    }
                }
            }
        }
    }

    if (fail) {
        throw new AssertionError(
                "View configuration does not match expected configuration, see log output for details.");
    }
}

From source file:org.structr.web.entity.dom.Page.java

@Override
public boolean move(FtpFile target) {
    try (Tx tx = StructrApp.getInstance().tx()) {

        logger.log(Level.INFO, "move()");

        final AbstractStructrFtpFile targetFile = (AbstractStructrFtpFile) target;
        final String path = targetFile instanceof StructrFtpFile ? "/" : targetFile.getAbsolutePath();

        try {/*from  www  .j a  v a  2  s . c  o m*/

            if (!("/".equals(path))) {
                final String newName = path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path;
                setProperty(AbstractNode.name, newName);
            }

        } catch (FrameworkException ex) {
            logger.log(Level.SEVERE, "Could not move ftp file", ex);
            return false;
        }

        tx.success();

        return true;
    } catch (FrameworkException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:org.structr.web.entity.File.java

static InputStream getInputStream(final File thisFile) {

    final java.io.File fileOnDisk = thisFile.getFileOnDisk();

    try {/* www. ja  va2  s. c  o m*/

        final FileInputStream fis = new FileInputStream(fileOnDisk);
        final SecurityContext securityContext = thisFile.getSecurityContext();

        if (thisFile.isTemplate()) {

            boolean editModeActive = false;
            if (securityContext.getRequest() != null) {

                final String editParameter = securityContext.getRequest().getParameter("edit");
                if (editParameter != null) {

                    editModeActive = !RenderContext.EditMode.NONE.equals(RenderContext.editMode(editParameter));
                }
            }

            if (!editModeActive) {

                final String content = IOUtils.toString(fis, "UTF-8");

                // close input stream here
                fis.close();

                try {

                    final String result = Scripting.replaceVariables(new ActionContext(securityContext),
                            thisFile, content);

                    String encoding = "UTF-8";

                    final String cType = getContentType();
                    if (cType != null) {

                        final String charset = StringUtils.substringAfterLast(cType, "charset=").trim()
                                .toUpperCase();
                        try {
                            if (!"".equals(charset) && Charset.isSupported(charset)) {
                                encoding = charset;
                            }
                        } catch (IllegalCharsetNameException ice) {
                            logger.warn("Charset is not supported '{}'. Using 'UTF-8'", charset);
                        }
                    }

                    return IOUtils.toInputStream(result, encoding);

                } catch (Throwable t) {

                    logger.warn("Scripting error in {}:\n{}\n{}", thisFile.getUuid(), content, t.getMessage());
                }
            }
        }

        return fis;

    } catch (IOException ex) {
        logger.warn("Unable to open input stream for {}: {}", fileOnDisk.getPath(), ex.getMessage());
    }

    return null;
}

From source file:org.structr.web.function.IncludeFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    try {/*from   ww  w.  j  a  v  a  2s  .c  o m*/

        if (!(arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String)) {

            return null;
        }

        final SecurityContext securityContext = entity != null ? entity.getSecurityContext()
                : ctx.getSecurityContext();
        final App app = StructrApp.getInstance(securityContext);
        final RenderContext innerCtx = new RenderContext((RenderContext) ctx);
        final List<DOMNode> nodeList = app.nodeQuery(DOMNode.class).andName((String) sources[0]).getAsList();

        DOMNode node = null;

        /**
         * Nodes can be included via their name property These nodes MUST: 1. be unique in name 2. NOT be in the trash => have an ownerDocument AND a parent (public
         * users are not allowed to see the __ShadowDocument__ ==> this check must either be made in a superuser-context OR the __ShadowDocument could be made public?)
         *
         * These nodes can be: 1. somewhere in the pages tree 2. in the shared components 3. both ==> causes a problem because we now have multiple nodes with the same
         * name (one shared component and multiple linking instances of that component)
         *
         * INFOS:
         *
         * - If a DOMNode has "syncedNodes" it MUST BE a shared component - If a DOMNodes "sharedComponent" is set it MUST BE AN INSTANCE of a shared component => Can
         * we safely ignore these? I THINK SO!
         */
        for (final DOMNode n : nodeList) {

            // Ignore nodes in trash
            if (n.getProperty(DOMNode.parent) == null && n.getOwnerDocumentAsSuperUser() == null) {
                continue;
            }

            // IGNORE everything that REFERENCES a shared component!
            if (n.getProperty(DOMNode.sharedComponent) == null) {

                // the DOMNode is either a shared component OR a named node in the pages tree
                if (node == null) {

                    node = n;

                } else {

                    // ERROR: we have found multiple DOMNodes with the same name
                    // TODO: Do we need to remove the nodes from the nodeList which can be ignored? (references to a shared component)
                    return "Ambiguous node name \"" + ((String) sources[0]) + "\" (nodes found: "
                            + StringUtils.join(nodeList, ", ") + ")";

                }

            }

        }

        if (node != null) {

            node.render(innerCtx, 0);

        } else {

            final FileBase file = app.nodeQuery(FileBase.class).andName((String) sources[0]).getFirst();

            if (file != null) {

                final String name = file.getProperty(NodeInterface.name);
                final String contentType = file.getProperty(FileBase.contentType);
                final String charset = StringUtils.substringAfterLast(contentType, "charset=");
                final String extension = StringUtils.substringAfterLast(name, ".");

                if (contentType == null || StringUtils.isBlank(extension)) {

                    logger.log(Level.WARNING,
                            "No valid file type detected. Please make sure {0} has a valid content type set or file extension. Parameters: {1}",
                            new Object[] { name, getParametersAsString(sources) });
                    return "No valid file type detected. Please make sure " + name
                            + " has a valid content type set or file extension.";

                }

                if (contentType.startsWith("text/css")) {

                    return "<link href=\"" + file.getPath() + "\" rel=\"stylesheet\">";

                } else if (contentType.contains("/javascript")) {

                    return "<script src=\"" + file.getPath() + "\"></script>";

                } else if (contentType.startsWith("image/svg")) {

                    try {

                        final byte[] buffer = new byte[file.getSize().intValue()];
                        IOUtils.read(file.getInputStream(), buffer);
                        return StringUtils.toEncodedString(buffer, Charset.forName(charset));

                    } catch (IOException ex) {

                        logger.log(Level.WARNING, "Exception for parameters: {0}",
                                getParametersAsString(sources));
                        logger.log(Level.SEVERE, "", ex);

                    }

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else if (contentType.startsWith("image/")) {

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else {

                    logger.log(Level.WARNING,
                            "Don't know how to render content type or extension of {0}. Parameters: {1}",
                            new Object[] { name, getParametersAsString(sources) });
                    return "Don't know how to render content type or extension of  " + name + ".";

                }

            }

        }

        return StringUtils.join(innerCtx.getBuffer().getQueue(), "");

    } catch (final IllegalArgumentException e) {

        logParameterError(entity, sources, ctx.isJavaScriptContext());

        return usage(ctx.isJavaScriptContext());

    }
}

From source file:org.structr.web.importer.Importer.java

private Linkable downloadFile(final String downloadAddress, final URL base) {

    URL downloadUrl = null;/*  w w w  . j av  a  2  s. c  om*/

    try {

        downloadUrl = new URL(base, downloadAddress);

    } catch (MalformedURLException ex) {

        logger.error("Could not resolve address {}", address != null ? address.concat("/") : "");
        return null;
    }

    final String alreadyDownloadedKey = downloadUrl.getPath();

    // Don't download the same file twice
    if (alreadyDownloaded.containsKey(alreadyDownloadedKey)) {
        return alreadyDownloaded.get(alreadyDownloadedKey);
    }

    long size;
    long checksum;
    String contentType;
    java.io.File tmpFile;

    try {
        // create temporary file on disk
        final Path tmpFilePath = Files.createTempFile("structr", "download");
        tmpFile = tmpFilePath.toFile();

    } catch (IOException ioex) {

        logger.error("Unable to create temporary file for download, aborting.");
        return null;
    }

    try {

        logger.info("Starting download from {}", downloadUrl);

        copyURLToFile(downloadUrl.toString(), tmpFile);

    } catch (IOException ioe) {

        if (originalUrl == null || address == null) {

            logger.info("Cannot download from {} without base address", downloadAddress);
            return null;

        }

        logger.warn("Unable to download from {} {}", new Object[] { originalUrl, downloadAddress });

        try {
            // Try alternative baseUrl with trailing "/"
            if (address.endsWith("/")) {

                // don't append a second slash!
                logger.info("Starting download from alternative URL {} {} {}",
                        new Object[] { originalUrl, address, downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address), downloadAddress);

            } else {

                // append a slash
                logger.info("Starting download from alternative URL {} {} {}",
                        new Object[] { originalUrl, address.concat("/"), downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress);
            }

            copyURLToFile(downloadUrl.toString(), tmpFile);

        } catch (MalformedURLException ex) {
            logger.error("Could not resolve address {}", address.concat("/"));
            return null;
        } catch (IOException ex) {
            logger.warn("Unable to download from {}", address.concat("/"));
            return null;
        }

        logger.info("Starting download from alternative URL {}", downloadUrl);

    }

    //downloadAddress = StringUtils.substringBefore(downloadAddress, "?");
    final String downloadName = cleanFileName(downloadUrl.getFile());
    final String fileName = PathHelper.getName(downloadName);

    if (StringUtils.isBlank(fileName)) {

        logger.warn("Can't figure out filename from download address {}, aborting.", downloadAddress);

        return null;
    }

    // TODO: Add security features like null/integrity/virus checking before copying it to
    // the files repo
    try {

        contentType = FileHelper.getContentMimeType(tmpFile, fileName);
        checksum = FileHelper.getChecksum(tmpFile);
        size = tmpFile.length();

    } catch (IOException ioe) {

        logger.warn("Unable to determine MIME type, size or checksum of {}", tmpFile);
        return null;
    }

    logger.info("Download URL: {}, address: {}, cleaned address: {}, filename: {}",
            new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName });

    String relativePath = StringUtils.substringAfter(downloadUrl.toString(),
            StringUtils.substringBeforeLast(address, "/"));
    if (StringUtils.isBlank(relativePath)) {

        relativePath = downloadAddress;
    }

    final String path;
    final String httpPrefix = "http://";
    final String httpsPrefix = "https://";
    final String flexiblePrefix = "//";

    if (downloadAddress.startsWith(httpsPrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpsPrefix)), "/");

    } else if (downloadAddress.startsWith(httpPrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpPrefix)), "/");

    } else if (downloadAddress.startsWith(flexiblePrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, flexiblePrefix)), "/");

    } else {

        path = StringUtils.substringBeforeLast(relativePath, "/");
    }

    logger.info("Relative path: {}, final path: {}", relativePath, path);

    if (contentType.equals("text/plain")) {

        contentType = StringUtils.defaultIfBlank(
                contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain");
    }

    try {

        final String fullPath = path + "/" + fileName;

        File fileNode = fileExists(fullPath, checksum);
        if (fileNode == null) {

            if (ImageHelper.isImageType(fileName)) {

                fileNode = createImageNode(fullPath, contentType, size, checksum);

            } else {

                fileNode = createFileNode(fullPath, contentType, size, checksum);
            }

            final java.io.File imageFile = fileNode.getFileOnDisk(false);
            final Path imagePath = imageFile.toPath();

            // rename / move file to final location
            Files.move(tmpFile.toPath(), imagePath);

            if (contentType.equals("text/css")) {

                processCssFileNode(fileNode, downloadUrl);
            }

            // set export flag according to user preference
            fileNode.setProperty(StructrApp.key(File.class, "includeInFrontendExport"), includeInExport);

        } else {

            tmpFile.delete();
        }

        alreadyDownloaded.put(alreadyDownloadedKey, fileNode);
        return fileNode;

    } catch (final FrameworkException | IOException ex) {

        logger.warn("Could not create file node.", ex);

    }

    return null;

}

From source file:org.structr.web.Importer.java

private Linkable downloadFile(String downloadAddress, final URL base) {

    final String uuid = UUID.randomUUID().toString().replaceAll("[\\-]+", "");
    String contentType;//from  w w w.ja  va  2s  . c om

    // Create temporary file with new uuid
    // FIXME: This is much too dangerous!
    final String relativeFilePath = File.getDirectoryPath(uuid) + "/" + uuid;
    final String filePath = FileHelper.getFilePath(relativeFilePath);
    final java.io.File fileOnDisk = new java.io.File(filePath);

    fileOnDisk.getParentFile().mkdirs();

    long size;
    long checksum;
    URL downloadUrl;

    try {

        downloadUrl = new URL(base, downloadAddress);

        logger.log(Level.INFO, "Starting download from {0}", downloadUrl);

        copyURLToFile(downloadUrl.toString(), fileOnDisk);

    } catch (IOException ioe) {

        if (originalUrl == null || address == null) {

            logger.log(Level.INFO, "Cannot download from {0} without base address", downloadAddress);
            return null;

        }

        logger.log(Level.WARNING, "Unable to download from {0} {1}",
                new Object[] { originalUrl, downloadAddress });
        ioe.printStackTrace();

        try {
            // Try alternative baseUrl with trailing "/"
            if (address.endsWith("/")) {

                // don't append a second slash!
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address, downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address), downloadAddress);

            } else {

                // append a slash
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address.concat("/"), downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress);
            }

            copyURLToFile(downloadUrl.toString(), fileOnDisk);

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, "Could not resolve address {0}", address.concat("/"));
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.log(Level.WARNING, "Unable to download from {0}", address.concat("/"));
            return null;
        }

        logger.log(Level.INFO, "Starting download from alternative URL {0}", downloadUrl);

    }

    downloadAddress = StringUtils.substringBefore(downloadAddress, "?");
    final String fileName = PathHelper.getName(downloadAddress);

    if (StringUtils.isBlank(fileName)) {

        logger.log(Level.WARNING, "Can't figure out filename from download address {0}, aborting.",
                downloadAddress);

        return null;
    }

    // TODO: Add security features like null/integrity/virus checking before copying it to
    // the files repo
    try {

        contentType = FileHelper.getContentMimeType(fileOnDisk, fileName);
        size = fileOnDisk.length();
        checksum = FileUtils.checksumCRC32(fileOnDisk);

    } catch (IOException ioe) {

        logger.log(Level.WARNING, "Unable to determine MIME type, size or checksum of {0}", fileOnDisk);
        return null;
    }

    String httpPrefix = "http://";

    logger.log(Level.INFO, "Download URL: {0}, address: {1}, cleaned address: {2}, filename: {3}",
            new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName });

    String relativePath = StringUtils.substringAfter(downloadUrl.toString(),
            StringUtils.substringBeforeLast(address, "/"));
    if (StringUtils.isBlank(relativePath)) {
        relativePath = downloadAddress;
    }

    final String path = StringUtils.substringBefore(
            ((downloadAddress.contains(httpPrefix)) ? StringUtils.substringAfter(downloadAddress, "http://")
                    : relativePath),
            fileName);

    logger.log(Level.INFO, "Relative path: {0}, final path: {1}", new Object[] { relativePath, path });

    if (contentType.equals("text/plain")) {

        contentType = StringUtils.defaultIfBlank(
                contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain");
    }

    final String ct = contentType;

    try {

        FileBase fileNode = fileExists(fileName, checksum);
        if (fileNode == null) {

            if (ImageHelper.isImageType(fileName)) {

                fileNode = createImageNode(uuid, fileName, ct, size, checksum);
            } else {

                fileNode = createFileNode(uuid, fileName, ct, size, checksum);
            }

            if (fileNode != null) {

                Folder parent = FileHelper.createFolderPath(securityContext, path);

                if (parent != null) {

                    fileNode.setProperty(File.parent, parent);

                }

                if (contentType.equals("text/css")) {

                    processCssFileNode(fileNode, downloadUrl);
                }

                if (!fileNode.validatePath(securityContext, null)) {
                    fileNode.setProperty(AbstractNode.name,
                            fileName.concat("_").concat(FileHelper.getDateString()));
                }

            }

            return fileNode;

        } else {

            fileOnDisk.delete();
            return fileNode;
        }

    } catch (FrameworkException | IOException fex) {

        logger.log(Level.WARNING, "Could not create file node.", fex);

    }

    return null;

}

From source file:org.structr.websocket.command.UnarchiveCommand.java

@Override
public void processMessage(WebSocketMessage webSocketData) {

    final Set<String> supportedByArchiveStreamFactory = new HashSet<>(
            Arrays.asList(new String[] { ArchiveStreamFactory.AR, ArchiveStreamFactory.ARJ,
                    ArchiveStreamFactory.CPIO, ArchiveStreamFactory.DUMP, ArchiveStreamFactory.JAR,
                    ArchiveStreamFactory.TAR, ArchiveStreamFactory.ZIP }));

    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final App app = StructrApp.getInstance(securityContext);

    try {/* w  w w .ja  v  a2  s  . c  om*/

        final String id = (String) webSocketData.getId();
        final File file;

        try (final Tx tx = app.tx()) {

            file = app.get(File.class, id);

            if (file == null) {
                getWebSocket().send(
                        MessageBuilder.status().code(400).message("File not found: ".concat(id)).build(), true);
                return;
            }

            final String fileExtension = StringUtils.substringAfterLast(file.getName(), ".");
            if (!supportedByArchiveStreamFactory.contains(fileExtension)) {

                getWebSocket().send(MessageBuilder.status().code(400)
                        .message("Unsupported archive format: ".concat(fileExtension)).build(), true);
                return;
            }

            tx.success();
        }

        // no transaction here since this is a bulk command
        unarchive(securityContext, file);

    } catch (Throwable t) {

        t.printStackTrace();

        String msg = t.toString();

        try (final Tx tx = app.tx()) {

            // return error message
            getWebSocket().send(
                    MessageBuilder.status().code(400)
                            .message("Could not unarchive file: ".concat((msg != null) ? msg : "")).build(),
                    true);

            tx.success();

        } catch (FrameworkException ignore) {
        }

    }
}

From source file:org.talend.commons.utils.VersionUtils.java

public static String getMojoVersion(String mojoKey) {
    String version = null;//w  ww  .  j a  v  a2  s .c  om
    String talendVersion = getTalendVersion();
    Properties properties = new Properties();
    File file = new Path(Platform.getConfigurationLocation().getURL().getPath())
            .append("mojo_version.properties").toFile(); //$NON-NLS-1$
    if (file.exists()) {
        try (InputStream inStream = new FileInputStream(file)) {
            properties.load(inStream);
            version = properties.getProperty(mojoKey);
        } catch (IOException e) {
            ExceptionHandler.process(e);
        }
        if (version != null && !version.startsWith(talendVersion)) {
            ExceptionHandler.process(new Exception(
                    "Incompatible Mojo version:" + mojoKey + "[" + version + "], use default version.")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            version = null;
        }
    }
    // default version
    if (StringUtils.isBlank(version)) {
        version = talendVersion;
        if (CommonsPlugin.isJUnitTest()) {
            productVersion = null;
        }
        String productVersion = getInternalVersion();
        String revision = StringUtils.substringAfterLast(productVersion, "-"); //$NON-NLS-1$
        if (("SNAPSHOT").equals(revision) || Pattern.matches("M\\d{1}", revision)) { //$NON-NLS-1$ //$NON-NLS-2$
            version += "-" + revision; //$NON-NLS-1$
        }
    }
    return version;
}