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

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

Introduction

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

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:org.structr.function.FromJsonFunction.java

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

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

        if (sources[0] != null) {

            try {

                final String source = sources[0].toString();
                final Gson gson = new GsonBuilder().create();
                List<Map<String, Object>> objects = new LinkedList<>();

                if (StringUtils.startsWith(source, "[")) {

                    final List<Map<String, Object>> list = gson.fromJson(source,
                            new TypeToken<List<Map<String, Object>>>() {
                            }.getType());
                    final List<GraphObjectMap> elements = new LinkedList<>();

                    if (list != null) {

                        objects.addAll(list);
                    }//from  w  ww . ja  v a2s.c  o  m

                    for (final Map<String, Object> src : objects) {

                        final GraphObjectMap destination = new GraphObjectMap();
                        elements.add(destination);

                        recursivelyConvertMapToGraphObjectMap(destination, src, 0);
                    }

                    return elements;

                } else if (StringUtils.startsWith(source, "{")) {

                    final Map<String, Object> value = gson.fromJson(source,
                            new TypeToken<Map<String, Object>>() {
                            }.getType());
                    final GraphObjectMap destination = new GraphObjectMap();

                    if (value != null) {

                        recursivelyConvertMapToGraphObjectMap(destination, value, 0);
                    }

                    return destination;
                }

            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        return "";
    }

    return usage(ctx.isJavaScriptContext());
}

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

@Override
public void close() throws IOException {

    if (closed) {
        return;/*w ww  . j ava2 s  .  c  om*/
    }

    try (Tx tx = StructrApp.getInstance().tx()) {

        super.close();

        final String _contentType = FileHelper.getContentMimeType(thisFile);
        final PropertyMap changedProperties = new PropertyMap();

        changedProperties.put(StructrApp.key(File.class, "checksum"), FileHelper.getChecksum(file));
        changedProperties.put(StructrApp.key(File.class, "size"), file.length());
        changedProperties.put(StructrApp.key(File.class, "contentType"), _contentType);

        if (StringUtils.startsWith(_contentType, "image") || ImageHelper.isImageType(thisFile.getName())) {
            changedProperties.put(NodeInterface.type, Image.class.getSimpleName());
        }

        thisFile.unlockSystemPropertiesOnce();
        thisFile.setProperties(thisFile.getSecurityContext(), changedProperties);

        thisFile.increaseVersion();

        if (notifyIndexerAfterClosing) {
            thisFile.notifyUploadCompletion();
        }

        tx.success();

    } catch (Throwable ex) {

        logger.error("Could not determine or save checksum and size after closing file output stream", ex);

    }

    closed = true;
}

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

public OutputStream getOutputStream(final boolean notifyIndexerAfterClosing) {

    final String path = getRelativeFilePath();
    if (path != null) {

        final String filePath = FileHelper.getFilePath(path);

        try {/*w  ww .  ja v  a  2  s. c  om*/

            final java.io.File fileOnDisk = new java.io.File(filePath);
            fileOnDisk.getParentFile().mkdirs();

            // Return file output stream and save checksum and size after closing
            final FileOutputStream fos = new FileOutputStream(fileOnDisk) {

                private boolean closed = false;

                @Override
                public void close() throws IOException {

                    if (closed) {
                        return;
                    }

                    try (Tx tx = StructrApp.getInstance().tx()) {

                        super.close();

                        final String _contentType = FileHelper.getContentMimeType(FileBase.this);

                        unlockReadOnlyPropertiesOnce();
                        setProperty(checksum, FileHelper.getChecksum(FileBase.this));

                        unlockReadOnlyPropertiesOnce();
                        setProperty(size, FileHelper.getSize(FileBase.this));
                        setProperty(contentType, _contentType);

                        if (StringUtils.startsWith(_contentType, "image")
                                || ImageHelper.isImageType(getProperty(name))) {
                            setProperty(NodeInterface.type, Image.class.getSimpleName());
                        }

                        increaseVersion();

                        if (notifyIndexerAfterClosing) {
                            notifyUploadCompletion();
                        }

                        tx.success();

                    } catch (Throwable ex) {

                        logger.log(Level.SEVERE,
                                "Could not determine or save checksum and size after closing file output stream",
                                ex);

                    }

                    closed = true;
                }
            };

            return fos;

        } catch (FileNotFoundException e) {

            e.printStackTrace();
            logger.log(Level.SEVERE, "File not found: {0}", new Object[] { path });
        }

    }

    return null;

}

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

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

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

        if (sources[0] == null) {
            return "";
        }//from   w  w w  .j  av  a2s .c  om

        try {

            final String source = sources[0].toString();
            final Gson gson = new GsonBuilder().create();
            List<Map<String, Object>> objects = new LinkedList<>();

            if (StringUtils.startsWith(source, "[")) {

                final List<Map<String, Object>> list = gson.fromJson(source,
                        new TypeToken<List<Map<String, Object>>>() {
                        }.getType());
                final List<GraphObjectMap> elements = new LinkedList<>();

                if (list != null) {

                    objects.addAll(list);
                }

                for (final Map<String, Object> src : objects) {

                    final GraphObjectMap destination = new GraphObjectMap();
                    elements.add(destination);

                    recursivelyConvertMapToGraphObjectMap(destination, src, 0);
                }

                return elements;

            } else if (StringUtils.startsWith(source, "{")) {

                final Map<String, Object> value = gson.fromJson(source, new TypeToken<Map<String, Object>>() {
                }.getType());
                final GraphObjectMap destination = new GraphObjectMap();

                if (value != null) {

                    recursivelyConvertMapToGraphObjectMap(destination, value, 0);
                }

                return destination;
            }

        } catch (Throwable t) {

            logException(entity, t, sources);

        }

        return "";

    } else {

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

    }

    return usage(ctx.isJavaScriptContext());
}

From source file:org.structr.web.maintenance.deploy.FileImportVisitor.java

private void createFile(final Path path, final String fileName) throws IOException {

    String newFileUuid = null;//from   w  w  w. jav a 2  s.  c o m

    try (final Tx tx = app.tx(true, false, false)) {

        final String fullPath = harmonizeFileSeparators("/", basePath.relativize(path).toString());
        final PropertyMap fileProperties = getPropertiesForFileOrFolder(fullPath);

        if (fileProperties == null) {

            if (!fileName.startsWith(".")) {
                logger.info("Ignoring {} (not in files.json)", fullPath);
            }

        } else {

            Folder parent = null;

            if (!basePath.equals(path.getParent())) {
                final String parentPath = harmonizeFileSeparators("/",
                        basePath.relativize(path.getParent()).toString());
                parent = getExistingFolder(parentPath);
            }

            boolean skipFile = false;

            File file = app.nodeQuery(File.class).and(StructrApp.key(File.class, "parent"), parent)
                    .and(File.name, fileName).getFirst();

            if (file != null) {

                final Long checksumOfExistingFile = file.getChecksum();
                final Long checksumOfNewFile = FileHelper.getChecksum(path.toFile());

                if (checksumOfExistingFile != null && checksumOfNewFile != null
                        && checksumOfExistingFile.equals(checksumOfNewFile)) {

                    skipFile = true;

                } else {

                    // remove existing file first!
                    app.delete(file);
                }
            }

            if (!skipFile) {

                logger.info("Importing {}...", fullPath);

                try (final FileInputStream fis = new FileInputStream(path.toFile())) {

                    // create file in folder structure
                    file = FileHelper.createFile(securityContext, fis, null, File.class, fileName, parent);
                    final String contentType = file.getContentType();

                    // modify file type according to content
                    if (StringUtils.startsWith(contentType, "image")
                            || ImageHelper.isImageType(file.getProperty(name))) {

                        file.unlockSystemPropertiesOnce();
                        file.setProperties(securityContext,
                                new PropertyMap(NodeInterface.type, Image.class.getSimpleName()));
                    }

                    newFileUuid = file.getUuid();
                }
            }

            if (file != null) {

                if (fileProperties
                        .containsKey(StructrApp.key(AbstractMinifiedFile.class, "minificationSources"))) {
                    deferredFiles.add(file);
                } else {
                    file.unlockSystemPropertiesOnce();
                    file.setProperties(securityContext, fileProperties);
                }
            }

            if (newFileUuid != null) {

                final File createdFile = app.get(File.class, newFileUuid);
                String type = createdFile.getType();
                boolean isImage = createdFile instanceof Image;

                logger.debug("File {}: {}, isImage? {}", new Object[] { createdFile.getName(), type, isImage });

                if (isImage) {

                    try {
                        ImageHelper.updateMetadata(createdFile);
                        handleThumbnails((Image) createdFile);

                    } catch (Throwable t) {
                        logger.warn("Unable to update metadata: {}", t.getMessage());
                    }
                }
            }
        }

        tx.success();

    } catch (FrameworkException ex) {
        logger.error("Error occured while reading file properties " + fileName, ex);
    }
}

From source file:org.thelq.stackexchange.dbimport.Utils.java

public static String genTablePrefix(String containerName) {
    String name = containerName.trim().toLowerCase();
    if (StringUtils.isBlank(name))
        return "";
    //Hardcoded conversions
    name = StringUtils.removeEnd(name, ".7z");
    name = StringUtils.removeEnd(name, ".stackexchange.com");
    if (StringUtils.contains(name, "stackoverflow"))
        name = StringUtils.replace(name, "stackoverflow", "so");
    else if (StringUtils.contains(name, "serverfault"))
        name = StringUtils.replace(name, "serverfault", "sf");
    else if (StringUtils.containsIgnoreCase(name, "superuser"))
        name = StringUtils.replace(name, "superuser", "su");

    //Remove unnessesary extensions
    name = StringUtils.removeEnd(name, ".com");

    //Meta handling
    if (StringUtils.startsWith(name, "meta"))
        name = StringUtils.removeStart(name, "meta") + "_m";
    else if (StringUtils.startsWith(name, "meta."))
        name = StringUtils.removeStart(name, "meta.") + "_m";

    //Basic make valid for SQL
    //TODO: more validation?
    name = StringUtils.remove(name, " ");
    name = StringUtils.remove(name, ".");
    return name + "_";
}

From source file:org.xlrnet.metadict.core.storage.StorageServiceFactory.java

private void initializeDefaultConfiguration() {
    Map<String, String> properties = CommonUtils.getProperties(STORAGE_CONFIG_FILE);

    for (String key : properties.keySet()) {
        if (StringUtils.startsWith(key, "storage." + this.defaultStorageServiceName + ".")) {
            String configKey = StringUtils.removeStart(key, "storage." + this.defaultStorageServiceName + ".");
            String configValue = properties.get(key);
            this.defaultStorageConfigMap.put(configKey, configValue);
            LOGGER.debug("Detected configuration key '{}' with value '{}'", configKey, configValue);
        }/* w w w  . jav a2 s . co  m*/
    }
}

From source file:org.xlrnet.metadict.engines.heinzelnisse.HeinzelnisseEngine.java

/**
 * Extracts information from the "other"-fields of the response. This field may contain information about plural
 * forms or irregular verb forms./*  w w  w  .  j a  v a  2  s .  c o m*/
 * <p>
 * Examples:
 * <ul>
 * <li>Plural: Mtter</li>
 * <li>fl.: mdre</li>
 * <li>syn.: tschs</li>
 * <li>Dialekt (sddeutsch/sterreichisch)</li>
 * <li>presens: kommer, preteritum: kom, partisipp perfekt: kommet</li>
 * <li>bestemt form: lille, intetkjnn: lite, flertall: sm</li>
 * <li>komparativ: frre, superlativ: frrest</li>
 * <li>Komparativ: weniger, Superlativ: am wenigsten</li>
 * </ul>
 *
 * @param otherInformation
 *         The source string
 * @param builder
 *         The target builder to write into.
 */
protected void extractOtherInformation(@NotNull String otherInformation,
        @NotNull DictionaryObjectBuilder builder) {
    // Try to extract plural forms
    if (StringUtils.startsWith(otherInformation, "Plural:")
            || StringUtils.startsWith(otherInformation, "fl.:")) {
        String pluralForm = StringUtils.substringAfter(otherInformation, ":");
        builder.setAdditionalForm(GrammaticalNumber.PLURAL, StringUtils.strip(pluralForm));
    }
    // Try to extract verb forms
    else if (StringUtils.startsWith(otherInformation, "presens")) {
        extractVerbForms(otherInformation, builder);
    }
    // Try to extract adjective comparisons
    else if (StringUtils.startsWithIgnoreCase(otherInformation, "komparativ")) {
        extractComparisonForms(otherInformation, builder);
    }
    // Try to extract adjective forms
    else if (StringUtils.startsWithIgnoreCase(otherInformation, "bestemt form")) {
        extractAdjectiveForms(otherInformation, builder);
    }
    // Write to description string otherwise...
    else if (StringUtils.isNotEmpty(otherInformation)) {
        builder.setDescription(StringUtils.strip(otherInformation));
    }
}

From source file:org.xwiki.index.tree.internal.nestedpages.AbstractDocumentTreeNode.java

@Override
protected EntityReference resolve(String nodeId) {
    String prefix = this.nodeType + ':';
    if (StringUtils.startsWith(nodeId, prefix)) {
        return super.resolve("document:" + nodeId.substring(prefix.length()));
    }//  w w  w.j av a  2s .  c o  m
    return null;
}

From source file:org.xwiki.lesscss.internal.compiler.DefaultLESSCompilerTest.java

@Test
public void compileWhenError() throws Exception {
    // Mocks//  w w w. j a va 2s. c om
    LESSCompilerException expectedException = new LESSCompilerException("an exception");
    when(cachedLESSCompiler.compute(any(LESSResourceReference.class), anyBoolean(), anyBoolean(), anyBoolean(),
            any())).thenThrow(expectedException);

    // Test
    String result = mocker.getComponentUnderTest().compile(lessResourceReference, false, false, false);

    // Asserts
    assertTrue(StringUtils.startsWith(result,
            "/* org.xwiki.lesscss.compiler.LESSCompilerException: an exception"));
    assertTrue(StringUtils.endsWith(result, "*/"));
    verify(cache).set(eq(lessResourceReference), eq(skinReference), eq(colorThemeReference), eq(result));
    verify(mocker.getMockedLogger()).error(eq("Error during the compilation of the resource [{}]."),
            eq(lessResourceReference), eq(expectedException));
}