Search in sources :

Example 6 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project knime-core by knime.

the class TableView method registerFindAction.

/**
 * Creates and registers the "Find ..." action on this component. Multiple invocation of this method have no effect
 * (lazy initialization).
 *
 * @return The non-null action representing the find task.
 * @see #registerNavigationActions()
 */
public TableAction registerFindAction() {
    if (m_findAction == null) {
        String name = "Find...";
        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
        TableAction action = new TableAction(stroke, name) {

            @Override
            public void actionPerformed(final ActionEvent e) {
                if (!hasData()) {
                    return;
                }
                if (m_searchPosition == null) {
                    initNewSearchPostion(new SearchOptions(true, false, true));
                }
                m_searchPosition.reset();
                SearchOptions searchOptions = m_searchPosition.getSearchOptions();
                boolean isSearchRowID = searchOptions.isSearchRowID();
                boolean isSearchColumnName = searchOptions.isSearchColumnName();
                boolean isSearchData = searchOptions.isSearchData();
                JCheckBox rowKeyBox = new JCheckBox("Search RowID Column", isSearchRowID);
                JCheckBox colNameBox = new JCheckBox("Search Column Names", isSearchColumnName);
                JCheckBox dataBox = new JCheckBox("Search Data", isSearchData);
                JCheckBox[] asArray = new JCheckBox[] { rowKeyBox, colNameBox, dataBox };
                rowKeyBox.addItemListener(new AtLeastOnButtonSelectedItemListener(dataBox, asArray));
                colNameBox.addItemListener(new AtLeastOnButtonSelectedItemListener(rowKeyBox, asArray));
                dataBox.addItemListener(new AtLeastOnButtonSelectedItemListener(rowKeyBox, asArray));
                JCheckBox ignoreCaseBox = new JCheckBox("Case insensitive", m_searchString.map(i -> i.isIgnoreCase()).orElse(false));
                JCheckBox regexBox = new JCheckBox("Regular Expression", m_searchString.map(i -> i.isRegex()).orElse(false));
                JPanel panel = new JPanel(new BorderLayout());
                panel.add(new JLabel("Options: "), BorderLayout.NORTH);
                JPanel centerPanel = new JPanel(new GridLayout(0, 1));
                centerPanel.add(rowKeyBox);
                centerPanel.add(colNameBox);
                centerPanel.add(dataBox);
                centerPanel.add(new JLabel());
                centerPanel.add(ignoreCaseBox);
                centerPanel.add(regexBox);
                centerPanel.add(new JLabel());
                panel.add(centerPanel, BorderLayout.CENTER);
                panel.add(new JLabel("    "), BorderLayout.WEST);
                panel.add(new JLabel("Find String: "), BorderLayout.SOUTH);
                SearchString newSearchString;
                while (true) {
                    String in = (String) JOptionPane.showInputDialog(TableView.this, panel, "Search", JOptionPane.QUESTION_MESSAGE, null, null, m_searchString.map(s -> s.getSearchString()).orElse(""));
                    if (StringUtils.isEmpty(in)) {
                        // canceled
                        return;
                    }
                    try {
                        newSearchString = new SearchString(in, ignoreCaseBox.isSelected(), regexBox.isSelected());
                        break;
                    } catch (PatternSyntaxException pse) {
                        JOptionPane.showMessageDialog(TableView.this, pse.getMessage(), "Invalid regular expression", JOptionPane.ERROR_MESSAGE);
                    }
                }
                searchOptions = new SearchOptions(rowKeyBox.isSelected(), colNameBox.isSelected(), dataBox.isSelected());
                find(newSearchString, searchOptions);
            }
        };
        registerAction(action);
        m_findAction = action;
    }
    return m_findAction;
}
Also used : Enumeration(java.util.Enumeration) Cursor(java.awt.Cursor) Point(java.awt.Point) ItemListener(java.awt.event.ItemListener) SearchOptions(org.knime.core.node.tableview.FindPosition.SearchOptions) TableCellRenderer(javax.swing.table.TableCellRenderer) StringUtils(org.apache.commons.lang3.StringUtils) GraphicsEnvironment(java.awt.GraphicsEnvironment) JCheckBoxMenuItem(javax.swing.JCheckBoxMenuItem) MouseAdapter(java.awt.event.MouseAdapter) ChangeListener(javax.swing.event.ChangeListener) BorderLayout(java.awt.BorderLayout) KeyStroke(javax.swing.KeyStroke) ScrollPaneConstants(javax.swing.ScrollPaneConstants) ChangeEvent(javax.swing.event.ChangeEvent) ItemEvent(java.awt.event.ItemEvent) PatternSyntaxException(java.util.regex.PatternSyntaxException) Font(java.awt.Font) Collection(java.util.Collection) JMenu(javax.swing.JMenu) MouseInputAdapter(javax.swing.event.MouseInputAdapter) KeyEvent(java.awt.event.KeyEvent) Component(java.awt.Component) Objects(java.util.Objects) Dimension(java.awt.Dimension) PropertyChangeListener(java.beans.PropertyChangeListener) AbstractAction(javax.swing.AbstractAction) HiLiteHandler(org.knime.core.node.property.hilite.HiLiteHandler) JCheckBox(javax.swing.JCheckBox) Optional(java.util.Optional) JTable(javax.swing.JTable) CheckUtils(org.knime.core.node.util.CheckUtils) JPanel(javax.swing.JPanel) TableContentFilter(org.knime.core.node.tableview.TableContentModel.TableContentFilter) Toolkit(java.awt.Toolkit) ListSelectionModel(javax.swing.ListSelectionModel) Rectangle(java.awt.Rectangle) ActionListener(java.awt.event.ActionListener) TableColumnModel(javax.swing.table.TableColumnModel) GraphicsDevice(java.awt.GraphicsDevice) Action(javax.swing.Action) ArrayList(java.util.ArrayList) GridLayout(java.awt.GridLayout) SwingUtilities(javax.swing.SwingUtilities) JMenuItem(javax.swing.JMenuItem) AbstractButton(javax.swing.AbstractButton) PropertyChangeEvent(java.beans.PropertyChangeEvent) JComponent(javax.swing.JComponent) TableColumn(javax.swing.table.TableColumn) JPopupMenu(javax.swing.JPopupMenu) DataTable(org.knime.core.data.DataTable) JOptionPane(javax.swing.JOptionPane) ActionEvent(java.awt.event.ActionEvent) MouseEvent(java.awt.event.MouseEvent) JScrollPane(javax.swing.JScrollPane) JLabel(javax.swing.JLabel) JRadioButtonMenuItem(javax.swing.JRadioButtonMenuItem) JViewport(javax.swing.JViewport) JPanel(javax.swing.JPanel) ActionEvent(java.awt.event.ActionEvent) JLabel(javax.swing.JLabel) SearchOptions(org.knime.core.node.tableview.FindPosition.SearchOptions) JCheckBox(javax.swing.JCheckBox) GridLayout(java.awt.GridLayout) BorderLayout(java.awt.BorderLayout) KeyStroke(javax.swing.KeyStroke) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 7 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project ORCID-Source by ORCID.

the class ActivityValidator method validateWork.

public void validateWork(Work work, SourceEntity sourceEntity, boolean createFlag, boolean isApiRequest, Visibility originalVisibility) {
    WorkTitle title = work.getWorkTitle();
    if (title == null || title.getTitle() == null || StringUtils.isEmpty(title.getTitle().getContent())) {
        throw new ActivityTitleValidationException();
    }
    if (work.getCountry() != null) {
        if (work.getCountry().getValue() == null) {
            Map<String, String> params = new HashMap<String, String>();
            String values = Arrays.stream(Iso3166Country.values()).map(element -> element.value()).collect(Collectors.joining(", "));
            params.put("type", "country");
            params.put("values", values);
            throw new ActivityTypeValidationException(params);
        }
    }
    //translated title language code
    if (title != null && title.getTranslatedTitle() != null) {
        String translatedTitle = title.getTranslatedTitle().getContent();
        String languageCode = title.getTranslatedTitle().getLanguageCode();
        if (PojoUtil.isEmpty(translatedTitle) && !PojoUtil.isEmpty(languageCode)) {
            throw new OrcidValidationException("Please specify a translated title or remove the language code");
        }
        //If translated title language code is null or invalid
        if (!PojoUtil.isEmpty(translatedTitle) && (PojoUtil.isEmpty(title.getTranslatedTitle().getLanguageCode()) || !Arrays.stream(SiteConstants.AVAILABLE_ISO_LANGUAGES).anyMatch(title.getTranslatedTitle().getLanguageCode()::equals))) {
            Map<String, String> params = new HashMap<String, String>();
            String values = Arrays.stream(SiteConstants.AVAILABLE_ISO_LANGUAGES).collect(Collectors.joining(", "));
            params.put("type", "translated title -> language code");
            params.put("values", values);
            throw new ActivityTypeValidationException(params);
        }
    }
    if (work.getWorkType() == null) {
        Map<String, String> params = new HashMap<String, String>();
        String values = Arrays.stream(WorkType.values()).map(element -> element.value()).collect(Collectors.joining(", "));
        params.put("type", "work type");
        params.put("values", values);
        throw new ActivityTypeValidationException(params);
    }
    if (!PojoUtil.isEmpty(work.getLanguageCode())) {
        if (!Arrays.stream(SiteConstants.AVAILABLE_ISO_LANGUAGES).anyMatch(work.getLanguageCode()::equals)) {
            Map<String, String> params = new HashMap<String, String>();
            String values = Arrays.stream(SiteConstants.AVAILABLE_ISO_LANGUAGES).collect(Collectors.joining(", "));
            params.put("type", "language code");
            params.put("values", values);
            throw new ActivityTypeValidationException(params);
        }
    }
    //publication date
    if (work.getPublicationDate() != null) {
        PublicationDate pd = work.getPublicationDate();
        Year year = pd.getYear();
        Month month = pd.getMonth();
        Day day = pd.getDay();
        if (year != null) {
            try {
                Integer.valueOf(year.getValue());
            } catch (NumberFormatException n) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("type", "publication date -> year");
                params.put("values", "integers");
                throw new ActivityTypeValidationException(params);
            }
            if (year.getValue().length() != 4) {
                throw new OrcidValidationException("Invalid year " + year.getValue() + " please specify a four digits value");
            }
        }
        if (month != null) {
            try {
                Integer.valueOf(month.getValue());
            } catch (NumberFormatException n) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("type", "publication date -> month");
                params.put("values", "integers");
                throw new ActivityTypeValidationException(params);
            }
            if (month.getValue().length() != 2) {
                throw new OrcidValidationException("Invalid month " + month.getValue() + " please specify a two digits value");
            }
        }
        if (day != null) {
            try {
                Integer.valueOf(day.getValue());
            } catch (NumberFormatException n) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("type", "publication date -> day");
                params.put("values", "integers");
                throw new ActivityTypeValidationException(params);
            }
            if (day.getValue().length() != 2) {
                throw new OrcidValidationException("Invalid day " + day.getValue() + " please specify a two digits value");
            }
        }
        //Check the date is valid
        boolean isYearEmpty = (year == null || year.getValue() == null) ? true : false;
        boolean isMonthEmpty = (month == null || month.getValue() == null) ? true : false;
        boolean isDayEmpty = (day == null || day.getValue() == null) ? true : false;
        if (isYearEmpty && (!isMonthEmpty || !isDayEmpty)) {
            throw new OrcidValidationException("Invalid date, please specify a year element");
        } else if (!isYearEmpty && isMonthEmpty && !isDayEmpty) {
            throw new OrcidValidationException("Invalid date, please specify a month element");
        } else if (isYearEmpty && isMonthEmpty && !isDayEmpty) {
            throw new OrcidValidationException("Invalid date, please specify a year and month elements");
        }
    }
    //citation
    if (work.getWorkCitation() != null) {
        String citation = work.getWorkCitation().getCitation();
        CitationType type = work.getWorkCitation().getWorkCitationType();
        if (type == null) {
            Map<String, String> params = new HashMap<String, String>();
            String values = Arrays.stream(CitationType.values()).map(element -> element.value()).collect(Collectors.joining(", "));
            params.put("type", "citation type");
            params.put("values", values);
            throw new ActivityTypeValidationException(params);
        }
        if (PojoUtil.isEmpty(citation)) {
            throw new OrcidValidationException("Please specify a citation or remove the parent tag");
        }
    }
    if (work.getWorkExternalIdentifiers() == null || work.getWorkExternalIdentifiers().getExternalIdentifier() == null || work.getExternalIdentifiers().getExternalIdentifier().isEmpty()) {
        throw new ActivityIdentifierValidationException();
    }
    if (work.getWorkContributors() != null) {
        WorkContributors contributors = work.getWorkContributors();
        if (!contributors.getContributor().isEmpty()) {
            for (Contributor contributor : contributors.getContributor()) {
                if (contributor.getContributorOrcid() != null) {
                    ContributorOrcid contributorOrcid = contributor.getContributorOrcid();
                    if (!PojoUtil.isEmpty(contributorOrcid.getUri())) {
                        if (!OrcidStringUtils.isValidOrcidUri(contributorOrcid.getUri())) {
                            throw new OrcidValidationException("Invalid contributor URI");
                        }
                    }
                    if (!PojoUtil.isEmpty(contributorOrcid.getPath())) {
                        if (!OrcidStringUtils.isValidOrcid(contributorOrcid.getPath())) {
                            throw new OrcidValidationException("Invalid contributor ORCID");
                        }
                    }
                }
                if (contributor.getCreditName() != null) {
                    if (PojoUtil.isEmpty(contributor.getCreditName().getContent())) {
                        throw new OrcidValidationException("Please specify a contributor credit name or remove the empty tag");
                    }
                }
                if (contributor.getContributorEmail() != null) {
                    if (PojoUtil.isEmpty(contributor.getContributorEmail().getValue())) {
                        throw new OrcidValidationException("Please specify a contributor email or remove the empty tag");
                    }
                }
            }
        }
    }
    if (work.getPutCode() != null && createFlag) {
        Map<String, String> params = new HashMap<String, String>();
        if (sourceEntity != null) {
            params.put("clientName", sourceEntity.getSourceName());
        }
        throw new InvalidPutCodeException(params);
    }
    // Check that we are not changing the visibility
    if (isApiRequest && !createFlag) {
        Visibility updatedVisibility = work.getVisibility();
        validateVisibilityDoesntChange(updatedVisibility, originalVisibility);
    }
    externalIDValidator.validateWorkOrPeerReview(work.getExternalIdentifiers());
}
Also used : FundingTitle(org.orcid.jaxb.model.record_v2.FundingTitle) Arrays(java.util.Arrays) Year(org.orcid.jaxb.model.common_v2.Year) InvalidPutCodeException(org.orcid.core.exception.InvalidPutCodeException) WorkTitle(org.orcid.jaxb.model.record_v2.WorkTitle) OrcidStringUtils(org.orcid.utils.OrcidStringUtils) ActivityTitleValidationException(org.orcid.core.exception.ActivityTitleValidationException) OrcidDuplicatedActivityException(org.orcid.core.exception.OrcidDuplicatedActivityException) Contributor(org.orcid.jaxb.model.common_v2.Contributor) ContributorOrcid(org.orcid.jaxb.model.common_v2.ContributorOrcid) Amount(org.orcid.jaxb.model.common_v2.Amount) PojoUtil(org.orcid.pojo.ajaxForm.PojoUtil) HashMap(java.util.HashMap) GroupIdRecord(org.orcid.jaxb.model.groupid_v2.GroupIdRecord) StringUtils(org.apache.commons.lang3.StringUtils) OrcidValidationException(org.orcid.core.exception.OrcidValidationException) Day(org.orcid.jaxb.model.common_v2.Day) Matcher(java.util.regex.Matcher) ActivityTypeValidationException(org.orcid.core.exception.ActivityTypeValidationException) Source(org.orcid.jaxb.model.common_v2.Source) Map(java.util.Map) VisibilityMismatchException(org.orcid.core.exception.VisibilityMismatchException) CitationType(org.orcid.jaxb.model.record_v2.CitationType) Employment(org.orcid.jaxb.model.record_v2.Employment) Funding(org.orcid.jaxb.model.record_v2.Funding) SourceEntity(org.orcid.persistence.jpa.entities.SourceEntity) PublicationDate(org.orcid.jaxb.model.common_v2.PublicationDate) Resource(javax.annotation.Resource) Month(org.orcid.jaxb.model.common_v2.Month) Collectors(java.util.stream.Collectors) WorkContributors(org.orcid.jaxb.model.record_v2.WorkContributors) ActivityIdentifierValidationException(org.orcid.core.exception.ActivityIdentifierValidationException) WorkType(org.orcid.jaxb.model.record_v2.WorkType) Iso3166Country(org.orcid.jaxb.model.common_v2.Iso3166Country) Visibility(org.orcid.jaxb.model.common_v2.Visibility) Relationship(org.orcid.jaxb.model.record_v2.Relationship) Work(org.orcid.jaxb.model.record_v2.Work) ExternalID(org.orcid.jaxb.model.record_v2.ExternalID) Pattern(java.util.regex.Pattern) PeerReview(org.orcid.jaxb.model.record_v2.PeerReview) SiteConstants(org.orcid.persistence.constants.SiteConstants) Education(org.orcid.jaxb.model.record_v2.Education) ExternalIDs(org.orcid.jaxb.model.record_v2.ExternalIDs) PeerReviewType(org.orcid.jaxb.model.record_v2.PeerReviewType) PublicationDate(org.orcid.jaxb.model.common_v2.PublicationDate) HashMap(java.util.HashMap) WorkContributors(org.orcid.jaxb.model.record_v2.WorkContributors) OrcidValidationException(org.orcid.core.exception.OrcidValidationException) Contributor(org.orcid.jaxb.model.common_v2.Contributor) ActivityTypeValidationException(org.orcid.core.exception.ActivityTypeValidationException) ActivityIdentifierValidationException(org.orcid.core.exception.ActivityIdentifierValidationException) Month(org.orcid.jaxb.model.common_v2.Month) ActivityTitleValidationException(org.orcid.core.exception.ActivityTitleValidationException) Year(org.orcid.jaxb.model.common_v2.Year) WorkTitle(org.orcid.jaxb.model.record_v2.WorkTitle) InvalidPutCodeException(org.orcid.core.exception.InvalidPutCodeException) CitationType(org.orcid.jaxb.model.record_v2.CitationType) Visibility(org.orcid.jaxb.model.common_v2.Visibility) ContributorOrcid(org.orcid.jaxb.model.common_v2.ContributorOrcid) Day(org.orcid.jaxb.model.common_v2.Day) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project jmeter by apache.

the class TimeShift method execute.

/** {@inheritDoc} */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    String dateString;
    LocalDateTime localDateTimeToShift = LocalDateTime.now(systemDefaultZoneID);
    DateTimeFormatter formatter = null;
    if (!StringUtils.isEmpty(format)) {
        try {
            formatter = dateTimeFormatterCache.get(format, key -> createFormatter((String) key));
        } catch (IllegalArgumentException ex) {
            // $NON-NLS-1$
            log.error("Format date pattern '{}' is invalid (see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)", format, ex);
            return "";
        }
    }
    if (!dateToShift.isEmpty()) {
        try {
            if (formatter != null) {
                localDateTimeToShift = LocalDateTime.parse(dateToShift, formatter);
            } else {
                localDateTimeToShift = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateToShift)), ZoneId.systemDefault());
            }
        } catch (DateTimeParseException | NumberFormatException ex) {
            // $NON-NLS-1$
            log.error("Failed to parse the date '{}' to shift", dateToShift, ex);
        }
    }
    // Check amount value to shift
    if (!StringUtils.isEmpty(amountToShift)) {
        try {
            Duration duration = Duration.parse(amountToShift);
            localDateTimeToShift = localDateTimeToShift.plus(duration);
        } catch (DateTimeParseException ex) {
            // $NON-NLS-1$
            log.error("Failed to parse the amount duration '{}' to shift (see https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-) ", amountToShift, ex);
        }
    }
    if (formatter != null) {
        dateString = localDateTimeToShift.format(formatter);
    } else {
        ZoneOffset offset = ZoneOffset.systemDefault().getRules().getOffset(localDateTimeToShift);
        dateString = String.valueOf(localDateTimeToShift.toInstant(offset).toEpochMilli());
    }
    if (!StringUtils.isEmpty(variableName)) {
        JMeterVariables vars = getVariables();
        if (vars != null) {
            // vars will be null on TestPlan
            vars.put(variableName, dateString);
        }
    }
    return dateString;
}
Also used : LocalDateTime(java.time.LocalDateTime) DateTimeFormatterBuilder(java.time.format.DateTimeFormatterBuilder) ChronoField(java.time.temporal.ChronoField) JMeterUtils(org.apache.jmeter.util.JMeterUtils) Arrays(java.util.Arrays) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) Logger(org.slf4j.Logger) Collection(java.util.Collection) LocalDateTime(java.time.LocalDateTime) LoggerFactory(org.slf4j.LoggerFactory) SampleResult(org.apache.jmeter.samplers.SampleResult) Instant(java.time.Instant) Cache(com.github.benmanes.caffeine.cache.Cache) StringUtils(org.apache.commons.lang3.StringUtils) ZoneId(java.time.ZoneId) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) CompoundVariable(org.apache.jmeter.engine.util.CompoundVariable) Year(java.time.Year) Duration(java.time.Duration) DateTimeFormatter(java.time.format.DateTimeFormatter) ZoneOffset(java.time.ZoneOffset) Sampler(org.apache.jmeter.samplers.Sampler) DateTimeParseException(java.time.format.DateTimeParseException) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) Duration(java.time.Duration) DateTimeFormatter(java.time.format.DateTimeFormatter) ZoneOffset(java.time.ZoneOffset)

Example 9 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project pact-jvm by DiUS.

the class PactBrokerLoader method loadPactsForProvider.

private List<Pact> loadPactsForProvider(final String providerName, final String tag) throws IOException {
    LOGGER.debug("Loading pacts from pact broker for provider " + providerName + " and tag " + tag);
    URIBuilder uriBuilder = new URIBuilder().setScheme(parseExpressions(pactBrokerProtocol)).setHost(parseExpressions(pactBrokerHost)).setPort(Integer.parseInt(parseExpressions(pactBrokerPort)));
    try {
        List<ConsumerInfo> consumers;
        PactBrokerClient pactBrokerClient = newPactBrokerClient(uriBuilder.build());
        if (StringUtils.isEmpty(tag)) {
            consumers = pactBrokerClient.fetchConsumers(providerName);
        } else {
            consumers = pactBrokerClient.fetchConsumersWithTag(providerName, tag);
        }
        if (failIfNoPactsFound && consumers.isEmpty()) {
            throw new NoPactsFoundException("No consumer pacts were found for provider '" + providerName + "' and tag '" + tag + "'. (URL " + pactBrokerClient.getUrlForProvider(providerName, tag) + ")");
        }
        return consumers.stream().map(consumer -> this.loadPact(consumer, pactBrokerClient.getOptions())).collect(toList());
    } catch (URISyntaxException e) {
        throw new IOException("Was not able load pacts from broker as the broker URL was invalid", e);
    }
}
Also used : PactRunnerTagListExpressionParser.parseTagListExpressions(au.com.dius.pact.provider.junit.sysprops.PactRunnerTagListExpressionParser.parseTagListExpressions) java.util(java.util) Logger(org.slf4j.Logger) Pact(au.com.dius.pact.model.Pact) ConsumerInfo(au.com.dius.pact.provider.ConsumerInfo) URIBuilder(org.apache.http.client.utils.URIBuilder) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) PactRunnerExpressionParser.parseExpressions(au.com.dius.pact.provider.junit.sysprops.PactRunnerExpressionParser.parseExpressions) StringUtils(org.apache.commons.lang3.StringUtils) Collectors.toList(java.util.stream.Collectors.toList) PactReader(au.com.dius.pact.model.PactReader) PactBrokerClient(au.com.dius.pact.provider.broker.PactBrokerClient) URI(java.net.URI) ConsumerInfo(au.com.dius.pact.provider.ConsumerInfo) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) PactBrokerClient(au.com.dius.pact.provider.broker.PactBrokerClient) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 10 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project carbon-apimgt by wso2.

the class OAuth2Authenticator method validateScopes.

/*
    * This method validates the given scope against scopes defined in the api resource
    * @param Request
    * @param ServiceMethodInfo
    * @param scopesToValidate scopes extracted from the access token
    * @return true if scope validation successful
    * */
@SuppressFBWarnings({ "DLS_DEAD_LOCAL_STORE" })
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate, String restAPIResource) throws APIMgtSecurityException {
    final boolean[] authorized = { false };
    String path = (String) request.getProperty(APIConstants.REQUEST_URL);
    String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
    if (log.isDebugEnabled()) {
        log.debug("Invoking rest api resource path " + verb + " " + path + " ");
        log.debug("LoggedIn user scopes " + scopesToValidate);
    }
    String[] scopesArr = new String[0];
    if (scopesToValidate != null) {
        scopesArr = scopesToValidate.split(" ");
    }
    if (scopesToValidate != null && scopesArr.length > 0) {
        final List<String> scopes = Arrays.asList(scopesArr);
        if (restAPIResource != null) {
            APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
            try {
                String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request, serviceMethodInfo);
                if (StringUtils.isEmpty(apiResourceDefinitionScopes)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Scope not defined in swagger for matching resource " + path + " and verb " + verb + " . Hence consider as anonymous permission and let request to continue.");
                    }
                    // scope validation gets through if no scopes found in the api definition
                    authorized[0] = true;
                } else {
                    Arrays.stream(apiResourceDefinitionScopes.split(" ")).forEach(scopeKey -> {
                        Optional<String> key = scopes.stream().filter(scp -> {
                            return scp.equalsIgnoreCase(scopeKey);
                        }).findAny();
                        if (key.isPresent()) {
                            // scope validation success if one of the
                            authorized[0] = true;
                        // apiResourceDefinitionScopes found.
                        }
                    });
                }
            } catch (APIManagementException e) {
                String message = "Error while validating scopes";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Rest API resource could not be found for request path '" + path + "'");
            }
        }
    } else {
        // scope validation gets through if access token does not contain scopes to validate
        authorized[0] = true;
    }
    if (!authorized[0]) {
        String message = "Scope validation fails for the scopes " + scopesToValidate;
        throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
    }
    return authorized[0];
}
Also used : Arrays(java.util.Arrays) TypeToken(com.google.gson.reflect.TypeToken) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) RESTAPIAuthenticator(org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator) LoggerFactory(org.slf4j.LoggerFactory) Request(org.wso2.msf4j.Request) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) StringUtils(org.apache.commons.lang3.StringUtils) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) RestApiUtil(org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) Response(org.wso2.msf4j.Response) Locale(java.util.Locale) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) Logger(org.slf4j.Logger) APIConstants(org.wso2.carbon.apimgt.rest.api.common.APIConstants) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) SystemVariableUtil(org.wso2.msf4j.util.SystemVariableUtil) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Optional(java.util.Optional) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)10 List (java.util.List)7 Collectors (java.util.stream.Collectors)5 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 Collection (java.util.Collection)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 Lists (com.google.common.collect.Lists)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 Pact (au.com.dius.pact.model.Pact)1 PactReader (au.com.dius.pact.model.PactReader)1 ConsumerInfo (au.com.dius.pact.provider.ConsumerInfo)1 PactBrokerClient (au.com.dius.pact.provider.broker.PactBrokerClient)1 PactRunnerExpressionParser.parseExpressions (au.com.dius.pact.provider.junit.sysprops.PactRunnerExpressionParser.parseExpressions)1 PactRunnerTagListExpressionParser.parseTagListExpressions (au.com.dius.pact.provider.junit.sysprops.PactRunnerTagListExpressionParser.parseTagListExpressions)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Cache (com.github.benmanes.caffeine.cache.Cache)1 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)1 ByteStreams (com.google.common.io.ByteStreams)1