Example usage for org.apache.commons.lang StringUtils substringBefore

List of usage examples for org.apache.commons.lang StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBefore.

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:edu.monash.merc.system.scheduling.impl.TpbDataProcessor.java

private void processNextProtData(ChromType chromType, Date importedTime) {
    FTPFileGetter ftpFileGetter = new FTPFileGetter();
    String ftpHost = systemPropSettings.getPropValue(SystemPropConts.FTP_NX_SERVER_NAME);
    String ftpUserName = systemPropSettings.getPropValue(SystemPropConts.FTP_NX_USER_NAME);
    String ftpPassword = systemPropSettings.getPropValue(SystemPropConts.FTP_NX_USER_PASSWORD);
    String workingDir = systemPropSettings.getPropValue(SystemPropConts.FTP_NX_CHROMOSOME_REL_DIR);
    try {/*from   w  w w .j a  va  2 s.  c om*/
        if (ftpFileGetter.connectAndLogin(ftpHost, ftpUserName, ftpPassword)) {
            ftpFileGetter.changeToWorkingDirectory(workingDir);
            ftpFileGetter.setPassiveMode(true);
            //get all chromosome file
            Vector<String> chromosomeFiles = ftpFileGetter.listFileNames();

            //set the binary download mode
            ftpFileGetter.binary();
            InputStream chromInputStream = null;
            for (String file : chromosomeFiles) {
                if (StringUtils.contains(file, NEXTPROT_CHROME_NAME + "_" + chromType.chm() + ".xml")) {
                    String fileLastModifiedTime = ftpFileGetter.getLastModifiedTime(file);
                    logger.info(
                            "The nextprot xml file: " + file + ", last modified time: " + fileLastModifiedTime);
                    //check if the file hasn't been updated, then get the file

                    if (!checkUpToDate(DbAcType.NextProt, chromType, file, fileLastModifiedTime)) {
                        chromInputStream = ftpFileGetter.downloadFileStream(file);
                        DMFileGZipper gZipper = new DMFileGZipper();
                        String outFileName = StringUtils.substringBefore(file, ".gz");
                        String storeDir = this.downloadLocation + File.separator;
                        gZipper.unzipFile(chromInputStream, storeDir + outFileName);

                        //call completePendingCommand to to finish command
                        if (!ftpFileGetter.completePendingCommand()) {
                            ftpFileGetter.logout();
                            ftpFileGetter.disconnect();
                        }
                        FileInputStream fileInputStream = new FileInputStream(new File(storeDir + outFileName));
                        processNextProtXML(chromType, fileInputStream, importedTime, file,
                                fileLastModifiedTime);
                    } else {
                        logger.info("The nextprot xml file - " + file + " is already imported.");
                    }
                }
            }
        } else {
            logger.error("Failed to login the ftp server - " + ftpHost);
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        try {
            ftpFileGetter.logout();
            ftpFileGetter.disconnect();
        } catch (Exception ftpEx) {
            //ignore whatever caught here
        }
    }
}

From source file:eionet.cr.web.action.factsheet.FactsheetActionBean.java

/**
 * Helper method for updating dcterms:modified if the given subject has been updated (i.e. triples added or deleted).
 *
 * @param currSubj The subject's DTO as it is currently in the repository.
 * @param types The subject's RDF types.
 * @param sourceUri The graph URI where the dcterms:modified should be updated.
 * @throws DAOException if any sort of DB error happens
 *//*from w  w w  . j a v a2  s  .c o  m*/
private void updateDctModified(SubjectDTO currSubj, Collection<String> types, String sourceUri)
        throws DAOException {

    if (currSubj == null || StringUtils.isBlank(sourceUri)) {
        return;
    }

    String dctModifiedSubjectUri = null;

    if (types.contains(Subjects.DATACUBE_DATA_SET)) {
        dctModifiedSubjectUri = uri;
    } else if (types.contains(Subjects.DATACUBE_OBSERVATION)) {
        if (currSubj != null) {
            List<String> datasetUris = currSubj.getObjectValues(Predicates.DATACUBE_DATA_SET);
            if (datasetUris != null && !datasetUris.isEmpty()) {
                dctModifiedSubjectUri = datasetUris.iterator().next();
            }
        }
    } else if (uri.contains(CODELIST_SUBSTRING)) {
        String tail = StringUtils.substringAfter(uri, CODELIST_SUBSTRING);
        int i = tail.indexOf('/');
        if (i < 0) {
            dctModifiedSubjectUri = uri;
        } else {
            dctModifiedSubjectUri = StringUtils.substringBefore(uri, CODELIST_SUBSTRING) + CODELIST_SUBSTRING
                    + tail.substring(0, i);
        }
    }

    if (StringUtils.isNotBlank(dctModifiedSubjectUri)) {
        DAOFactory.get().getDao(ScoreboardSparqlDAO.class).updateDcTermsModified(dctModifiedSubjectUri,
                new Date(), sourceUri);
    }
}

From source file:com.jaxio.celerio.template.PreviousEngine.java

/**
 * return the class name given a java file.
 *///  ww  w  .  j a va  2 s.c  o m
private String convertFileNameToClassName(String filename) {
    return StringUtils.substringBefore(filename, ".java");
}

From source file:com.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java

private static String unpackJar(URL resource) {
    String file = resource.getPath();
    if (file.contains(".jar!/")) {
        s_logger.info("Unpacking zip file located within a jar file: {}", resource);
        String jarFileName = StringUtils.substringBefore(file, "!/");
        if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(5);
            if (SystemUtils.IS_OS_WINDOWS) {
                jarFileName = StringUtils.stripStart(jarFileName, "/");
            }/*from  w w w. j  ava 2 s .co  m*/
        } else if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(6);
        }
        jarFileName = StringUtils.replace(jarFileName, "%20", " ");
        String innerFileName = StringUtils.substringAfter(file, "!/");
        innerFileName = StringUtils.replace(innerFileName, "%20", " ");
        s_logger.info("Unpacking zip file found jar file: {}", jarFileName);
        s_logger.info("Unpacking zip file found zip file: {}", innerFileName);
        try {
            JarFile jar = new JarFile(jarFileName);
            JarEntry jarEntry = jar.getJarEntry(innerFileName);
            try (InputStream in = jar.getInputStream(jarEntry)) {
                File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip");
                tempFile.deleteOnExit();
                try (OutputStream out = new FileOutputStream(tempFile)) {
                    IOUtils.copy(in, out);
                }
                file = tempFile.getCanonicalPath();
            }
        } catch (IOException ex) {
            throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex);
        }
        s_logger.debug("Unpacking zip file extracted to: {}", file);
    }
    return file;
}

From source file:com.amalto.core.server.StorageAdminImpl.java

public Storage get(String storageName, StorageType type) {
    // Remove #STAGING (if any) at end of storage name
    String cleanedStorageName = StringUtils.substringBeforeLast(storageName, STAGING_SUFFIX);
    // Look up for already registered storages
    Storage storage = getRegisteredStorage(cleanedStorageName, type);
    Map<String, XSystemObjects> xDataClustersMap = XSystemObjects.getXSystemObjects(XObjectType.DATA_CLUSTER);
    if (getRegisteredStorage(SYSTEM_STORAGE, StorageType.SYSTEM) != null
            && !XSystemObjects.DC_UPDATE_PREPORT.getName().equals(cleanedStorageName)
            && !XSystemObjects.DC_CROSSREFERENCING.getName().equals(cleanedStorageName)
            && (XSystemObjects.isXSystemObject(xDataClustersMap, cleanedStorageName)
                    || cleanedStorageName.startsWith("amaltoOBJECTS"))) { //$NON-NLS-1$
        return getRegisteredStorage(SYSTEM_STORAGE, StorageType.SYSTEM);
    }/*from w  ww. j  av a  2  s .co  m*/
    if (storage == null) {
        // May get request for "StorageName/Concept" (especially in case of XML DB -> SQL migration).
        storage = getRegisteredStorage(StringUtils.substringBefore(cleanedStorageName, "/"), type); //$NON-NLS-1$
    }
    if (storage == null) {
        LOGGER.info("Container '" + cleanedStorageName + "' does not exist.");
        // If data model xsd exists on server, create storage
        MetadataRepositoryAdmin metadataRepositoryAdmin = ServerContext.INSTANCE.get()
                .getMetadataRepositoryAdmin();
        if (metadataRepositoryAdmin.exist(storageName)) {
            String dataSourceName = getDatasource(cleanedStorageName);
            storage = create(cleanedStorageName, cleanedStorageName, type, dataSourceName);
        }
    }
    return storage;
}

From source file:adalid.util.velocity.BaseBuilder.java

private void createTextFilePropertiesFile(String source, String target) {
    boolean java = StringUtils.endsWithIgnoreCase(source, ".java");
    boolean bundle = StringUtils.endsWithIgnoreCase(source, ".properties");
    File sourceFile = new File(source);
    String sourceFileName = sourceFile.getName();
    String sourceFileSimpleName = StringUtils.substringBeforeLast(sourceFileName, ".");
    String sourceFolderName = sourceFile.getParentFile().getName();
    String sourceFolderSimpleName = StringUtils.substringBeforeLast(sourceFolderName, ".");
    String sourceEntityName = getOptionalEntityName(sourceFileSimpleName, sourceFolderSimpleName);
    String properties = source.replace(projectFolderPath, velocityPlatformsTargetFolderPath) + ".properties";
    String folder = StringUtils.substringBeforeLast(properties, FS);
    String template = StringUtils.substringAfter(target, velocityFolderPath + FS).replace(FS, "/");
    String path = StringUtils.substringBeforeLast(StringUtils.substringAfter(source, projectFolderPath), FS)
            .replace(FS, "/").replace(project, PROJECT_ALIAS).replace("eclipse.settings", ".settings");
    path = replaceAliasWithRootFolderName(path);
    String pack = null;/* ww w.  ja va2  s  .  c  o  m*/
    if (java || bundle) {
        String s1 = StringUtils.substringAfter(path, SRC);
        if (StringUtils.contains(s1, PROJECT_ALIAS)) {
            String s2 = StringUtils.substringBefore(s1, PROJECT_ALIAS);
            String s3 = SRC + s2;
            String s4 = StringUtils.substringBefore(path, s3) + s3;
            String s5 = StringUtils.substringAfter(s1, PROJECT_ALIAS).replace("/", ".");
            path = StringUtils.removeEnd(s4, "/");
            pack = ROOT_PACKAGE_NAME + s5;
        }
    }
    path = finalisePath(path);
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS)
            .replace("eclipse.project", ".project");
    List<String> lines = new ArrayList<>();
    lines.add("template = " + template);
    //      lines.add("template-type = velocity");
    lines.add("path = " + path);
    if (StringUtils.isNotBlank(pack)) {
        lines.add("package = " + pack);
    }
    lines.add("file = " + file);
    if (sourceFileSimpleName.equals("eclipse") || sourceFolderSimpleName.equals("eclipse")
            || sourceFolderSimpleName.equals("nbproject")) {
        lines.add("disabled = true");
    } else if (sourceEntityName != null) {
        lines.add("disabled-when-missing = " + sourceEntityName);
    }
    if (source.endsWith(".css") || source.endsWith(".jrtx")) {
        lines.add("preserve = true");
    } else if (ArrayUtils.contains(preservableFiles, sourceFileName)) {
        lines.add("preserve = true");
    }
    lines.add("dollar.string = $");
    lines.add("pound.string = #");
    lines.add("backslash.string = \\\\");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}

From source file:com.amalto.core.server.DefaultItem.java

/**
 * Returns an ordered collection of results searched in a cluster and specifying an optional condition<br/>
 * The results are xml objects made of elements constituted by the specified viewablePaths
 *
 * @param dataClusterPOJOPK The Data Cluster where to run the query
 * @param forceMainPivot An optional pivot that will appear first in the list of pivots in the query<br>
 * : This allows forcing cartesian products: for instance Order Header vs Order Line
 * @param viewablePaths The list of elements returned in each result
 * @param whereItem The condition/*from   w  w w  . jav  a 2s.co m*/
 * @param spellThreshold The condition spell checking threshold. A negative value de-activates spell
 * @param orderBy The full path of the item user to order
 * @param direction One of {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_ASCENDING} or
 * {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_DESCENDING}
 * @param start The first item index (starts at zero)
 * @param limit The maximum number of items to return
 * @param returnCount True if total search count should be returned as first result.
 * @return The ordered list of results
 * @throws com.amalto.core.util.XtentisException In case of error in MDM code.
 */
@Override
public ArrayList<String> xPathsSearch(DataClusterPOJOPK dataClusterPOJOPK, String forceMainPivot,
        ArrayList<String> viewablePaths, IWhereItem whereItem, int spellThreshold, String orderBy,
        String direction, int start, int limit, boolean returnCount) throws XtentisException {
    try {
        if (viewablePaths.size() == 0) {
            String err = "The list of viewable xPaths must contain at least one element";
            LOGGER.error(err);
            throw new XtentisException(err);
        }
        // Check if user is allowed to read the cluster
        ILocalUser user = LocalUser.getLocalUser();
        boolean authorized = false;
        String dataModelName = dataClusterPOJOPK.getUniqueId();
        if (MDMConfiguration.getAdminUser().equals(user.getUsername())) {
            authorized = true;
        } else if (user.userCanRead(DataClusterPOJO.class, dataModelName)) {
            authorized = true;
        }
        if (!authorized) {
            throw new XtentisException("Unauthorized read access on data cluster '" + dataModelName
                    + "' by user '" + user.getUsername() + "'");
        }
        Server server = ServerContext.INSTANCE.get();
        String typeName = StringUtils.substringBefore(viewablePaths.get(0), "/"); //$NON-NLS-1$
        StorageAdmin storageAdmin = server.getStorageAdmin();
        Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName));
        MetadataRepository repository = storage.getMetadataRepository();
        ComplexTypeMetadata type = repository.getComplexType(typeName);
        UserQueryBuilder qb = from(type);
        qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository));
        qb.start(start);
        qb.limit(limit);
        if (orderBy != null) {
            List<TypedExpression> fields = UserQueryHelper.getFields(type,
                    StringUtils.substringAfter(orderBy, "/")); //$NON-NLS-1$
            if (fields == null) {
                throw new IllegalArgumentException("Field '" + orderBy + "' does not exist.");
            }
            OrderBy.Direction queryDirection;
            if ("ascending".equals(direction)) { //$NON-NLS-1$
                queryDirection = OrderBy.Direction.ASC;
            } else {
                queryDirection = OrderBy.Direction.DESC;
            }
            for (TypedExpression field : fields) {
                qb.orderBy(field, queryDirection);
            }
        }
        // Select fields
        for (String viewablePath : viewablePaths) {
            String viewableTypeName = StringUtils.substringBefore(viewablePath, "/"); //$NON-NLS-1$
            String viewableFieldName = StringUtils.substringAfter(viewablePath, "/"); //$NON-NLS-1$
            if (!viewableFieldName.isEmpty()) {
                qb.select(repository.getComplexType(viewableTypeName), viewableFieldName);
            } else {
                qb.selectId(repository.getComplexType(viewableTypeName)); // Select id if xPath is 'typeName' and not 'typeName/field'
            }
        }
        ArrayList<String> resultsAsString = new ArrayList<String>();
        StorageResults results;
        try {
            storage.begin();
            if (returnCount) {
                results = storage.fetch(qb.getSelect());
                resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            results = storage.fetch(qb.getSelect());
            DataRecordWriter writer = new DataRecordDefaultWriter();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            for (DataRecord result : results) {
                try {
                    writer.write(result, output);
                } catch (IOException e) {
                    throw new XmlServerException(e);
                }
                String document = new String(output.toByteArray());
                resultsAsString.add(document);
                output.reset();
            }
            storage.commit();
        } catch (Exception e) {
            storage.rollback();
            throw new XmlServerException(e);
        }
        return resultsAsString;
    } catch (XtentisException e) {
        throw (e);
    } catch (Exception e) {
        String err = "Unable to single search: " + ": " + e.getClass().getName() + ": "
                + e.getLocalizedMessage();
        LOGGER.error(err, e);
        throw new XtentisException(err, e);
    }
}

From source file:adalid.util.velocity.SecondBaseBuilder.java

private void createTextFilePropertiesFile(String source, String target) {
    boolean java = StringUtils.endsWithIgnoreCase(source, ".java");
    boolean bundle = StringUtils.endsWithIgnoreCase(source, ".properties");
    File sourceFile = new File(source);
    String sourceFileName = sourceFile.getName();
    String sourceFileSimpleName = StringUtils.substringBeforeLast(sourceFileName, ".");
    String sourceFolderName = sourceFile.getParentFile().getName();
    String sourceFolderSimpleName = StringUtils.substringBeforeLast(sourceFolderName, ".");
    String sourceEntityName = getOptionalEntityName(sourceFileSimpleName, sourceFolderSimpleName);
    String properties = source.replace(projectFolderPath, velocityPlatformsTargetFolderPath) + ".properties";
    String folder = StringUtils.substringBeforeLast(properties, FS);
    String template = StringUtils.substringAfter(target, velocityFolderPath + FS).replace(FS, "/");
    String path = StringUtils.substringBeforeLast(StringUtils.substringAfter(source, projectFolderPath), FS)
            .replace(FS, "/").replace(project, PROJECT_ALIAS).replace("eclipse.settings", ".settings");
    path = replaceAliasWithRootFolderName(path);
    String pack = null;/* w  ww.java 2  s .  com*/
    if (java || bundle) {
        String s1 = StringUtils.substringAfter(path, SRC);
        if (StringUtils.contains(s1, PROJECT_ALIAS)) {
            String s2 = StringUtils.substringBefore(s1, PROJECT_ALIAS);
            String s3 = SRC + s2;
            String s4 = StringUtils.substringBefore(path, s3) + s3;
            String s5 = StringUtils.substringAfter(s1, PROJECT_ALIAS).replace("/", ".");
            path = StringUtils.removeEnd(s4, "/");
            pack = ROOT_PACKAGE_NAME + s5;
        }
    }
    path = finalisePath(path);
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS)
            .replace("eclipse.project", ".project");
    List<String> lines = new ArrayList<>();
    lines.add("template = " + template);
    //      lines.add("template-type = velocity");
    lines.add("path = " + path);
    if (StringUtils.isNotBlank(pack)) {
        lines.add("package = " + pack);
    }
    lines.add("file = " + file);
    if (sourceFileSimpleName.equals("eclipse") || sourceFolderSimpleName.equals("eclipse")
            || sourceFolderSimpleName.equals("nbproject")) {
        lines.add("disabled = true");
    } else if (sourceEntityName != null) {
        lines.add("disabled-when-missing = " + sourceEntityName);
    }
    if (preservable(sourceFile)) {
        lines.add("preserve = true");
    }
    lines.add("dollar.string = $");
    lines.add("pound.string = #");
    lines.add("backslash.string = \\\\");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}

From source file:eionet.cr.dao.helpers.CsvImportHelper.java

/**
 * Extracts column labels (without language and type) from columns.
 *
 * @param rawColumns//from w  ww.j av  a2s  . co  m
 * @return
 */
private List<String> extractColumnLabels(List<String> rawColumns) {
    ArrayList<String> columnsLabelResult = new ArrayList<String>();

    for (String col : rawColumns) {
        String colLabel = StringUtils.substringBefore(col, ":").trim();
        colLabel = StringUtils.substringBefore(colLabel, "@").trim();
        columnsLabelResult.add(colLabel);
    }

    return columnsLabelResult;
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * ./*w  ww . j  a  v a2s . c o  m*/
 * 
 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain",
 * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK",
 * "no-cache:false");
 * 
 * @param headers
 *            header"encoding:""no-cache:",UTF-8true.
 */
public static void render(final String contentType, final String content, final String... headers) {
    try {
        // headers
        String encoding = ENCODING_DEFAULT;
        boolean noCache = NOCACHE_DEFAULT;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else
                throw new IllegalArgumentException(headerName + "header");
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        // headers
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
            WebUtils.setNoCacheHeader(response);
        }

        response.getWriter().write(content);
        response.getWriter().flush();

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}