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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:org.eclipse.gyrex.common.console.SubCommand.java

/**
 * Answer a string (may be as many lines as you like) with help texts that
 * explain the command.//  w  w w .j  a v a 2  s  .c  om
 * <p>
 * The default implementation returns a list of registered commands
 * including their descriptions).
 * </p>
 * 
 * @see org.eclipse.osgi.framework.console.CommandProvider#getHelp()
 */
public String getHelp() {
    final StrBuilder help = new StrBuilder(512);
    if (null == parentCommandName) {
        help.append("---").append(getClass().getSimpleName()).appendln("---");
        help.append("\t").append(getCommandName()).appendln(" <cmd> [args]");
    } else {
        help.append("\t").append(parentCommandName).append(' ').append(getCommandName())
                .appendln(" <cmd> [args]");
    }
    for (final String name : commands.keySet()) {
        try {
            help.append("\t\t").append(name);
            final Command command = commands.get(name).newInstance();
            //            final CmdLineParser parser = new CmdLineParser(command);
            final String description = command.getDescription();
            if (!StringUtils.contains(description, " - ")) {
                help.append(" - ");
            } else if (!StringUtils.startsWith(description, " ")) {
                help.append(' ');
            }
            help.appendln(description);
            //            help.append("\t\t\t");
            //            parser.printSingleLineUsage(help.asWriter(), null);
            //            help.appendNewLine();
        } catch (final Exception e) {
            help.append("\t\t").append(name).append(" - ").appendln(ExceptionUtils.getRootCauseMessage(e));
        }
    }
    return help.toString();
}

From source file:org.eclipse.gyrex.jobs.internal.manager.JobManagerImpl.java

private static String findCaller() {
    final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    if (trace.length == 0)
        return StringUtils.EMPTY;

    // find first _none_ jobs API call
    for (int i = 0; i < trace.length; i++) {
        if (StringUtils.startsWith(trace[i].getClassName(), JobManagerImpl.class.getName())) {
            continue;
        }//from   w  w  w. j ava  2  s .co m
        return trace[i].toString();
    }

    return StringUtils.EMPTY;
}

From source file:org.eclipse.gyrex.jobs.internal.scheduler.SchedulingJob.java

/**
 * Queues a Gyrex job based on data in a Quartz JobDataMap.
 * //from w ww .ja  v  a  2  s. co  m
 * @param dataMap
 * @throws Exception
 */
public static void queueJob(final JobDataMap dataMap) throws Exception {
    final String jobId = dataMap.getString(PROP_JOB_ID);
    final String jobTypeId = dataMap.getString(PROP_JOB_TYPE_ID);
    final String jobContextPath = dataMap.getString(PROP_JOB_CONTEXT_PATH);
    final String scheduleId = dataMap.getString(PROP_SCHEDULE_ID);
    final String scheduleEntryId = dataMap.getString(PROP_SCHEDULE_ENTRY_ID);
    final String scheduleEntriesToTriggerAfterRun = dataMap
            .getString(PROP_SCHEDULE_ENTRIES_TO_TRIGGER_AFTER_RUN);
    final Boolean enabled = dataMap.containsKey(PROP_ENABLED) ? dataMap.getBooleanValue(PROP_ENABLED) : null;
    final String queueId = StringUtils.isNotBlank(dataMap.getString(PROP_QUEUE_ID))
            ? dataMap.getString(PROP_QUEUE_ID)
            : IJobManager.DEFAULT_QUEUE;

    // check if enabled
    // (note, we must keep this here because there are multiple entry paths)
    if ((null != enabled) && !enabled) {
        LOG.debug(String.format("Skipping execution of job '%s' - entry is not enabled", jobId));
        return;
    }

    // parse path
    final IPath contextPath = new Path(jobContextPath);

    // populate map
    final Map<String, String> parameter = new HashMap<String, String>();
    for (final Object keyObj : dataMap.keySet()) {
        if (!(keyObj instanceof String)) {
            continue;
        }
        final String key = (String) keyObj;
        if (!StringUtils.startsWith(key, INTERNAL_PROP_PREFIX)) {
            final Object value = dataMap.get(key);
            if (value instanceof String) {
                parameter.put(key, (String) value);
            }
        }
    }

    // get context
    final IRuntimeContext runtimeContext = JobsActivator.getInstance().getService(IRuntimeContextRegistry.class)
            .get(contextPath);
    if (null == runtimeContext) {
        LOG.error("Unable to find context (using path {}) for job {}.", jobContextPath, jobId);
        return;
    }

    // get job manager
    final IJobManager jobManager = runtimeContext.get(IJobManager.class);
    if (!(jobManager instanceof JobManagerImpl)) {
        LOG.error("Invalid job manager ({}). Please verify the system is setup properly.", jobManager);
        return;
    }
    final JobManagerImpl jobManagerImpl = (JobManagerImpl) jobManager;

    // check that job state is NONE (and it's not stuck) if one exists
    final JobImpl job = jobManagerImpl.getJob(jobId);
    if ((job != null) && (job.getState() != JobState.NONE) && !jobManagerImpl.isStuck(job)) {
        LOG.warn(
                "Job {} (type {}) cannot be queued because it is already active in the system (current state {}).",
                new Object[] { job.getId(), job.getTypeId(), job.getState() });
        return;
    }

    // check that queue exists
    final IQueueService queueService = JobsActivator.getInstance().getQueueService();
    IQueue queue = queueService.getQueue(queueId, null);
    if (queue == null) {
        queue = queueService.createQueue(queueId, null);
    }

    // queue job (create it if necessary)
    jobManagerImpl.queueJob(jobTypeId, jobId, parameter, queue.getId(),
            String.format("Schedule '%s' entry '%s'.", scheduleId, scheduleEntryId),
            createScheduleInfo(scheduleId, scheduleEntryId, scheduleEntriesToTriggerAfterRun));
}

From source file:org.eclipse.jubula.client.ui.rcp.validator.TestDataCubeReferenceValidator.java

/**
 * {@inheritDoc}//from w  ww  .  ja  v a 2  s.c  o  m
 */
public ValidationState validateInput(VerifyEvent e) {
    Text txt = (Text) e.widget;
    StringBuilder workValue = new StringBuilder(txt.getText());
    workValue.replace(e.start, e.end, e.text);
    String newValue = workValue.toString();
    boolean mightMatch = false;
    for (IParameterInterfacePO dataCube : TestDataCubeBP.getAllTestDataCubesFor(m_project)) {
        if (StringUtils.equals(e.text, dataCube.getName())) {
            return ValidationState.OK;
        }
        if (!mightMatch && StringUtils.startsWith(dataCube.getName(), newValue)) {
            mightMatch = true;
        }
    }

    if (mightMatch) {
        return ValidationState.MightMatchAccept;
    }

    return ValidationState.MightMatchReject;
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.parser.CommonRpcParser.java

/**
 * Assembles a datapoint with the given parameters.
 *//*  w  w  w  .ja  v  a  2 s  .  co  m*/
protected HmDatapoint assembleDatapoint(String name, String unit, String type, String[] options, Object min,
        Object max, Integer operations, Object defaultValue, HmParamsetType paramsetType, boolean isHmIpDevice)
        throws IOException {
    HmDatapoint dp = new HmDatapoint();
    dp.setName(name);
    dp.setDescription(name);
    dp.setUnit(StringUtils.replace(StringUtils.trimToNull(unit), "\ufffd", ""));
    if (dp.getUnit() == null && StringUtils.startsWith(dp.getName(), "RSSI_")) {
        dp.setUnit("dBm");
    }

    HmValueType valueType = HmValueType.parse(type);
    if (valueType == null || valueType == HmValueType.UNKNOWN) {
        throw new IOException("Unknown datapoint type: " + type);
    }
    dp.setType(valueType);

    dp.setOptions(options);
    if (dp.isNumberType() || dp.isEnumType()) {
        if (isHmIpDevice && dp.isEnumType()) {
            dp.setMinValue(dp.getOptionIndex(toString(min)));
            dp.setMaxValue(dp.getOptionIndex(toString(max)));
        } else {
            dp.setMinValue(toNumber(min));
            dp.setMaxValue(toNumber(max));
        }
    }
    dp.setReadOnly((operations & 2) != 2);
    dp.setReadable((operations & 1) == 1);
    dp.setParamsetType(paramsetType);
    if (isHmIpDevice && dp.isEnumType()) {
        dp.setDefaultValue(dp.getOptionIndex(toString(defaultValue)));
    } else {
        dp.setDefaultValue(convertToType(dp, defaultValue));
    }
    dp.setValue(dp.getDefaultValue());
    return dp;
}

From source file:org.eclipse.smarthome.binding.homematic.internal.type.MetadataUtils.java

/**
 * Loads the standard datapoints for channel metadata generation.
 *//* ww  w.  j a  v  a 2s  .  com*/
private static void loadStandardDatapoints() {
    Bundle bundle = FrameworkUtil.getBundle(MetadataUtils.class);
    try (InputStream stream = bundle.getResource("homematic/standard-datapoints.properties").openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {

        String line;
        while ((line = reader.readLine()) != null) {
            if (StringUtils.trimToNull(line) != null && !StringUtils.startsWith(line, "#")) {
                String channelType = StringUtils.trimToNull(StringUtils.substringBefore(line, "|"));
                String datapointName = StringUtils.trimToNull(StringUtils.substringAfter(line, "|"));

                Set<String> channelDatapoints = standardDatapoints.get(channelType);
                if (channelDatapoints == null) {
                    channelDatapoints = new HashSet<String>();
                    standardDatapoints.put(channelType, channelDatapoints);
                }

                channelDatapoints.add(datapointName);
            }
        }
    } catch (IllegalStateException | IOException e) {
        logger.warn("Can't load standard-datapoints.properties file!", e);
    }
}

From source file:org.eclipse.wb.internal.core.DesignerPlugin.java

/**
 * We should not allow user code to terminate JVM.
 *///from  ww  w .j a  v a 2 s  . c  o m
public static void installSecurityManager() {
    System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkPermission(java.security.Permission perm) {
            if (isExitVM(perm)) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                for (StackTraceElement element : stackTrace) {
                    String className = element.getClassName();
                    String methodName = element.getMethodName();
                    // ignore this class, because it has our class name prefix
                    if (className.equals(getClass().getName())) {
                        continue;
                    }
                    // ignore JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    if (className.equals("javax.swing.JFrame")
                            && methodName.equals("setDefaultCloseOperation")) {
                        return;
                    }
                    // prevent exit() from user invoked by "designer"
                    if (className.startsWith("org.eclipse.wb.")
                            || className.startsWith("com.google.gdt.eclipse.designer.")
                            || className.startsWith("net.rim.ejde.designer.")
                            || className.startsWith("java.awt.EventQueue")) {
                        // we often use test_exit() method as point to stop tests, allow it
                        if (methodName.startsWith("test_") && methodName.endsWith("_exit")) {
                            return;
                        }
                        // prevent exit()
                        throw new SecurityException("Exit from within user-loaded code");
                    }
                }
            }
        }

        private boolean isExitVM(java.security.Permission perm) {
            return perm instanceof RuntimePermission && StringUtils.startsWith(perm.getName(), "exitVM");
        }
    });
}

From source file:org.eclipse.wb.internal.core.model.property.category.PropertyCategory.java

/**
 * Parses {@link PropertyCategory} from strings. Supported strings are:
 * //from   w  ww  . j  a v a 2  s. co m
 * <ul>
 * <li><b>normal</b></li>
 * <li><b>preferred</b></li>
 * <li><b>advanced</b></li>
 * <li><b>advanced-really</b></li>
 * <li><b>hidden</b></li>
 * <li><b>system(number)</b></li>
 * </ul>
 * 
 * @param defaultCategory
 *          the {@link PropertyCategory} to use if given string can not be parsed, or
 *          <code>null</code> if exception should be thrown.
 * 
 * @return the parsed {@link PropertyCategory}.
 */
public static PropertyCategory get(String text, PropertyCategory defaultCategory) {
    // simple
    if (StringUtils.equals(text, "normal")) {
        return NORMAL;
    }
    if (StringUtils.equals(text, "preferred")) {
        return PREFERRED;
    }
    if (StringUtils.equals(text, "advanced")) {
        return ADVANCED;
    }
    if (StringUtils.equals(text, "advanced-really")) {
        return ADVANCED_REALLY;
    }
    if (StringUtils.equals(text, "hidden")) {
        return HIDDEN;
    }
    // system
    if (StringUtils.startsWith(text, "system(")) {
        String systemText = text;
        systemText = StringUtils.removeStart(systemText, "system(");
        systemText = StringUtils.removeEnd(systemText, ")");
        try {
            int priority = Integer.parseInt(systemText);
            return system(priority);
        } catch (NumberFormatException e) {
        }
    }
    // can not parse
    if (defaultCategory != null) {
        return defaultCategory;
    }
    throw new IllegalArgumentException("Unknown category " + text);
}

From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionTest.java

/** Tests that CA and End Entity profile authorization methods in EndEntityManagementSessionBean works.
 * When called with a user that does not have access to the CA (that you try to add a user for), or the
 * end entity profile specified for the user, an AuthorizationDeniedException should be thrown.
 * For end entity profile authorization to be effective, this must be configured in global configuration.
 *///from   w ww.jav a 2s .c  om
@Test
public void test08Authorization() throws Exception {

    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new X500Principal("C=SE,O=Test,CN=Test EndEntityManagementSessionNoAuth"));

    TestX509CertificateAuthenticationToken adminTokenNoAuth = (TestX509CertificateAuthenticationToken) simpleAuthenticationProvider
            .authenticate(new AuthenticationSubject(principals, null));
    final X509Certificate adminCert = adminTokenNoAuth.getCertificate();

    final String testRole = "EndEntityManagementSessionTestAuthRole";
    GlobalConfiguration gc = (GlobalConfiguration) globalConfSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    boolean eelimitation = gc.getEnableEndEntityProfileLimitations();

    final String authUsername = genRandomUserName();
    String email = authUsername + "@anatom.se";
    EndEntityInformation userdata = new EndEntityInformation(authUsername, "C=SE, O=AnaTom, CN=" + username,
            caid, null, email, new EndEntityType(EndEntityTypes.ENDUSER), SecConst.EMPTY_ENDENTITYPROFILE,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, SecConst.TOKEN_SOFT_P12, 0, null);
    userdata.setPassword("foo123");
    // Test CA authorization
    try {
        try {
            endEntityManagementSession.addUser(adminTokenNoAuth, userdata, false);
            fail("should throw");
        } catch (AuthorizationDeniedException e) {
            assertTrue("Wrong auth denied message: " + e.getMessage(),
                    StringUtils.startsWith(e.getMessage(), "Administrator not authorized to CA"));
        }

        try {
            endEntityManagementSession.changeUser(adminTokenNoAuth, userdata, true);
            fail("should throw");
        } catch (AuthorizationDeniedException e) {
            assertTrue("Wrong auth denied message: " + e.getMessage(),
                    StringUtils.startsWith(e.getMessage(), "Administrator not authorized to CA"));
        }

        try {
            endEntityManagementSession.addUser(admin, userdata, false);
            endEntityManagementSession.deleteUser(adminTokenNoAuth, authUsername);
            fail("should throw");
        } catch (AuthorizationDeniedException e) {
            assertTrue("Wrong auth denied message: " + e.getMessage(),
                    StringUtils.startsWith(e.getMessage(), "Administrator not authorized to CA"));
        }

        // Now add the administrator to a role that has access to /ca/* but not ee profiles
        RoleData role = roleAccessSession.findRole(testRole);
        if (role == null) {
            role = roleManagementSession.create(roleMgmgToken, testRole);
        }
        final List<AccessRuleData> accessRules = new ArrayList<AccessRuleData>();
        accessRules.add(new AccessRuleData(testRole, StandardRules.CAACCESSBASE.resource(),
                AccessRuleState.RULE_ACCEPT, true));
        role = roleManagementSession.addAccessRulesToRole(roleMgmgToken, role, accessRules);

        final List<AccessUserAspectData> accessUsers = new ArrayList<AccessUserAspectData>();
        accessUsers.add(new AccessUserAspectData(testRole, CertTools.getIssuerDN(adminCert).hashCode(),
                X500PrincipalAccessMatchValue.WITH_COMMONNAME, AccessMatchType.TYPE_EQUALCASE,
                CertTools.getPartFromDN(CertTools.getSubjectDN(adminCert), "CN")));
        roleManagementSession.addSubjectsToRole(roleMgmgToken, role, accessUsers);
        accessControlSession.forceCacheExpire();
        // We must enforce end entity profile limitations for this, with false it should be ok now
        gc.setEnableEndEntityProfileLimitations(false);
        globalConfSession.saveConfiguration(roleMgmgToken, gc);
        // Do the same test, now it should work since we are authorized to CA and we don't enforce EE profile authorization
        endEntityManagementSession.changeUser(adminTokenNoAuth, userdata, false);
        // Enforce EE profile limitations
        gc.setEnableEndEntityProfileLimitations(true);
        globalConfSession.saveConfiguration(roleMgmgToken, gc);
        // Do the same test, now we should get auth denied on EE profiles instead
        try {
            endEntityManagementSession.changeUser(adminTokenNoAuth, userdata, false);
            fail("should throw");
        } catch (AuthorizationDeniedException e) {
            assertTrue("Wrong auth denied message: " + e.getMessage(), StringUtils.startsWith(e.getMessage(),
                    "Administrator not authorized to end entity profile"));
        }

    } finally {
        gc.setEnableEndEntityProfileLimitations(eelimitation);
        globalConfSession.saveConfiguration(roleMgmgToken, gc);
        try {
            endEntityManagementSession.deleteUser(admin, authUsername);
        } catch (Exception e) { // NOPMD
            log.info("Error in finally: ", e);
        }
        RoleData role = roleAccessSession.findRole(testRole);
        if (role != null) {
            roleManagementSession.remove(roleMgmgToken, role);
        }
    }
}

From source file:org.ejbca.core.ejb.ra.UserData.java

/**
 * /*  ww  w . ja  v a  2  s  .  c  om*/
 * @return which hashing algorithm was used for this UserData object
 */
public SupportedPasswordHashAlgorithm findHashAlgorithm() {
    final String hash = getPasswordHash();
    if (StringUtils.startsWith(hash, "$2")) {
        return SupportedPasswordHashAlgorithm.SHA1_BCRYPT;
    } else {
        return SupportedPasswordHashAlgorithm.SHA1_OLD;
    }
}