Example usage for org.apache.commons.lang3 StringUtils repeat

List of usage examples for org.apache.commons.lang3 StringUtils repeat

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils repeat.

Prototype

public static String repeat(final char ch, final int repeat) 

Source Link

Document

<p>Returns padding using the specified delimiter repeated to a given length.</p> <pre> StringUtils.repeat('e', 0) = "" StringUtils.repeat('e', 3) = "eee" StringUtils.repeat('e', -2) = "" </pre> <p>Note: this method doesn't not support padding with <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> as they require a pair of char s to be represented.

Usage

From source file:com.mirth.connect.cli.CommandLineInterface.java

private void listCodeTemplates(List<CodeTemplate> codeTemplates, boolean indent, int maxNameLength) {
    for (CodeTemplate codeTemplate : codeTemplates) {
        if (codeTemplate.getName().length() > maxNameLength) {
            maxNameLength = codeTemplate.getName().length();
        }//w ww  . j av a 2  s . c  om
    }

    out.printf((indent ? '\t' : "") + "%-" + maxNameLength + "s  %-36s  %-24s  %-8s  %s\n", "Name", "Id",
            "Type", "Revision", "Last Modified");
    out.printf((indent ? '\t' : "") + "%-" + maxNameLength + "s  %-36s  %-24s  %-8s  %s\n",
            StringUtils.repeat('-', maxNameLength), StringUtils.repeat('-', 36), StringUtils.repeat('-', 24),
            StringUtils.repeat('-', 8), StringUtils.repeat('-', 19));
    for (CodeTemplate codeTemplate : codeTemplates) {
        out.printf((indent ? '\t' : "") + "%-" + maxNameLength + "s  %-36s  %-24s  %-8d  %tF %<tT\n",
                codeTemplate.getName(), codeTemplate.getId(), codeTemplate.getType(),
                codeTemplate.getRevision(), codeTemplate.getLastModified());
    }
}

From source file:info.financialecology.finance.utilities.datastruct.VersatileTimeSeries.java

/**
 * Prints a sequence of '-' characters with a total width covering the length of the time
 * series plus a left-hand row label. /*w w  w  .ja v a2  s  .c o  m*/
 * <p>
 * @param width the width of the space to contain the left-hand row label
 * @return a sequence of '-' characters covering the time series plus row label
 * @see #printRowSeparator()
 */
public String printDecoratedRowSeparator(int width) {
    String ts = StringUtils.repeat('-', width + 9); // TODO extend to include right-hand row label
    ts += printRowSeparator();
    return ts;
}

From source file:com.ibm.cics.ca1y.Emit.java

/**
 * Add name / value properties from contents of container DFHEP.DESCRIPTOR and business information items from
 * containers DFHEP.DATA.nnnnn//from  www. j a  v  a  2  s.c  om
 * 
 * @param props
 *            - The properties to add entries to
 * @param channel
 *            - The channel to get the container from
 * @return true if properties added successfully
 */
private static boolean addPropertiesFromDFHEP_DESCRIPTOR(EmitProperties props, Channel channel)
        throws ContainerErrorException, ChannelErrorException, CCSIDErrorException, CodePageErrorException {

    // DFHEP.DESCRIPTOR container is mapped by COBOL copybook
    // hlq.DFHCOB(DFHEPDEO).
    // Use createContainer to create a proxy container object otherwise
    // JCICS will use JNI to CICS just to create this object.
    EPDEv1 epde = new EPDEv1();
    epde.setBytes(channel.createContainer("DFHEP.DESCRIPTOR").get());

    // Get event business information items
    Epde_epde__item[] epdeitems = epde.getEpde__item();
    int index = 0;

    for (Epde_epde__item epdeitem : epdeitems) {
        // Container DFHEP.DATA.nnnnn has the business information item data
        String datatype = epdeitem.getEpde__datatype();

        // Use createContainer to create a proxy container object otherwise
        // JCICS will use JNI to CICS just to create this object.
        Container data = channel.createContainer("DFHEP.DATA." + String.format("%05d", ++index));
        if (data == null) {
            // If no container has been captured for this information item,
            // ignore
            continue;
        }

        String dataString = null;
        Float dataFloat = null;
        BigInteger dataBigInteger = null;
        Long dataLong = null;
        String conversionFormat = null;
        String conversionSummary = "";
        byte[] dataToConvert = null;
        int dataToConvertLength = 0;

        if ((epdeitem.isEpde__char(datatype)) || (epdeitem.isEpde__charz(datatype))) {
            // Use CICS container API to convert captured data into UTF-8 as
            // Java may not support all CICS codepages

            try {
                dataToConvert = data.get("UTF-8");

            } catch (ContainerErrorException e) {
                // Container could not be found because it was not available
                // to be captured by CICS. Ignore.
                //
                // Details are in CICS topic "Writing a custom EP adapter"
                // that says
                // "If a data item was not available for data capture, the
                // corresponding data item container is not present
                // in the CICS event object. This situation can happen, for
                // example, when CAPTURESPEC specifies a capture data item
                // associated with an optional parameter that was not
                // present on the API command that caused the event."

            } catch (Exception e) {
                // Data captured by CICS does not match the codepage
                // specified in the event binding information source
                e.printStackTrace();
            }

        } else {
            dataToConvert = data.getNoConvert();
        }

        if (dataToConvert != null) {
            dataToConvertLength = dataToConvert.length;
        }

        if (dataToConvert == null) {
            // No data to convert

        } else if ((epdeitem.isEpde__char(datatype) || epdeitem.isEpde__charz(datatype))) {
            // Handle EPDE-DATATYPE=EPDE-CHAR
            // Handle EPDE-DATATYPE=EPDE-CHARZ
            try {
                dataString = new String(dataToConvert, "UTF-8");

            } catch (Exception e) {
                // Data captured by CICS does not match the codepage
                // specified in the event binding information source
                e.printStackTrace();
            }

            if (epdeitem.isEpde__charz(datatype)) {
                // Truncate string before first 0x00 character
                int n = dataString.indexOf(0x00);

                if (n > 0) {
                    dataString = dataString.substring(0, n - 1);
                }
            }

        } else if (epdeitem.isEpde__hex(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-HEX

            // No conversion required.

        } else if (epdeitem.isEpde__hexz(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-HEXZ

            // Find first byte that is x'00' in byte array
            for (dataToConvertLength = 0; dataToConvertLength < dataToConvert.length; dataToConvertLength++) {

                if (dataToConvert[dataToConvertLength] == 0x00) {

                    if (dataToConvertLength == 0) {
                        // Nothing to copy
                        dataToConvert = new byte[0];
                        break;
                    } else {
                        // Create a new array of the correct length and copy
                        // contents
                        --dataToConvertLength;
                        byte[] bcopy = new byte[dataToConvertLength];
                        System.arraycopy(dataToConvert, 0, bcopy, 0, dataToConvertLength);
                        dataToConvert = bcopy;

                        break;
                    }
                }
            }

        } else if (epdeitem.isEpde__uhword(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-UHWORD
            dataLong = new Long(MarshallIntegerUtils.unmarshallTwoByteIntegerFromBuffer(dataToConvert, 0, true,
                    MarshallIntegerUtils.SIGN_CODING_UNSIGNED_BINARY));

        } else if (epdeitem.isEpde__ufword(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-UFWORD
            dataLong = new Long(MarshallIntegerUtils.unmarshallFourByteIntegerFromBuffer(dataToConvert, 0, true,
                    MarshallIntegerUtils.SIGN_CODING_UNSIGNED_BINARY));

        } else if (epdeitem.isEpde__shword(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-SHWORD
            dataLong = new Long(MarshallIntegerUtils.unmarshallTwoByteIntegerFromBuffer(dataToConvert, 0, true,
                    MarshallIntegerUtils.SIGN_CODING_TWOS_COMPLEMENT));

        } else if (epdeitem.isEpde__sfword(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-SFWORD
            dataLong = new Long(MarshallIntegerUtils.unmarshallFourByteIntegerFromBuffer(dataToConvert, 0, true,
                    MarshallIntegerUtils.SIGN_CODING_TWOS_COMPLEMENT));

        } else if (epdeitem.isEpde__packed(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-PACKED
            dataBigInteger = MarshallPackedDecimalUtils.unmarshallBigIntegerFromBuffer(dataToConvert, 0,
                    dataToConvertLength);

        } else if (epdeitem.isEpde__zoned(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-ZONED
            boolean sign = false;
            int signFormat = 0;
            byte first = dataToConvert[0];
            byte last = dataToConvert[dataToConvert.length - 1];

            if ((first == 0x4E) || (first == 0x60)) {
                // 0x4E is the EBCDIC character "+" and 0x60 is the EBCDIC
                // character "-"
                sign = true;
                signFormat = MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING_SEPARATE;

            } else if ((last == 0x4E) || (last == 0x60)) {
                sign = true;
                signFormat = MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING_SEPARATE;

            } else if (((first & 0xF0) == 0xC0) || ((first & 0xF0) == 0xD0)) {
                sign = true;
                signFormat = MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING;

            } else if (((last & 0xF0) == 0xC0) || ((last & 0xF0) == 0xD0)) {
                sign = true;
                signFormat = MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING;
            }

            dataBigInteger = MarshallExternalDecimalUtils.unmarshallBigIntegerFromBuffer(dataToConvert, 0,
                    dataToConvertLength, sign, signFormat,
                    MarshallExternalDecimalUtils.EXTERNAL_DECIMAL_SIGN_EBCDIC);

            if (logger.isLoggable(Level.FINE)) {
                if (signFormat == MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING_SEPARATE)
                    conversionSummary = "sign type MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING_SEPARATE";

                else if (signFormat == MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING_SEPARATE)
                    conversionSummary = "sign type MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING_SEPARATE";

                else if (signFormat == MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING)
                    conversionSummary = "sign type MarshallExternalDecimalUtils.SIGN_FORMAT_LEADING";

                else if (signFormat == MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING)
                    conversionSummary = "sign type MarshallExternalDecimalUtils.SIGN_FORMAT_TRAILING";
                else
                    conversionSummary = "found sign:" + sign;
            }

        } else if (epdeitem.isEpde__hexfloat(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-HEXFLOAT
            if (dataToConvertLength == 4)
                dataFloat = new Float(MarshallFloatUtils.unmarshallFloatFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IBM_390_HEX, dataToConvertLength));
            else
                dataFloat = new Float(MarshallFloatUtils.unmarshallDoubleFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IBM_390_HEX, dataToConvertLength));

        } else if (epdeitem.isEpde__binfloat(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-BINFLOAT
            if (dataToConvertLength == 4)
                dataFloat = new Float(MarshallFloatUtils.unmarshallFloatFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IEEE_EXTENTED_OS390, dataToConvertLength));
            else
                dataFloat = new Float(MarshallFloatUtils.unmarshallDoubleFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IEEE_EXTENTED_OS390, dataToConvertLength));

        } else if (epdeitem.isEpde__decfloat(datatype)) {
            // Handle EPDE-DATATYPE=EPDE-DECFLOAT
            if (dataToConvertLength == 4)
                dataFloat = new Float(MarshallFloatUtils.unmarshallFloatFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IEEE_DFP_IBM, dataToConvertLength));
            else
                dataFloat = new Float(MarshallFloatUtils.unmarshallDoubleFromBuffer(dataToConvert, 0, true,
                        MarshallFloatUtils.FLOAT_FORMAT_IEEE_DFP_IBM, dataToConvertLength));
        }

        // Format as type attachment, text, numeric, or scientific

        if ((epdeitem.isEpde__hex(datatype)) || (epdeitem.isEpde__hexz(datatype))) {

            // No need to format Hex and Hexz data types as they will be
            // attachments
            dataString = null;

        } else if (epdeitem.isEpde__text(epdeitem.getEpde__formattype())) {

            // Format type is text

            if (dataString == null) {
                // Data not captured
                dataString = "";

            } else if (epdeitem.isEpde__formatlen__auto(epdeitem.getEpde__formatlen())) {
                // Format length is automatic, so just remove trailing
                // blanks
                dataString = dataString.trim();

            } else if (dataString.length() != epdeitem.getEpde__formatlen()) {
                // Format length is specified, so truncate or pad with
                // blanks
                dataString = Util.rightPad(dataString, epdeitem.getEpde__formatlen());
            }

        } else if (epdeitem.isEpde__numeric(epdeitem.getEpde__formattype())) {

            // Format type is numeric

            if (epdeitem.isEpde__formatlen__auto(epdeitem.getEpde__formatlen())) {
                // Format length is automatic
                conversionFormat = "#." + StringUtils.repeat("#", 10);

            } else if (epdeitem.isEpde__formatprec__auto(epdeitem.getEpde__formatprecision())) {
                // Format precision is automatic
                conversionFormat = StringUtils.repeat("0", epdeitem.getEpde__formatlen()) + "."
                        + StringUtils.repeat("#", 10);

            } else {
                conversionFormat = StringUtils.repeat("0", epdeitem.getEpde__formatlen()) + "."
                        + StringUtils.repeat("#", epdeitem.getEpde__formatprecision());
            }

            if (dataLong != null) {
                dataString = (new DecimalFormat(conversionFormat)).format(dataLong);

            } else if (dataFloat != null) {
                dataString = (new DecimalFormat(conversionFormat)).format(dataFloat);

            } else if (dataBigInteger != null) {
                dataString = (new DecimalFormat(conversionFormat)).format(dataBigInteger);
            }

            if (dataString.endsWith(".")) {
                // Remove trailing "."
                dataString = dataString.substring(0, dataString.length() - 1);
            }

        } else if (epdeitem.isEpde__scientific(epdeitem.getEpde__formattype())) {

            // Format type is scientific

            if (epdeitem.isEpde__formatlen__auto(epdeitem.getEpde__formatlen())) {
                conversionFormat = "%e";

            } else if (epdeitem.isEpde__formatprec__auto(epdeitem.getEpde__formatprecision())) {
                conversionFormat = "%" + epdeitem.getEpde__formatlen() + "e";

            } else {
                conversionFormat = "%" + epdeitem.getEpde__formatlen() + "."
                        + epdeitem.getEpde__formatprecision() + "e";
            }

            if (dataFloat != null) {
                dataString = String.format(conversionFormat, dataFloat);

            } else if (dataBigInteger != null) {
                dataString = String.format(conversionFormat, dataBigInteger);
            }
        }

        if (dataString == null) {
            // set property to an empty string and mark as resolved
            props.setPropertyAndResolved(epdeitem.getEpde__dataname().trim(), "");

            // Add as attachment
            props.setPropertyAttachment(epdeitem.getEpde__dataname().trim(), dataToConvert);

            if (logger.isLoggable(Level.FINE)) {
                conversionSummary = "added as attachment";
            }

        } else {
            props.setProperty(epdeitem.getEpde__dataname().trim(), dataString);
        }

        // Keep list of business information items so we can later retrieve them in the specific order presented
        // here, including the format length
        if (dataString == null) {
            props.putBusinessInformationItem(epdeitem.getEpde__dataname().trim(), dataToConvert.length);
        } else {
            if (epdeitem.isEpde__formatlen__auto(epdeitem.getEpde__formatlen())) {
                props.putBusinessInformationItem(epdeitem.getEpde__dataname().trim(), dataToConvertLength);
            } else {
                props.putBusinessInformationItem(epdeitem.getEpde__dataname().trim(), dataString.length());
            }
        }

        if (logger.isLoggable(Level.FINE)) {
            StringBuilder sb = new StringBuilder();

            sb.append(messages.getString("AddedProperty")).append(" ")
                    .append(epdeitem.getEpde__dataname().trim()).append(",")
                    .append(messages.getString("CapturedDataLength")).append(":").append(dataToConvertLength)
                    .append(",").append(messages.getString("CapturedDataInHex")).append(":0x")
                    .append(Util.getHexSummary(dataToConvert)).append(",")
                    .append(messages.getString("CapturedType")).append(":").append(datatype.trim()).append(",")
                    .append(messages.getString("CapturedPrecision")).append(":")
                    .append(epdeitem.getEpde__dataprecision()).append(",").append(conversionSummary).append(",")
                    .append(messages.getString("FormatType")).append(":")
                    .append(epdeitem.getEpde__formattype().trim()).append(",")
                    .append(messages.getString("FormatLength")).append(":")
                    .append(epdeitem.isEpde__formatlen__auto(epdeitem.getEpde__formatlen()) ? "auto"
                            : epdeitem.getEpde__formatlen())
                    .append(",").append(messages.getString("FormatPrecision")).append(":")
                    .append(epdeitem.getEpde__formatprecision());

            if (dataFloat != null) {
                sb.append(",Java Float:").append(dataFloat);
            }

            if (dataBigInteger != null) {
                sb.append(",Java BigInteger:").append(dataBigInteger);
            }

            if (dataLong != null) {
                sb.append(",Java Long:").append(dataLong);
            }

            if (conversionFormat != null) {
                sb.append(",").append(messages.getString("ConversionFormat")).append(":")
                        .append(conversionFormat);
            }

            if (dataString != null) {
                sb.append(",").append(messages.getString("ResultOfConversion")).append(":").append(dataString);
            }

            logger.fine(sb.toString());
        }
    }

    return true;
}

From source file:com.thoughtworks.go.config.MagicalGoConfigXmlWriterTest.java

@Test(timeout = 1000)
public void shouldValidateLeadingAndTrailingSpacesOnExecCommandInReasonableTime() throws Exception {
    // See https://github.com/gocd/gocd/issues/3551
    // This is only reproducible on longish strings, so don't try shortening the exec task length...
    String longPath = StringUtils.repeat("f", 100);
    CruiseConfig config = GoConfigMother.configWithPipelines("pipeline1");
    config.findJob("pipeline1", "stage", "job").addTask(new ExecTask(longPath + " ", "arg1", (String) null));

    output = new ByteArrayOutputStream();
    try {/*  www.  j av a  2  s.c o  m*/
        xmlWriter.write(config, output, false);
        fail("expected to blow up");
    } catch (XsdValidationException e) {
        assertThat(e.getMessage(), containsString("should conform to the pattern - \\S(.*\\S)?"));
    }
}

From source file:info.financialecology.finance.utilities.datastruct.VersatileTimeSeries.java

/**
 * Prints a sequence of '-' characters with a total width covering the length of the time
 * series plus a left-hand row label. /*from ww  w  . j  a  v a 2  s  .c  o m*/
 * <p>
 * @return a sequence of '-' characters covering the time series plus row label
 * @see #printDecoratedRowSeparator(int)
 */
public String printRowSeparator() {
    String ts = "-";
    int nItems = getItemCount();
    int headLength = nItems < internalParams.getOutputHead() ? nItems : internalParams.getOutputHead();
    int tailLength = nItems < internalParams.getOutputHead() ? 0 : nItems - internalParams.getOutputHead();
    tailLength = tailLength < internalParams.getOutputTail() ? tailLength : internalParams.getOutputTail();

    // Covering the time series head with '-'
    for (int i = 0; i < headLength; i++) {
        ts += StringUtils.repeat('-', internalParams.getColumnWidth() + 1);
    }

    if (tailLength > 0)
        ts += "---------"; // to cover the intermediate '...'

    // Covering the time series tail
    for (int i = nItems - tailLength; i < nItems; i++) {
        ts += StringUtils.repeat('-', internalParams.getColumnWidth() + 1);
    }

    return ts + "-";
}

From source file:com.cloudera.impala.analysis.AnalyzeDDLTest.java

@Test
public void TestCreateTable() throws AnalysisException {
    AnalyzesOk("create table functional.new_table (i int)");
    AnalyzesOk("create table if not exists functional.alltypes (i int)");
    AnalysisError("create table functional.alltypes", "Table already exists: functional.alltypes");
    AnalysisError("create table functional.alltypes (i int)", "Table already exists: functional.alltypes");
    AnalyzesOk("create table functional.new_table (i int) row format delimited fields " + "terminated by '|'");

    AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal)");
    AnalyzesOk("create table new_table (i int) PARTITIONED BY (d decimal(3,1))");
    AnalyzesOk("create table new_table(d1 decimal, d2 decimal(10), d3 decimal(5, 2))");
    AnalysisError("create table new_table (i int) PARTITIONED BY (d decimal(40,1))",
            "Decimal precision must be <= 38: 40");

    AnalyzesOk("create table new_table(s1 varchar(1), s2 varchar(32672))");
    AnalysisError("create table new_table(s1 varchar(0))", "Varchar size must be > 0: 0");
    AnalysisError("create table new_table(s1 varchar(65356))", "Varchar size must be <= 65355: 65356");
    AnalysisError("create table new_table(s1 char(0))", "Char size must be > 0: 0");
    AnalysisError("create table new_table(s1 Char(256))", "Char size must be <= 255: 256");
    AnalyzesOk("create table new_table (i int) PARTITIONED BY (s varchar(3))");
    AnalyzesOk("create table functional.new_table (c char(250))");
    AnalyzesOk("create table new_table (i int) PARTITIONED BY (c char(3))");

    {//from   w ww  . j av a  2s. co  m
        // Check that long_properties fail at the analysis layer
        String long_property_key = "";
        for (int i = 0; i < MetaStoreUtil.MAX_PROPERTY_KEY_LENGTH; ++i) {
            long_property_key += 'k';
        }
        String long_property_value = "";
        for (int i = 0; i < MetaStoreUtil.MAX_PROPERTY_VALUE_LENGTH; ++i) {
            long_property_value += 'v';
        }

        // At this point long_property_{key_value} are actually not quite long enough to
        // cause analysis to fail.

        AnalyzesOk("create table new_table (i int) " + "with serdeproperties ('" + long_property_key + "'='"
                + long_property_value + "') " + "tblproperties ('" + long_property_key + "'='"
                + long_property_value + "')");

        long_property_key += 'X';
        long_property_value += 'X';
        // Now that long_property_{key,value} are one character longer, they are too long
        // for the analyzer.

        AnalysisError("create table new_table (i int) " + "tblproperties ('" + long_property_key + "'='value')",
                "Property key length must be <= " + MetaStoreUtil.MAX_PROPERTY_KEY_LENGTH + ": "
                        + (MetaStoreUtil.MAX_PROPERTY_KEY_LENGTH + 1));

        AnalysisError("create table new_table (i int) " + "tblproperties ('key'='" + long_property_value + "')",
                "Property value length must be <= " + MetaStoreUtil.MAX_PROPERTY_VALUE_LENGTH + ": "
                        + (MetaStoreUtil.MAX_PROPERTY_VALUE_LENGTH + 1));

        AnalysisError(
                "create table new_table (i int) " + "with serdeproperties ('" + long_property_key
                        + "'='value')",
                "Serde property key length must be <= " + MetaStoreUtil.MAX_PROPERTY_KEY_LENGTH + ": "
                        + (MetaStoreUtil.MAX_PROPERTY_KEY_LENGTH + 1));

        AnalysisError(
                "create table new_table (i int) " + "with serdeproperties ('key'='" + long_property_value
                        + "')",
                "Serde property value length must be <= " + MetaStoreUtil.MAX_PROPERTY_VALUE_LENGTH + ": "
                        + (MetaStoreUtil.MAX_PROPERTY_VALUE_LENGTH + 1));
    }

    // Supported file formats. Exclude Avro since it is tested separately.
    String[] fileFormats = { "TEXTFILE", "SEQUENCEFILE", "PARQUET", "PARQUETFILE", "RCFILE" };
    for (String format : fileFormats) {
        AnalyzesOk(String.format(
                "create table new_table (i int) " + "partitioned by (d decimal) comment 'c' stored as %s",
                format));
        // No column definitions.
        AnalysisError(
                String.format("create table new_table " + "partitioned by (d decimal) comment 'c' stored as %s",
                        format),
                "Table requires at least 1 column");
    }

    // Note: Backslashes need to be escaped twice - once for Java and once for Impala.
    // For example, if this were a real query the value '\' would be stored in the
    // metastore for the ESCAPED BY field.
    AnalyzesOk("create table functional.new_table (i int) row format delimited fields "
            + "terminated by '\\t' escaped by '\\\\' lines terminated by '\\n'");
    AnalyzesOk("create table functional.new_table (i int) row format delimited fields "
            + "terminated by '\\001' escaped by '\\002' lines terminated by '\\n'");
    AnalyzesOk("create table functional.new_table (i int) row format delimited fields "
            + "terminated by '-2' escaped by '-3' lines terminated by '\\n'");
    AnalyzesOk("create table functional.new_table (i int) row format delimited fields "
            + "terminated by '-128' escaped by '127' lines terminated by '40'");

    AnalysisError(
            "create table functional.new_table (i int) row format delimited "
                    + "fields terminated by '-2' escaped by '128' lines terminated by '\\n'",
            "ESCAPED BY values and LINE/FIELD terminators must be specified as a single "
                    + "character or as a decimal value in the range [-128:127]: 128");
    AnalysisError(
            "create table functional.new_table (i int) row format delimited "
                    + "fields terminated by '-2' escaped by '127' lines terminated by '255'",
            "ESCAPED BY values and LINE/FIELD terminators must be specified as a single "
                    + "character or as a decimal value in the range [-128:127]: 255");
    AnalysisError(
            "create table functional.new_table (i int) row format delimited "
                    + "fields terminated by '-129' escaped by '127' lines terminated by '\\n'",
            "ESCAPED BY values and LINE/FIELD terminators must be specified as a single "
                    + "character or as a decimal value in the range [-128:127]: -129");
    AnalysisError(
            "create table functional.new_table (i int) row format delimited "
                    + "fields terminated by '||' escaped by '\\\\' lines terminated by '\\n'",
            "ESCAPED BY values and LINE/FIELD terminators must be specified as a single "
                    + "character or as a decimal value in the range [-128:127]: ||");

    // IMPALA-2251: it should not be possible to create text tables with the same
    // delimiter character used for multiple purposes.
    AnalysisError(
            "create table functional.broken_text_table (c int) "
                    + "row format delimited fields terminated by '\001' lines terminated by '\001'",
            "Field delimiter and line delimiter have same value: byte 1");
    AnalysisError(
            "create table functional.broken_text_table (c int) "
                    + "row format delimited lines terminated by '\001'",
            "Field delimiter and line delimiter have same value: byte 1");
    AnalysisError(
            "create table functional.broken_text_table (c int) "
                    + "row format delimited fields terminated by '\012'",
            "Field delimiter and line delimiter have same value: byte 10");
    AnalyzesOk("create table functional.broken_text_table (c int) " + "row format delimited escaped by '\001'",
            "Field delimiter and escape character have same value: byte 1. "
                    + "Escape character will be ignored");
    AnalyzesOk(
            "create table functional.broken_text_table (c int) "
                    + "row format delimited escaped by 'x' lines terminated by 'x'",
            "Line delimiter and escape character have same value: byte 120. "
                    + "Escape character will be ignored");

    AnalysisError("create table db_does_not_exist.new_table (i int)",
            "Database does not exist: db_does_not_exist");
    AnalysisError("create table new_table (i int, I string)", "Duplicate column name: i");
    AnalysisError("create table new_table (c1 double, col2 int, c1 double, c4 string)",
            "Duplicate column name: c1");
    AnalysisError("create table new_table (i int, s string) PARTITIONED BY (i int)",
            "Duplicate column name: i");
    AnalysisError("create table new_table (i int) PARTITIONED BY (C int, c2 int, c int)",
            "Duplicate column name: c");

    // Unsupported partition-column types.
    AnalysisError("create table new_table (i int) PARTITIONED BY (t timestamp)",
            "Type 'TIMESTAMP' is not supported as partition-column type in column: t");

    // Caching ops
    AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) " + "cached in 'testPool'");
    AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) uncached");
    AnalyzesOk("create table cached_tbl(i int) partitioned by(j int) "
            + "location '/test-warehouse/' cached in 'testPool'");
    AnalyzesOk(
            "create table cached_tbl(i int) partitioned by(j int) " + "location '/test-warehouse/' uncached");
    AnalysisError(
            "create table cached_tbl(i int) location "
                    + "'file:///test-warehouse/cache_tbl' cached in 'testPool'",
            "Location 'file:/test-warehouse/cache_tbl' cannot be cached. "
                    + "Please retry without caching: CREATE TABLE default.cached_tbl ... UNCACHED");

    // Invalid database name.
    AnalysisError("create table `???`.new_table (x int) PARTITIONED BY (y int)", "Invalid database name: ???");
    // Invalid table/view name.
    AnalysisError("create table functional.`^&*` (x int) PARTITIONED BY (y int)",
            "Invalid table/view name: ^&*");
    // Invalid column names.
    AnalysisError("create table new_table (`???` int) PARTITIONED BY (i int)",
            "Invalid column/field name: ???");
    AnalysisError("create table new_table (i int) PARTITIONED BY (`^&*` int)",
            "Invalid column/field name: ^&*");
    // Test HMS constraint on type name length.
    AnalyzesOk(String.format("create table t (i %s)", genTypeSql(MetaStoreUtil.MAX_TYPE_NAME_LENGTH)));
    AnalysisError(String.format("create table t (i %s)", genTypeSql(MetaStoreUtil.MAX_TYPE_NAME_LENGTH + 1)),
            "Type of column 'i' exceeds maximum type length of 4000 characters:");
    // Test HMS constraint on comment length.
    AnalyzesOk(String.format("create table t (i int comment '%s')",
            StringUtils.repeat("c", MetaStoreUtil.CREATE_MAX_COMMENT_LENGTH)));
    AnalysisError(
            String.format("create table t (i int comment '%s')",
                    StringUtils.repeat("c", MetaStoreUtil.CREATE_MAX_COMMENT_LENGTH + 1)),
            "Comment of column 'i' exceeds maximum length of 256 characters:");

    // Valid URI values.
    AnalyzesOk("create table tbl (i int) location '/test-warehouse/new_table'");
    AnalyzesOk("create table tbl (i int) location " + "'hdfs://localhost:20500/test-warehouse/new_table'");
    AnalyzesOk("create table tbl (i int) location " + "'file:///test-warehouse/new_table'");
    AnalyzesOk("create table tbl (i int) location " + "'s3n://bucket/test-warehouse/new_table'");
    AnalyzesOk("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " + "'file://test-warehouse/new_table'");

    // Invalid URI values.
    AnalysisError("create table functional.foo (x int) location " + "'foofs://test-warehouse/new_table'",
            "No FileSystem for scheme: foofs");
    AnalysisError("create table functional.foo (x int) location " + "'  '", "URI path cannot be empty.");
    AnalysisError(
            "ALTER TABLE functional_seq_snap.alltypes SET LOCATION " + "'foofs://test-warehouse/new_table'",
            "No FileSystem for scheme: foofs");
    AnalysisError("ALTER TABLE functional_seq_snap.alltypes SET LOCATION " + "'  '",
            "URI path cannot be empty.");

    // Create table PRODUCED BY DATA SOURCE
    final String DATA_SOURCE_NAME = "TestDataSource1";
    catalog_.addDataSource(new DataSource(DATA_SOURCE_NAME, "/foo.jar", "foo.Bar", "V1"));
    AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " + DATA_SOURCE_NAME);
    AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " + DATA_SOURCE_NAME.toLowerCase());
    AnalyzesOk("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " + DATA_SOURCE_NAME + "(\"\")");
    AnalyzesOk("CREATE TABLE DataSrcTable1 (a tinyint, b smallint, c int, d bigint, "
            + "e float, f double, g boolean, h string) PRODUCED BY DATA SOURCE " + DATA_SOURCE_NAME);
    AnalysisError("CREATE TABLE DataSrcTable1 (x int) PRODUCED BY DATA SOURCE " + "not_a_data_src(\"\")",
            "Data source does not exist");
    for (Type t : Type.getSupportedTypes()) {
        PrimitiveType type = t.getPrimitiveType();
        if (DataSourceTable.isSupportedPrimitiveType(type) || t.isNull())
            continue;
        String typeSpec = type.name();
        if (type == PrimitiveType.CHAR || type == PrimitiveType.DECIMAL || type == PrimitiveType.VARCHAR) {
            typeSpec += "(10)";
        }
        AnalysisError(
                "CREATE TABLE DataSrcTable1 (x " + typeSpec + ") PRODUCED " + "BY DATA SOURCE "
                        + DATA_SOURCE_NAME,
                "Tables produced by an external data source do not support the column type: " + type.name());
    }
}

From source file:com.cloudera.impala.analysis.AnalyzeDDLTest.java

/**
 * Generates a valid type string with exactly the given number of characters.
 * The type is a struct with at least two fields.
 * The given length must be at least "struct<s:int,c:int>".length() == 19.
 *///from  w  ww .jav a  2 s.c  o  m
private String genTypeSql(int length) {
    Preconditions.checkState(length >= 19);
    StringBuilder result = new StringBuilder();
    result.append("struct<s:int");
    // The middle fields always have a fixed length.
    int midFieldLen = ",f000:int".length();
    // The last field has a variable length, but this is the minimum.
    int lastFieldMinLen = ",f:int".length();
    int fieldIdx = 0;
    while (result.length() < length - midFieldLen - lastFieldMinLen) {
        String fieldStr = String.format(",f%03d:int", fieldIdx);
        result.append(fieldStr);
        ++fieldIdx;
    }
    Preconditions.checkState(result.length() == length - 1 || result.length() < length - lastFieldMinLen);
    // Generate last field with a variable length.
    if (result.length() < length - 1) {
        int fieldNameLen = length - result.length() - ",:int".length() - 1;
        Preconditions.checkState(fieldNameLen > 0);
        String fieldStr = String.format(",%s:int", StringUtils.repeat("f", fieldNameLen));
        result.append(fieldStr);
    }
    result.append(">");
    Preconditions.checkState(result.length() == length);
    return result.toString();
}

From source file:com.evolveum.midpoint.model.impl.lens.TestAssignmentProcessor2.java

private String createName(String prefix, int level, int number) {
    return StringUtils.repeat('M', level - 1) + prefix + number;
}

From source file:com.quinsoft.zeidon.standardoe.EntityInstanceImpl.java

@Override
public void logEntity(boolean logChildren, int indentN) {
    EntityDef entityDef = getEntityDef();
    String indent = StringUtils.repeat("    ", indentN);

    StringBuilder flagStr = new StringBuilder();
    if (isUpdated())
        flagStr.append(" Updated");
    if (isCreated())
        flagStr.append(" Created");
    if (isIncluded())
        flagStr.append(" Included");
    if (isDeleted())
        flagStr.append(" Deleted");
    if (isExcluded())
        flagStr.append(" Excluded");

    getTask().log().info("%s[%s] %s (%x:%d)", indent, entityDef.getName(), flagStr, hashCode(), getEntityKey());
    for (AttributeDef attributeDef : getNonNullAttributeList()) {
        AttributeInstanceImpl attrib = getAttribute(attributeDef);
        String value = attrib.getString(null);
        //            if ( ( flags & View.DISPLAY_EMPTY_ATTRIBS ) == 0 && StringUtils.isBlank( value ) )
        //                continue;
        ///*from  w ww.  j  av a2 s.c o m*/
        //            if ( ( flags & View.DISPLAY_HIDDEN ) == 0 && attributeDef.isHidden() )
        //                continue;

        getTask().log().info("%s   (%s)%s: %s", indent, attrib.isUpdated() ? "#" : "~", attributeDef.getName(),
                value);
    }

    if (logChildren) {
        for (EntityInstance ei : getDirectChildren())
            ei.logEntity(logChildren, indentN + 1);
    }
}

From source file:com.evolveum.midpoint.model.impl.lens.TestAssignmentProcessor2.java

private static String getRoleOid(String name) {
    name = name.substring(0, Math.min(12, name.length()));
    return "99999999-0000-0000-0000-" + StringUtils.repeat('0', 12 - name.length()) + name;
}