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

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

Introduction

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

Prototype

public static String substringAfter(String str, String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:eionet.cr.staging.FileDownloader.java

/**
 * Derives a name for the file to be downloaded from the given {@link URLConnection}.
 *
 * @param connection The given {@link URLConnection}.
 * @return The derived file name.// www  .  j  a v  a 2s .co  m
 */
private String getFileName(URLConnection connection) {

    // If file name already given, just return it.
    if (StringUtils.isNotBlank(newFileName)) {
        return newFileName;
    }

    // Attempt detection from the response's "Content-Disposition" header.
    String contentDisposition = connection.getHeaderField("Content-Disposition");
    if (StringUtils.isNotBlank(contentDisposition)) {
        String s = StringUtils.substringAfter(contentDisposition, "filename");
        if (StringUtils.isNotBlank(s)) {
            s = StringUtils.substringAfter(s, "=");
            if (StringUtils.isNotBlank(s)) {
                s = StringUtils.substringAfter(s, "\"");
                if (StringUtils.isNotBlank(s)) {
                    s = StringUtils.substringBefore(s, "\"");
                    if (StringUtils.isNotBlank(s)) {
                        return s.trim();
                    }
                }
            }
        }
    }

    // // Attempt detection from the response's "Content-Location" header.
    // String contentLocation = connection.getHeaderField("Content-Location");
    // if (StringUtils.isNotBlank(contentLocation)) {
    // String s = new File(contentLocation).getName();
    // if (StringUtils.isNotBlank(s)) {
    // return s.trim();
    // }
    // }
    //
    // Attempt detection from the URL itself.

    String s = StringUtils.substringAfterLast(connection.getURL().toString(), "#");
    if (StringUtils.isBlank(s)) {
        s = StringUtils.substringAfterLast(connection.getURL().toString(), "/");
    }

    if (StringUtils.isNotBlank(s)) {
        // Remove all characters that are not one of these: a latin letter, a digit, a minus, a dot, an underscore.
        s = s.replaceAll("[^a-zA-Z0-9-._]+", "");
    }

    // If still no success, then just generate a hash from the URL.
    return StringUtils.isBlank(s) ? DigestUtils.md5Hex(connection.getURL().toString()) : s;
}

From source file:com.thalesgroup.hudson.plugins.cppcheck.CppcheckResult.java

/**
 * Gets the dynamic result of the selection element.
 *
 * @param link     the link to identify the sub page to show
 * @param request  Stapler request//from   w  w w  .ja v  a  2 s.c  om
 * @param response Stapler response
 * @return the dynamic result of the analysis (detail page).
 * @throws java.io.IOException if an error occurs
 */
public Object getDynamic(final String link, final StaplerRequest request, final StaplerResponse response)
        throws IOException {

    if (link.startsWith("source.")) {

        if (!owner.getProject().getACL().hasPermission(Item.WORKSPACE)) {
            response.sendRedirect2("nosourcepermission");
            return null;
        }

        Map<Integer, CppcheckWorkspaceFile> agregateMap = cppcheckSourceContainer.getInternalMap();
        if (agregateMap != null) {
            CppcheckWorkspaceFile vCppcheckWorkspaceFile = agregateMap
                    .get(Integer.parseInt(StringUtils.substringAfter(link, "source.")));
            if (vCppcheckWorkspaceFile == null) {
                throw new IllegalArgumentException("Error for retrieving the source file with link:" + link);
            }
            return new CppcheckSource(owner, vCppcheckWorkspaceFile);
        }
    }
    return null;
}

From source file:gobblin.data.management.conversion.hive.converter.HiveAvroToOrcConverterTest.java

/***
 * Test flattened DDL and DML generation
 * @throws IOException/*from w w  w  .  j a v  a2 s  . c  o  m*/
 */
@Test
public void testFlattenSchemaDDLandDML() throws Exception {
    String dbName = "testdb";
    String tableName = "testtable";
    String tableSdLoc = "/tmp/testtable";

    this.hiveMetastoreTestUtils.getLocalMetastoreClient().dropDatabase(dbName, false, true, true);

    Table table = this.hiveMetastoreTestUtils.createTestTable(dbName, tableName, tableSdLoc,
            Optional.<String>absent());
    Schema schema = ConversionHiveTestUtils.readSchemaFromJsonFile(resourceDir,
            "recordWithinRecordWithinRecord_nested.json");
    WorkUnitState wus = ConversionHiveTestUtils.createWus(dbName, tableName, 0);

    try (HiveAvroToFlattenedOrcConverter converter = new HiveAvroToFlattenedOrcConverter();) {

        Config config = ConfigFactory.parseMap(ImmutableMap.<String, String>builder()
                .put("destinationFormats", "flattenedOrc").put("flattenedOrc.destination.dbName", dbName)
                .put("flattenedOrc.destination.tableName", tableName + "_orc")
                .put("flattenedOrc.destination.dataPath", "file:" + tableSdLoc + "_orc").build());

        ConvertibleHiveDataset cd = ConvertibleHiveDatasetTest.createTestConvertibleDataset(config);

        List<QueryBasedHiveConversionEntity> conversionEntities = Lists
                .newArrayList(converter.convertRecord(converter.convertSchema(schema, wus),
                        new QueryBasedHiveConversionEntity(cd, new SchemaAwareHiveTable(table, schema)), wus));

        Assert.assertEquals(conversionEntities.size(), 1, "Only one query entity should be returned");

        QueryBasedHiveConversionEntity queryBasedHiveConversionEntity = conversionEntities.get(0);
        List<String> queries = queryBasedHiveConversionEntity.getQueries();

        Assert.assertEquals(queries.size(), 4, "4 DDL and one DML query should be returned");

        // Ignoring part before first bracket in DDL and 'select' clause in DML because staging table has
        // .. a random name component
        String actualDDLQuery = StringUtils.substringAfter("(", queries.get(0).trim());
        String actualDMLQuery = StringUtils.substringAfter("SELECT", queries.get(0).trim());
        String expectedDDLQuery = StringUtils.substringAfter("(", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.ddl"));
        String expectedDMLQuery = StringUtils.substringAfter("SELECT", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.dml"));

        Assert.assertEquals(actualDDLQuery, expectedDDLQuery);
        Assert.assertEquals(actualDMLQuery, expectedDMLQuery);
    }

}

From source file:com.enonic.cms.core.preference.PreferenceKey.java

private void initScope(String scopePart) {

    this.scopePart = scopePart;

    String scopeName;//www .  j av  a  2  s  .com
    String scopeKeyStr = null;
    if (StringUtils.contains(scopePart, ':')) {
        scopeName = StringUtils.substringBefore(scopePart, ":");
        scopeKeyStr = StringUtils.substringAfter(scopePart, ":");
    } else {
        scopeName = scopePart;
    }

    this.scopeType = PreferenceScopeType.parse(scopeName);
    if (this.scopeType == null) {
        throw new InvalidKeyException(rawKey, this.getClass(), "invalid scope");
    }

    if (scopeType != PreferenceScopeType.GLOBAL) {
        this.scopeKey = new PreferenceScopeKey(scopeKeyStr);
    }
}

From source file:adalid.util.i18n.Merger.java

private static String locale(String name) {
    String substringBeforeLast = StringUtils.substringBeforeLast(name, ".");
    String substringAfter = StringUtils.substringAfter(substringBeforeLast, "_");
    return StringUtils.trimToNull(substringAfter);
}

From source file:hydrograph.ui.expression.editor.dialogs.AddCategoreisDialog.java

public boolean createPropertyFileForSavingData() {
    IProject iProject = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject();
    IFolder iFolder = iProject.getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    FileOutputStream file = null;
    Properties properties = new Properties();
    try {/* w  w  w  .j  a v  a  2s .  c  om*/
        if (!iFolder.exists()) {
            iFolder.create(true, true, new NullProgressMonitor());
        }
        for (String items : categoriesDialogTargetComposite.getTargetList().getItems()) {
            String jarFileName = StringUtils.trim(StringUtils.substringAfter(items, Constants.DASH));
            String packageName = StringUtils.trim(StringUtils.substringBefore(items, Constants.DASH));
            properties.setProperty(packageName, jarFileName);
        }

        file = new FileOutputStream(iFolder.getLocation().toString() + File.separator
                + PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
        properties.store(file, "");
        return true;
    } catch (IOException | CoreException exception) {
        LOGGER.error("Exception occurred while saving jar file path at projects setting folder", exception);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                LOGGER.warn("Exception in closing output stream. The error message is " + e.getMessage());
            }
        }
    }
    return false;
}

From source file:com.hangum.tadpole.rdb.erd.core.dnd.TableTransferDropTargetListener.java

@Override
protected void handleDrop() {
    String strDragSource = (String) getCurrentEvent().data;
    try {// w  ww. j a v  a  2s . c  om
        String[] arrayDragSourceData = StringUtils.splitByWholeSeparator(strDragSource,
                PublicTadpoleDefine.DELIMITER);

        int sourceDBSeq = Integer.parseInt(arrayDragSourceData[0]);
        if (userDB.getSeq() != sourceDBSeq) {
            MessageDialog.openWarning(null, Messages.get().Warning,
                    Messages.get().TableTransferDropTargetListener_1); //$NON-NLS-1$
            return;
        }
    } catch (Exception e) {
        logger.error("dragger error", e); //$NON-NLS-1$
        MessageDialog.openError(null, Messages.get().Error, "Draging exception : " + e.getMessage()); //$NON-NLS-1$
        return;
    }

    final int nextTableX = getDropLocation().x;
    final int nextTableY = getDropLocation().y;

    final String strFullData = StringUtils.substringAfter(strDragSource, PublicTadpoleDefine.DELIMITER);
    final String[] arryTables = StringUtils.splitByWholeSeparator(strFullData,
            PublicTadpoleDefine.DELIMITER_DBL);
    final Map<String, List<TableColumnDAO>> mapTable = new HashMap<>();

    Job job = new Job("Painting model") {
        @Override
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Painting table object", IProgressMonitor.UNKNOWN);

            try {
                for (int i = 0; i < arryTables.length; i++) {
                    String strTable = arryTables[i];
                    monitor.subTask(String.format("Working %s/%s", i, arryTables.length));
                    String[] arryTable = StringUtils.splitByWholeSeparator(strTable,
                            PublicTadpoleDefine.DELIMITER);
                    if (arryTable.length == 0)
                        continue;

                    String schemaName = arryTable[0];
                    String tableName = arryTable[1];

                    TableDAO table = new TableDAO();
                    table.setSchema_name(schemaName);
                    table.setName(tableName);
                    table.setSysName(tableName);
                    mapTable.put(tableName, TDBDataHandler.getColumns(userDB, table));
                }

            } catch (Exception e) {
                logger.error("ERD Initialize excepiton", e);

                return new Status(Status.WARNING, Activator.PLUGIN_ID, e.getMessage());
            } finally {
                monitor.done();
            }

            /////////////////////////////////////////////////////////////////////////////////////////
            return Status.OK_STATUS;
        }
    };

    // job? event  ?.
    job.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {
            final IJobChangeEvent jobEvent = event;
            Display display = rdbEditor.getEditorSite().getShell().getDisplay();
            display.syncExec(new Runnable() {
                public void run() {

                    if (jobEvent.getResult().isOK()) {
                        paintingModel(nextTableX, nextTableY, arryTables, mapTable);
                    } else {
                        MessageDialog.openError(null, Messages.get().Error, jobEvent.getResult().getMessage());
                    }
                }
            }); // end display.asyncExec
        } // end done

    }); // end job

    job.setName(userDB.getDisplay_name());
    job.setUser(true);
    job.schedule();

}

From source file:cn.heu.hmps.util.web.Struts2Utils.java

/**
 * ?contentTypeheaders./*from w w w.j  a va2s. com*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            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) {
        ServletUtils.setDisableCacheHeader(response);
    }

    return response;
}

From source file:com.sic.bb.jenkins.plugins.sicci_for_xcode.io.OCUnitOutputParser.java

private boolean matchTestCaseStarted(String line) {
    Matcher matcher = testCaseStarted.matcher(line);

    if (!matcher.matches())
        return false;

    OCUnitTestSuite lastTestSuite = this.testSuites.lastElement();

    if (!matcher.group(1).contains(lastTestSuite.getTestSuiteName()))
        return false;

    String testCaseName = StringUtils
            .strip(StringUtils.substringAfter(matcher.group(1), lastTestSuite.getTestSuiteName()));

    this.testSuites.lastElement().addTestCase(new OCUnitTestCase(testCaseName));

    return true;//ww  w.  ja v  a  2  s .c  om
}

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

public Set<Expression> getIndexedExpressions(String dataModelName) {
    if (XSystemObjects.DM_UPDATEREPORT.getName().equals(dataModelName)) { // Indexed expressions for UpdateReport
        MetadataRepository repository = get(dataModelName);
        // Index Concept field (used in JournalStatistics for the top N types)
        ComplexTypeMetadata updateType = repository.getComplexType("Update"); //$NON-NLS-1$
        return Collections
                .singleton(from(updateType).where(isNull(updateType.getField("Concept"))).getExpression()); //$NON-NLS-1$
    }//w  w  w. ja  va  2  s  .c o  m
    synchronized (metadataRepository) {
        ViewPOJO view = null;
        try {
            MetadataRepository repository = get(dataModelName);
            View viewCtrlLocal = Util.getViewCtrlLocal();
            Set<Expression> indexedExpressions = new HashSet<Expression>();
            for (Object viewAsObject : viewCtrlLocal.getAllViews(".*")) { //$NON-NLS-1$
                UserQueryBuilder qb = null;
                view = (ViewPOJO) viewAsObject;
                ArrayList<String> searchableElements = view.getSearchableBusinessElements().getList();
                for (String searchableElement : searchableElements) {
                    String typeName = StringUtils.substringBefore(searchableElement, "/"); //$NON-NLS-1$
                    ComplexTypeMetadata userType = repository.getComplexType(typeName);
                    if (userType != null) {
                        if (qb == null) {
                            qb = from(userType);
                        } else {
                            qb.and(userType);
                        }
                        String fieldName = StringUtils.substringAfter(searchableElement, "/"); //$NON-NLS-1$
                        if (userType.hasField(fieldName)) {
                            qb.where(UserQueryBuilder.isEmpty(userType.getField(fieldName)));
                        }
                    } else {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("View '" + view.getPK().getUniqueId()
                                    + "' does not apply to data model '" + dataModelName + "'.");
                        }
                        break; // View does not apply to model
                    }
                }
                if (qb != null) {
                    for (IWhereItem condition : view.getWhereConditions().getList()) {
                        qb.where(UserQueryHelper.buildCondition(qb, condition, repository));
                    }
                    indexedExpressions.add(qb.getExpression());
                }
            }
            return indexedExpressions;
        } catch (Exception e) {
            if (view != null) {
                throw new RuntimeException("Can not use view '" + view.getPK().getUniqueId()
                        + "' with data model '" + dataModelName + "': " + e.getMessage(), e);
            } else {
                throw new RuntimeException("Could not get indexed fields.", e);
            }
        }
    }
}