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:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java

private static void setCellValueFeeFormat(Workbook wb, Cell cell, Object oneCellValue, String vendor) {
    CellStyle style = wb.createCellStyle();
    style.setDataFormat(wb.createDataFormat().getFormat("$#,#0.00"));
    cell.setCellStyle(style);//  w w  w  .j a v  a2s  . c o m

    if (oneCellValue == null) {
        cell.setCellValue(Double.parseDouble("0.0"));
        return;
    }

    String feeStr = StringUtils.replace(oneCellValue.toString(), "$", StringUtils.EMPTY);
    feeStr = StringUtils.trimToEmpty(feeStr);
    feeStr = feeStr.replaceAll("\\p{javaSpaceChar}", StringUtils.EMPTY);
    if (StringUtils.isEmpty(feeStr)) {
        cell.setCellValue(Double.parseDouble("0.0"));
        return;
    }

    if (StringUtils.contains(vendor, TOLL_COMPANY_EZ_PASS_PA)
            || StringUtils.contains(vendor, TOLL_COMPANY_IPASS)
            || StringUtils.contains(vendor, TOLL_COMPANY_SUN_PASS)) {
        if (StringUtils.startsWith(feeStr, "-")) {
            feeStr = StringUtils.substring(feeStr, 1);
        } else {
            feeStr = "-" + feeStr;
        }
    }

    cell.setCellValue(Double.parseDouble(feeStr));
}

From source file:com.prowidesoftware.swift.model.SwiftTagListBlock.java

/**
 * Get all the fields that match the given name and whose first component is <em>being</em>.
 * @param name the name of the field to match, may end with 'a' as wildcard. When name ends with 'a' it is removed from the search and the field is matched with startsWith instead of equals
 * @param being value to match in {@link Field#is(String)} which compares the value of component 1
 * @return a list of matching fields or an empty list if none found
 * @since 7.6//  w  w  w .ja  v  a 2 s .  c  o  m
 */
public List<? extends Field> getFieldsByName(final String name, final String being) {
    // sanity check
    Validate.notNull(name, "parameter 'name' cannot not be null");
    Validate.notNull(being, "parameter 'being' cannot not be null");

    final boolean wildcard;
    final String search;
    if (name.endsWith("a")) {
        wildcard = true;
        search = name.substring(0, name.length() - 1);
    } else {
        wildcard = false;
        search = name;
    }
    final List<Field> l = new ArrayList<Field>();
    for (final Iterator<Tag> it = this.tags.iterator(); it.hasNext();) {
        final Tag t = (Tag) it.next();
        if ((wildcard && StringUtils.startsWith(t.getName(), search))
                || StringUtils.equals(t.getName(), name)) {
            final Field field = t.getField();
            if (field == null) {
                log.warning("Could not create field instance of " + t);
            } else {
                // Excepto por este if es igual a getFieldsByName y devuelve list
                if (field.is(being)) {
                    l.add(field);
                }
            }
        }
    }
    return l;
}

From source file:jp.primecloud.auto.process.vmware.VmwareProcessClient.java

public void waitForRunning(String machineName) {
    VirtualMachine machine = getVirtualMachine(machineName);

    // ?//w w w. j  av  a2 s . c o  m
    long startTime = System.currentTimeMillis();
    while (true) {
        // 15???????????
        if (System.currentTimeMillis() - startTime > 15 * 60 * 1000L) {
            throw new AutoException("EPROCESS-000531", machineName);
        }

        try {
            Thread.sleep(30 * 1000L);
        } catch (InterruptedException ignore) {
        }

        // ?????
        if (machine.getRuntime().getPowerState() != VirtualMachinePowerState.poweredOn) {
            throw new AutoException("EPROCESS-000530", machineName);
        }

        // ?
        GuestInfo guestInfo = machine.getGuest();

        if (log.isDebugEnabled()) {
            log.debug(jp.primecloud.auto.util.StringUtils.reflectToString(guestInfo));
        }

        // VMware Tools??????
        if (VirtualMachineToolsVersionStatus.guestToolsNotInstalled.toString()
                .equals(guestInfo.getToolsVersionStatus2())) {
            throw new AutoException("EPROCESS-000509", machineName);
        }

        // VMware Tools??????
        if (!VirtualMachineToolsRunningStatus.guestToolsRunning.toString()
                .equals(guestInfo.getToolsRunningStatus())) {
            continue;
        }

        // ??????
        if (!VirtualMachineGuestState.running.toString().equals(guestInfo.getGuestState())) {
            continue;
        }

        // ?????????
        if (guestInfo.getNet() == null) {
            continue;
        }

        // ???IP??????
        int count = 0;
        for (GuestNicInfo nicInfo : guestInfo.getNet()) {
            // NIC?IPv4??
            NetIpConfigInfoIpAddress[] tmpAddresses = nicInfo.getIpConfig().getIpAddress();
            if (tmpAddresses == null) {
                continue;
            }
            String ipAddress = null;
            for (NetIpConfigInfoIpAddress tmpAdress : tmpAddresses) {
                try {
                    InetAddress inetAddress = InetAddress.getByName(tmpAdress.getIpAddress());
                    if (inetAddress instanceof Inet4Address) {
                        ipAddress = tmpAdress.getIpAddress();
                        break;
                    }
                } catch (UnknownHostException ignore) {
                }
            }

            if (ipAddress != null && !StringUtils.startsWith(ipAddress, "169.254.")) {
                count++;
            }
        }
        if (count != guestInfo.getNet().length) {
            continue;
        }

        break;
    }
}

From source file:com.activecq.tools.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Covert OSGi Property storing Root content paths:Error page paths into a SortMap
 *
 * @param paths/*w w w  .java2  s . co m*/
 * @return
 */
private SortedMap<String, String> configurePathMap(String[] paths) {
    SortedMap<String, String> sortedMap = new TreeMap<String, String>(new StringLengthComparator());

    for (String path : paths) {
        if (StringUtils.isBlank(path)) {
            continue;
        }

        final SimpleEntry tmp = toSimpleEntry(path, ":");

        if (tmp == null) {
            continue;
        }

        String key = StringUtils.strip((String) tmp.getKey());
        String val = StringUtils.strip((String) tmp.getValue());

        // Only accept absolute paths
        if (StringUtils.isBlank(key) || !StringUtils.startsWith(key, "/")) {
            continue;
        }

        // Validate page name value
        if (StringUtils.isBlank(val)) {
            val = key + "/" + DEFAULT_ERROR_PAGE_NAME;
        } else if (StringUtils.equals(val, ".")) {
            val = key;
        } else if (!StringUtils.startsWith(val, "/")) {
            val = key + "/" + val;
        }

        sortedMap.put(key, val);
    }

    return sortedMap;
}

From source file:eu.europeana.portal2.web.presentation.model.FullDocPage.java

public boolean isUrlRefMms() {
    return StringUtils.startsWith(getUrlRef(), "mms");
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.MafFileValidator.java

/**
 * Validates a maf file.  Will add errors found.
 *
 * @param mafFile the file to validate/*from w  ww .  j ava 2  s  .c  om*/
 * @param context the qc context
 * @return whether validation passed or not
 * @throws IOException if the file could not be opened/read
 * @throws gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.Processor.ProcessorException
 *                     if an error happens
 */
protected boolean validate(final File mafFile, final QcContext context) throws IOException, ProcessorException {

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;

    try {
        // initialize threadlocal
        initThreadLocals();

        boolean ok = true;
        context.setFile(mafFile);

        // set sampleTypes
        for (SampleType sample : sampleTypeQueries.getAllSampleTypes()) {
            sampleCodes.put(sample.getSampleTypeCode(), sample.getIsTumor());
        }

        // open file
        fileReader = new FileReader(mafFile);
        bufferedReader = new BufferedReader(fileReader);

        int lineNum = 0;

        // find first non-blank line not starting with #, this is the header
        String headerLine = bufferedReader.readLine();
        lineNum++;
        while (StringUtils.isEmpty(headerLine.trim())
                || StringUtils.startsWith(headerLine, COMMENT_LINE_TOKEN)) {
            headerLine = bufferedReader.readLine();
            lineNum++;
        }

        final List<String> headers = Arrays.asList(headerLine.split("\\t"));

        // get order of fields from header
        final Map<String, Integer> fieldOrder = mapFieldOrder(headers);
        // make sure the field order is correct
        for (int i = 0; i < getMafFieldList().size(); i++) {
            if (fieldOrder.get(getMafFieldList().get(i)) == null) {
                context.addError(MessageFormat.format(MessagePropertyType.MISSING_REQUIRED_COLUMN_ERROR,
                        getMafFieldList().get(i)));
                // if a column is missing, just return false now
                return false;
            } else if (fieldOrder.get(getMafFieldList().get(i)) != i) {
                context.addError(
                        MessageFormat.format(MessagePropertyType.MAF_FILE_PROCESSING_ERROR, mafFile.getName(),
                                new StringBuilder().append("Expected column '").append(getMafFieldList().get(i))
                                        .append("' to be at index '").append((i + 1)).append("' but found at '")
                                        .append((fieldOrder.get(getMafFieldList().get(i)) + 1)).append("'")
                                        .toString()));
                // if order is wrong, make error but ok to continue rest of checks
                ok = false;
            }
        }

        String line;
        int initialErrorCount = context.getErrorCount();
        while ((line = bufferedReader.readLine()) != null) {
            lineNum++;
            if (!StringUtils.isBlank(line.trim()) && !StringUtils.startsWith(line, COMMENT_LINE_TOKEN)) {
                final String[] row = line.split("\\t");

                if (row.length >= fieldOrder.size()) {
                    boolean rowOk = validateRow(row, fieldOrder, lineNum, context, mafFile.getName());

                    ok = ok && rowOk;
                } else {
                    context.addError(MessageFormat.format(MessagePropertyType.MAF_FILE_VALIDATION_ERROR,
                            mafFile.getName(), lineNum,
                            new StringBuilder().append("Improper format: expected '").append(fieldOrder.size())
                                    .append("' fields but found '").append(row.length).append("'").toString()));
                    ok = false;
                }
            }
            if (context.getErrorCount() - initialErrorCount > 100) {
                context.addError("More than 100 errors found, halting MAF validation");
                break;
            }

        }

        // validate remaining ids (barcodes or UUIDs)
        if (context.isStandaloneValidator()) {
            ok = batchValidate(null, context, mafFile.getName(), true, true);
        }

        if (!ok) {
            context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
        }

        return ok;

    } finally {
        cleanupThreadLocals();
        if (bufferedReader != null) {
            bufferedReader.close();
        }

        if (fileReader != null) {
            fileReader.close();
        }
    }
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

@SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
    Dictionary<?, ?> config = componentContext.getProperties();
    final String legacyPrefix = "prop.";

    this.enabled = PropertiesUtil.toBoolean(config.get(PROP_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_ENABLED), DEFAULT_ENABLED));

    this.vanityDispatchCheckEnabled = PropertiesUtil.toBoolean(config.get(PROP_VANITY_DISPATCH_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_VANITY_DISPATCH_ENABLED),
                    DEFAULT_VANITY_DISPATCH_ENABLED));

    /** Error Pages **/

    this.systemErrorPagePath = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_PATH), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_PATH), DEFAULT_SYSTEM_ERROR_PAGE_PATH_DEFAULT));

    this.errorPageExtension = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_EXTENSION), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_EXTENSION), DEFAULT_ERROR_PAGE_EXTENSION));

    this.fallbackErrorName = PropertiesUtil.toString(config.get(PROP_FALLBACK_ERROR_NAME), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_FALLBACK_ERROR_NAME), DEFAULT_FALLBACK_ERROR_NAME));

    this.pathMap = configurePathMap(PropertiesUtil.toStringArray(config.get(PROP_SEARCH_PATHS),
            PropertiesUtil.toStringArray(config.get(legacyPrefix + PROP_SEARCH_PATHS), DEFAULT_SEARCH_PATHS)));

    /** Not Found Handling **/
    this.notFoundBehavior = PropertiesUtil.toString(config.get(PROP_NOT_FOUND_DEFAULT_BEHAVIOR),
            DEFAULT_NOT_FOUND_DEFAULT_BEHAVIOR);

    String[] tmpNotFoundExclusionPatterns = PropertiesUtil.toStringArray(
            config.get(PROP_NOT_FOUND_EXCLUSION_PATH_PATTERNS), DEFAULT_NOT_FOUND_EXCLUSION_PATH_PATTERNS);

    this.notFoundExclusionPatterns = new ArrayList<Pattern>();
    for (final String tmpPattern : tmpNotFoundExclusionPatterns) {
        this.notFoundExclusionPatterns.add(Pattern.compile(tmpPattern));
    }/*from w w  w.  j a  v a 2s  .c o  m*/

    /** Error Page Cache **/

    int ttl = PropertiesUtil.toInteger(config.get(PROP_TTL),
            PropertiesUtil.toInteger(LEGACY_PROP_TTL, DEFAULT_TTL));

    boolean serveAuthenticatedFromCache = PropertiesUtil
            .toBoolean(config.get(PROP_SERVE_AUTHENTICATED_FROM_CACHE), PropertiesUtil.toBoolean(
                    LEGACY_PROP_SERVE_AUTHENTICATED_FROM_CACHE, DEFAULT_SERVE_AUTHENTICATED_FROM_CACHE));
    try {
        cache = new ErrorPageCacheImpl(ttl, serveAuthenticatedFromCache);

        Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
        serviceProps.put("jmx.objectname", "com.adobe.acs.commons:type=ErrorPageHandlerCache");

        cacheRegistration = componentContext.getBundleContext().registerService(DynamicMBean.class.getName(),
                cache, serviceProps);
    } catch (NotCompliantMBeanException e) {
        log.error("Unable to create cache", e);
    }

    /** Error Images **/

    this.errorImagesEnabled = PropertiesUtil.toBoolean(config.get(PROP_ERROR_IMAGES_ENABLED),
            DEFAULT_ERROR_IMAGES_ENABLED);

    this.errorImagePath = PropertiesUtil.toString(config.get(PROP_ERROR_IMAGE_PATH), DEFAULT_ERROR_IMAGE_PATH);

    // Absolute path
    if (StringUtils.startsWith(this.errorImagePath, "/")) {
        ResourceResolver serviceResourceResolver = null;
        try {
            Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE,
                    (Object) SERVICE_NAME);
            serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
            final Resource resource = serviceResourceResolver.resolve(this.errorImagePath);

            if (resource != null && resource.isResourceType(JcrConstants.NT_FILE)) {
                final PathInfo pathInfo = new PathInfo(this.errorImagePath);

                if (!StringUtils.equals("img", pathInfo.getSelectorString())
                        || StringUtils.isBlank(pathInfo.getExtension())) {

                    log.warn("Absolute Error Image Path paths to nt:files should have '.img.XXX' "
                            + "selector.extension");
                }
            }
        } catch (LoginException e) {
            log.error("Could not get admin resource resolver to inspect validity of absolute errorImagePath");
        } finally {
            if (serviceResourceResolver != null) {
                serviceResourceResolver.close();
            }
        }
    }

    this.errorImageExtensions = PropertiesUtil.toStringArray(config.get(PROP_ERROR_IMAGE_EXTENSIONS),
            DEFAULT_ERROR_IMAGE_EXTENSIONS);

    for (int i = 0; i < errorImageExtensions.length; i++) {
        this.errorImageExtensions[i] = StringUtils.lowerCase(errorImageExtensions[i], Locale.ENGLISH);
    }

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    pw.println();
    pw.printf("Enabled: %s", this.enabled).println();
    pw.printf("System Error Page Path: %s", this.systemErrorPagePath).println();
    pw.printf("Error Page Extension: %s", this.errorPageExtension).println();
    pw.printf("Fallback Error Page Name: %s", this.fallbackErrorName).println();

    pw.printf("Resource Not Found - Behavior: %s", this.notFoundBehavior).println();
    pw.printf("Resource Not Found - Exclusion Path Patterns %s", Arrays.toString(tmpNotFoundExclusionPatterns))
            .println();

    pw.printf("Cache - TTL: %s", ttl).println();
    pw.printf("Cache - Serve Authenticated: %s", serveAuthenticatedFromCache).println();

    pw.printf("Error Images - Enabled: %s", this.errorImagesEnabled).println();
    pw.printf("Error Images - Path: %s", this.errorImagePath).println();
    pw.printf("Error Images - Extensions: %s", Arrays.toString(this.errorImageExtensions)).println();

    log.debug(sw.toString());
}

From source file:com.ewcms.content.document.service.ArticleMainService.java

@Override
public Map<Channel, Long> findBeApprovalArticleMain(String userName) {
    Map<Channel, Long> result = new HashMap<Channel, Long>();

    List<String> groupNames = new ArrayList<String>();
    UserDetails user = userService.loadUserByUsername(userName);
    if (user != null) {
        Collection<GrantedAuthority> authorites = user.getAuthorities();
        for (GrantedAuthority auth : authorites) {
            if (StringUtils.startsWith(auth.getAuthority(), GroupServiceable.GROUP_NAME_PERFIX)) {
                groupNames.add(auth.getAuthority());
            }//from   w  ww  .j  a va  2 s.c o m
        }
    }

    Map<Integer, Long> map = articleMainDAO.findBeApprovalArticleMain(userName, groupNames);
    if (!map.isEmpty()) {
        Set<Integer> keySets = map.keySet();
        for (Integer key : keySets) {
            Channel channel = channelDAO.get(key);
            Long count = map.get(key);
            result.put(channel, count);
        }
    }
    return result;
}

From source file:com.tesora.dve.sql.TestCreates.java

@Test
public void testPE842() throws Throwable {
    String[] tbls = { "CREATE TABLE `ira_aa` ( " + "`id` varchar(32) NOT NULL, "
            + "`qid` varchar(32) NOT NULL, " + "PRIMARY KEY (`id`), " + "KEY `fk_aaqi` (`qid`), "
            + "CONSTRAINT `fk_aaqi` FOREIGN KEY (`qid`) REFERENCES `ira_aq` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION "
            + ") ENGINE=InnoDB DEFAULT CHARSET=latin1 ",
            "CREATE TABLE `ira_aq` ( " + "`id` varchar(32) NOT NULL, " + "`tid` varchar(45) NOT NULL, "
                    + "`cai` varchar(32) DEFAULT NULL, " + "PRIMARY KEY (`id`), " + "KEY `fk_qt` (`tid`), "
                    + "KEY `fk_qca` (`cai`), " + "CONSTRAINT `fk_qca` FOREIGN KEY "
                    + "(`cai`) REFERENCES `ira_aa` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, "
                    + "CONSTRAINT `fk_qt` FOREIGN KEY (`tid`) REFERENCES `irp_t` (`tid`) ON DELETE NO ACTION ON UPDATE NO ACTION "
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1 ",
            "CREATE TABLE `ira_qi` ( " + "`id` varchar(32) NOT NULL, " + "`qid` varchar(32) NOT NULL, "
                    + "`tii` varchar(32) DEFAULT NULL, " + "PRIMARY KEY (`id`), " + "KEY `fk_qiq` (`qid`), "
                    + "KEY `fk_qiti` (`tii`), "
                    + "CONSTRAINT `fk_qiq` FOREIGN KEY (`qid`) REFERENCES `ira_aq` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, "
                    + "CONSTRAINT `fk_qiti` FOREIGN KEY (`tii`) REFERENCES `ira_t` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION "
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1 " };

    rootConnection.execute("CREATE RANGE id_range (varchar(32)) PERSISTENT GROUP "
            + testDDL_FK_MODE_IGNORE.getPersistentGroup().getName());

    String db = "PE842";
    int[] fkChecks = { 0, 1 };
    FKMode[] fkmodes = { FKMode.IGNORE, FKMode.STRICT };
    String[] dists = { "broadcast distribute", "random distribute" };
    ProxyConnectionResource rc = null;/* ww w .  ja v  a2s.  com*/
    for (int fkCheck : fkChecks) {
        for (FKMode fkmode : fkmodes) {
            rc = rootConnection;
            if (fkmode == FKMode.IGNORE) {
                rc = rootConnection_fk_mode_ignore;
            }
            rc.execute("DROP DATABASE IF EXISTS " + db);
            rc.execute("CREATE DATABASE " + db + " DEFAULT PERSISTENT GROUP " + sgDDL.getName()
                    + " USING TEMPLATE " + TemplateMode.OPTIONAL + " FOREIGN KEY MODE " + fkmode);
            try {
                rc.execute("SET FOREIGN_KEY_CHECKS = " + fkCheck);
                rc.execute("USE " + db);
                for (String dist : dists) {
                    for (String tbl : tbls) {
                        try {
                            String d = dist;
                            if (StringUtils.startsWith(dist, "range")) {
                                if (StringUtils.startsWith(tbl, "CREATE TABLE `ira_aq`")) {
                                    d = StringUtils.replace(dist, "%", "id");
                                } else {
                                    d = StringUtils.replace(dist, "%", "qid");
                                }
                            }
                            rc.execute(tbl + d);
                        } catch (Exception e) {
                            // do nothing will validate after loop ends
                        }
                    }

                    assertTestPE842VariationResult(rc, db, fkCheck, fkmode, dist);

                    rc.execute("drop table if exists ira_aa, ira_qi, ira_aq");
                    rc.assertResults("show tables like 'ira_%'", br());
                    rc.assertResults(
                            "select * from information_schema.table_constraints where constraint_type='FOREIGN KEY' and table_name like 'ira_%' order by constraint_name",
                            br());
                }
            } finally {
                rc.execute("DROP DATABASE IF EXISTS " + db);
            }
        }
    }

    rootConnection.execute("DROP DATABASE IF EXISTS " + db);
    rootConnection.execute("CREATE DATABASE " + db + " DEFAULT PERSISTENT GROUP " + sgDDL.getName()
            + " USING TEMPLATE " + TemplateMode.OPTIONAL);

    try {
        rootConnection.execute("SET FOREIGN_KEY_CHECKS=0");
        rootConnection.execute("USE " + db);

        rootConnection.execute(
                "CREATE TABLE IF NOT EXISTS `Apps` (" + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
                        + "`AppTypes_id` int(10) unsigned DEFAULT NULL," + "PRIMARY KEY (`id`),"
                        + "KEY `fk_Apps_AppTypes1` (`AppTypes_id`),"
                        + "CONSTRAINT `fk_Apps_AppTypes1` FOREIGN KEY (`AppTypes_id`)"
                        + "REFERENCES `AppTypes` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION"
                        + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 broadcast distribute");
        rootConnection.execute("CREATE TABLE IF NOT EXISTS `AppTypes` ("
                + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT," + "`Apps_id` int(10) unsigned DEFAULT NULL,"
                + "PRIMARY KEY (`id`)," + "CONSTRAINT `fk_AppTypes_Apps` FOREIGN KEY (`Apps_id`)"
                + "REFERENCES `Apps` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION"
                + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 broadcast distribute");
        rootConnection.assertResults("show tables like 'App%'", br(nr, "Apps", nr, "AppTypes"));
        rootConnection.assertResults("select * from Apps", br());
    } finally {
        rootConnection.execute("DROP DATABASE IF EXISTS " + db);
    }
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Convert OSGi Property storing Root content paths:Error page paths into a SortMap.
 *
 * @param paths//from ww w . j  a v a 2  s.  c o m
 * @return
 */
private SortedMap<String, String> configurePathMap(String[] paths) {
    SortedMap<String, String> sortedMap = new TreeMap<String, String>(new StringLengthComparator());

    for (String path : paths) {
        if (StringUtils.isBlank(path)) {
            continue;
        }

        final SimpleEntry<String, String> tmp = toSimpleEntry(path, ":");

        if (tmp == null) {
            continue;
        }

        String key = StringUtils.strip(tmp.getKey());
        String val = StringUtils.strip(tmp.getValue());

        // Only accept absolute paths
        if (StringUtils.isBlank(key) || !StringUtils.startsWith(key, "/")) {
            continue;
        }

        // Validate page name value
        if (StringUtils.isBlank(val)) {
            val = key + "/" + DEFAULT_ERROR_PAGE_NAME;
        } else if (StringUtils.equals(val, ".")) {
            val = key;
        } else if (!StringUtils.startsWith(val, "/")) {
            val = key + "/" + val;
        }

        sortedMap.put(key, val);
    }

    return sortedMap;
}