Example usage for java.lang StringBuffer StringBuffer

List of usage examples for java.lang StringBuffer StringBuffer

Introduction

In this page you can find the example usage for java.lang StringBuffer StringBuffer.

Prototype

public StringBuffer(CharSequence seq) 

Source Link

Document

Constructs a string buffer that contains the same characters as the specified CharSequence .

Usage

From source file:CreateTableAllTypesInOracle.java

public static void main(String[] args) {
    PreparedStatement pstmt = null;
    Connection conn = null;/*from  w ww.java 2s  .c om*/
    try {
        conn = getConnection();
        pstmt = conn.prepareStatement("CREATE TYPE varray_type is VARRAY(5) OF VARCHAR(10)");
        pstmt.executeUpdate();
        // Create an OBJECT type
        pstmt = conn.prepareStatement(
                "CREATE TYPE oracle_object is OBJECT(column_string VARCHAR(128), column_integer INTEGER)");
        pstmt.executeUpdate();

        StringBuffer allTypesTable = new StringBuffer("CREATE TABLE oracle_all_types(");
        //                    Column Name          Oracle Type              Java Type
        allTypesTable.append("column_short           SMALLINT, "); // short
        allTypesTable.append("column_int             INTEGER, "); // int
        allTypesTable.append("column_float           REAL, "); // float; can also be NUMBER
        allTypesTable.append("column_double          DOUBLE PRECISION, "); // double; can also be FLOAT or NUMBER
        allTypesTable.append("column_bigdecimal      DECIMAL(13,0), "); // BigDecimal
        allTypesTable.append("column_string          VARCHAR2(254), "); // String; can also be CHAR(n)
        allTypesTable.append("column_characterstream LONG, "); // CharacterStream or AsciiStream
        allTypesTable.append("column_bytes           RAW(2000), "); // byte[]; can also be LONG RAW(n)
        allTypesTable.append("column_binarystream    RAW(2000), "); // BinaryStream; can also be LONG RAW(n)
        allTypesTable.append("column_timestamp       DATE, "); // Timestamp
        allTypesTable.append("column_clob            CLOB, "); // Clob
        allTypesTable.append("column_blob            BLOB, "); // Blob; can also be BFILE
        allTypesTable.append("column_bfile           BFILE, "); // oracle.sql.BFILE
        allTypesTable.append("column_array           varray_type, "); // oracle.sql.ARRAY
        allTypesTable.append("column_object          oracle_object)"); // oracle.sql.OBJECT

        pstmt.executeUpdate(allTypesTable.toString());
    } catch (Exception e) {
        // creation of table failed.
        // handle the exception
        e.printStackTrace();
    }
}

From source file:TextVerifyInputFormatDate.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    ;//from   w  ww  . j a va  2 s.  c  o m
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuffer buffer = new StringBuffer(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M */
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuffer date = new StringBuffer(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:InsertDemo.java

public static void main(String[] args) {
    StringBuffer palindrome = new StringBuffer("A man, a plan, a canal; Panama.");
    palindrome.insert(15, "a cat, ");
    System.out.println(palindrome);
}

From source file:StringsDemo.java

public static void main(String[] args) {
    String palindrome = "Dot saw I was Tod";
    int len = palindrome.length();
    StringBuffer dest = new StringBuffer(len);

    for (int i = (len - 1); i >= 0; i--) {
        dest.append(palindrome.charAt(i));
    }//from  w  ww  . j a v  a2s.  c  o  m
    System.out.println(dest.toString());
}

From source file:StringRevChar.java

public static void main(String[] argv) {
    //+/* w  ww  . j a v  a2s. c o m*/
    String sh = "FCGDAEB";
    System.out.println(sh + " -> " + new StringBuffer(sh).reverse());
    //-
}

From source file:es.upv.grycap.opengateway.examples.AppDaemon.java

/**
 * Main entry point to the application.//from  w ww.jav a  2s . c o m
 * @param args - arguments passed to the application
 * @throws Exception - if the application fails to start the required services
 */
public static void main(final String[] args) throws Exception {
    final AppDaemon daemon = new AppDaemon();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                daemon.stop();
            } catch (Exception e) {
                System.err.println(
                        new StringBuffer("Failed to stop application: ").append(e.getMessage()).toString());
            }
            try {
                daemon.destroy();
            } catch (Exception e) {
                System.err.println(
                        new StringBuffer("Failed to stop application: ").append(e.getMessage()).toString());
            }
        }
    });
    daemon.init(new DaemonContext() {
        @Override
        public DaemonController getController() {
            return null;
        }

        @Override
        public String[] getArguments() {
            return args;
        }
    });
    daemon.start();
}

From source file:TextVerifyInputRegularExpression.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);// w  ww  .  j  av a 2 s.  c  o m
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        // create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);

        // ignore event when caused by inserting text inside event handler
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuffer buffer = new StringBuffer(e.text);

            // handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuffer newText = new StringBuffer(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:DataIODemo.java

public static void main(String[] args) throws IOException {

    // write the data out
    DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt"));

    double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    int[] units = { 12, 8, 13, 29, 50 };
    String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);/*from  w  ww. java  2  s . c  o  m*/
        out.writeChar('\t');
        out.writeInt(units[i]);
        out.writeChar('\t');
        out.writeChars(descs[i]);
        out.writeChar('\n');
    }
    out.close();

    // read it in again
    DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt"));

    double price;
    int unit;
    StringBuffer desc;
    double total = 0.0;

    try {
        while (true) {
            price = in.readDouble();
            in.readChar(); // throws out the tab
            unit = in.readInt();
            in.readChar(); // throws out the tab
            char chr;
            desc = new StringBuffer(20);
            char lineSep = System.getProperty("line.separator").charAt(0);
            while ((chr = in.readChar()) != lineSep)
                desc.append(chr);
            System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
            total = total + unit * price;
        }
    } catch (EOFException e) {
    }
    System.out.println("For a TOTAL of: $" + total);
    in.close();
}

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w  ww.  j a  va  2  s.  co m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.digitalgeneralists.assurance.Application.java

public static void main(String[] args) {
    Logger logger = Logger.getLogger(Application.class);

    logger.info("App is starting.");

    Properties applicationProperties = new Properties();
    String applicationInfoFileName = "/version.txt";
    InputStream inputStream = Application.class.getResourceAsStream(applicationInfoFileName);
    applicationInfoFileName = null;/*from   w w w . j av  a  2  s.co m*/

    try {
        if (inputStream != null) {
            applicationProperties.load(inputStream);

            Application.applicationShortName = applicationProperties.getProperty("name");
            Application.applicationName = applicationProperties.getProperty("applicationName");
            Application.applicationVersion = applicationProperties.getProperty("version");
            Application.applicationBuildNumber = applicationProperties.getProperty("buildNumber");

            applicationProperties = null;
        }
    } catch (IOException e) {
        logger.warn("Could not load application version information.", e);
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            logger.error("Couldn't close the application version input stream.");
        }
        inputStream = null;
    }

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        private Logger logger = Logger.getLogger(Application.class);

        public void run() {
            logger.info("Starting the Swing run thread.");

            try {
                Application.installDb();
            } catch (IOException e) {
                logger.fatal("Unable to install the application database.", e);
                System.exit(1);
            } catch (SQLException e) {
                logger.fatal("Unable to install the application database.", e);
                System.exit(1);
            }

            IApplicationUI window = null;
            ClassPathXmlApplicationContext springContext = null;
            try {
                springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
                StringBuffer message = new StringBuffer(256);
                logger.info(message.append("Spring Context: ").append(springContext));
                message.setLength(0);
                window = (IApplicationUI) springContext.getBean("ApplicationUI");
            } finally {
                if (springContext != null) {
                    springContext.close();
                }
                springContext = null;
            }

            if (window != null) {
                logger.info("Launching the window.");
                window.display();
            } else {
                logger.fatal("The main application window object is null.");
            }

            logger = null;
        }
    });
}