Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

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

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:com.impetus.client.cassandra.query.CassQuery.java

/**
 * Create Update CQL query from a given JPA query.
 * /* ww  w  . j  a  va2s .  co m*/
 * @param kunderaQuery
 *            the kundera query
 * @return the string
 */
public String createUpdateQuery(KunderaQuery kunderaQuery) {
    EntityMetadata metadata = kunderaQuery.getEntityMetadata();
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(metadata.getPersistenceUnit());

    CQLTranslator translator = new CQLTranslator();
    String update_Query = translator.UPDATE_QUERY;

    String tableName = metadata.getTableName();
    update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());

    StringBuilder builder = new StringBuilder(update_Query);

    Object ttlColumns = ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).getTtlValues()
            .get(metadata.getTableName());

    if ((ttlColumns != null && ttlColumns instanceof Integer) || this.ttl != null) {
        int ttl = this.ttl != null ? this.ttl : ((Integer) ttlColumns).intValue();
        if (ttl != 0) {
            builder.append(" USING TTL ");
            builder.append(ttl);
            builder.append(" ");
        }
    }

    builder.append(CQLTranslator.ADD_SET_CLAUSE);

    for (UpdateClause updateClause : kunderaQuery.getUpdateClauseQueue()) {

        String property = updateClause.getProperty();

        String jpaColumnName = getColumnName(metadata, property);

        Object value = updateClause.getValue();

        translator.buildSetClause(metadata, builder, jpaColumnName, value);
    }
    builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());
    builder.append(CQLTranslator.ADD_WHERE_CLAUSE);

    Class compoundKeyClass = metadata.getIdAttribute().getBindableJavaType();
    EmbeddableType compoundKey = null;
    String idColumn;
    if (metaModel.isEmbeddable(compoundKeyClass)) {
        compoundKey = metaModel.embeddable(compoundKeyClass);
        idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
    } else {
        idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
    }

    onCondition(metadata, metaModel, compoundKey, idColumn, builder, false, translator, false);

    return builder.toString();
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

public void testAuditAuthenticationService() throws Exception {
    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);/*from w w  w.j a  v  a  2 s.c o  m*/
    params.setApplicationName(APPLICATION_API_TEST);

    // Load in the config for this specific test: alfresco-audit-test-authenticationservice.xml
    URL testModelUrl = ResourceUtils
            .getURL("classpath:alfresco/testaudit/alfresco-audit-test-authenticationservice.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            if (logger.isDebugEnabled()) {
                logger.debug("Audit Entry " + entryId + ": " + applicationName + ", " + user + ", "
                        + new Date(time) + "\n" + "   Data: " + values);
            }
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_API_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    final MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
    // Create a good authentication
    RunAsWork<Void> createAuthenticationWork = new RunAsWork<Void>() {
        public Void doWork() throws Exception {
            if (!authenticationService.authenticationExists(getName())) {
                authenticationService.createAuthentication(getName(), getName().toCharArray());
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(createAuthenticationWork, AuthenticationUtil.getSystemUserName());

    // Clear everything out and do a successful authentication
    clearAuditLog(APPLICATION_API_TEST);
    try {
        AuthenticationUtil.pushAuthentication();
        authenticationService.authenticate(getName(), getName().toCharArray());
    } finally {
        AuthenticationUtil.popAuthentication();
    }

    // Check that the call was audited
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertFalse("Did not get any audit results after successful login", results.isEmpty());

    // Clear everything and check that unsuccessful authentication was audited
    clearAuditLog(APPLICATION_API_TEST);
    int iterations = 1000;
    for (int i = 0; i < iterations; i++) {
        try {
            AuthenticationUtil.pushAuthentication();
            authenticationService.authenticate("banana", "****".toCharArray());
            fail("Invalid authentication attempt should fail");
        } catch (AuthenticationException e) {
            // Expected
        } finally {
            AuthenticationUtil.popAuthentication();
        }
    }

    // ALF-3055 : auditing of failures is now asynchronous, so loop up to 60 times with
    // a 5 second sleep to ensure that the audit is processed
    for (int i = 0; i < 60; i++) {
        results.clear();
        sb.delete(0, sb.length());
        queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
        if (results.size() == iterations) {
            break;
        }
        Thread.sleep(5000);
    }

    logger.debug(sb.toString());
    assertEquals("Incorrect number of audit entries after failed login", iterations, results.size());

    // Check that we can delete explicit entries
    long before = System.currentTimeMillis();
    deleteAuditEntries(results);
    System.out.println("Clearing " + results.size() + " entries by ID took "
            + (System.currentTimeMillis() - before) + "ms.");
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertEquals("Explicit audit entries were not deleted", 0, results.size());
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMAppBlock.java

@Override
protected void generateApplicationTable(Block html, UserGroupInformation callerUGI,
        Collection<ApplicationAttemptReport> attempts) {
    // Application Attempt Table
    Hamlet.TBODY<Hamlet.TABLE<Hamlet>> tbody = html.table("#attempts").thead().tr().th(".id", "Attempt ID")
            .th(".started", "Started").th(".node", "Node").th(".logs", "Logs")
            .th(".appBlacklistednodes", "Nodes blacklisted by the application", "Nodes blacklisted by the app")
            .th(".rmBlacklistednodes", "Nodes blacklisted by the RM for the" + " app",
                    "Nodes blacklisted by the system")
            ._()._().tbody();/*from  w w w  .j  a  v a 2 s .  co m*/

    RMApp rmApp = this.rm.getRMContext().getRMApps().get(this.appID);
    if (rmApp == null) {
        return;
    }
    StringBuilder attemptsTableData = new StringBuilder("[\n");
    for (final ApplicationAttemptReport appAttemptReport : attempts) {
        RMAppAttempt rmAppAttempt = rmApp.getRMAppAttempt(appAttemptReport.getApplicationAttemptId());
        if (rmAppAttempt == null) {
            continue;
        }
        AppAttemptInfo attemptInfo = new AppAttemptInfo(this.rm, rmAppAttempt, rmApp.getUser(),
                WebAppUtils.getHttpSchemePrefix(conf));
        Set<String> nodes = rmAppAttempt.getBlacklistedNodes();
        // nodes which are blacklisted by the application
        String appBlacklistedNodesCount = String.valueOf(nodes.size());
        // nodes which are blacklisted by the RM for AM launches
        String rmBlacklistedNodesCount = String.valueOf(
                rmAppAttempt.getAMBlacklistManager().getBlacklistUpdates().getBlacklistAdditions().size());
        String nodeLink = attemptInfo.getNodeHttpAddress();
        if (nodeLink != null) {
            nodeLink = WebAppUtils.getHttpSchemePrefix(conf) + nodeLink;
        }
        String logsLink = attemptInfo.getLogsLink();
        attemptsTableData.append("[\"<a href='")
                .append(url("appattempt", rmAppAttempt.getAppAttemptId().toString())).append("'>")
                .append(String.valueOf(rmAppAttempt.getAppAttemptId())).append("</a>\",\"")
                .append(attemptInfo.getStartTime()).append("\",\"<a ")
                .append(nodeLink == null ? "#" : "href='" + nodeLink).append("'>")
                .append(nodeLink == null ? "N/A"
                        : StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(nodeLink)))
                .append("</a>\",\"<a ").append(logsLink == null ? "#" : "href='" + logsLink).append("'>")
                .append(logsLink == null ? "N/A" : "Logs").append("</a>\",").append("\"")
                .append(appBlacklistedNodesCount).append("\",").append("\"").append(rmBlacklistedNodesCount)
                .append("\"],\n");
    }
    if (attemptsTableData.charAt(attemptsTableData.length() - 2) == ',') {
        attemptsTableData.delete(attemptsTableData.length() - 2, attemptsTableData.length() - 1);
    }
    attemptsTableData.append("]");
    html.script().$type("text/javascript")._("var attemptsTableData=" + attemptsTableData)._();

    tbody._()._();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.AppsBlock.java

@Override
public void render(Block html) {
    TBODY<TABLE<Hamlet>> tbody = html.table("#apps").thead().tr().th(".id", "ID").th(".user", "User")
            .th(".name", "Name").th(".type", "Application Type").th(".queue", "Queue")
            .th(".starttime", "StartTime").th(".finishtime", "FinishTime").th(".state", "State")
            .th(".finalstatus", "FinalStatus").th(".progress", "Progress").th(".ui", "Tracking UI")._()._()
            .tbody();//from   w ww  .ja v a 2 s. co  m
    Collection<YarnApplicationState> reqAppStates = null;
    String reqStateString = $(APP_STATE);
    if (reqStateString != null && !reqStateString.isEmpty()) {
        String[] appStateStrings = reqStateString.split(",");
        reqAppStates = new HashSet<YarnApplicationState>(appStateStrings.length);
        for (String stateString : appStateStrings) {
            reqAppStates.add(YarnApplicationState.valueOf(stateString));
        }
    }
    StringBuilder appsTableData = new StringBuilder("[\n");
    for (RMApp app : apps.values()) {
        if (reqAppStates != null && !reqAppStates.contains(app.createApplicationState())) {
            continue;
        }
        AppInfo appInfo = new AppInfo(app, true, WebAppUtils.getHttpSchemePrefix(conf));
        String percent = String.format("%.1f", appInfo.getProgress());
        //AppID numerical value parsed by parseHadoopID in yarn.dt.plugins.js
        appsTableData.append("[\"<a href='").append(url("app", appInfo.getAppId())).append("'>")
                .append(appInfo.getAppId()).append("</a>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getUser())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getName())))
                .append("\",\"")
                .append(StringEscapeUtils
                        .escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getApplicationType())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getQueue())))
                .append("\",\"").append(appInfo.getStartTime()).append("\",\"").append(appInfo.getFinishTime())
                .append("\",\"").append(appInfo.getState()).append("\",\"").append(appInfo.getFinalStatus())
                .append("\",\"")
                // Progress bar
                .append("<br title='").append(percent).append("'> <div class='").append(C_PROGRESSBAR)
                .append("' title='").append(join(percent, '%')).append("'> ").append("<div class='")
                .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", percent, '%'))
                .append("'> </div> </div>").append("\",\"<a href='");

        String trackingURL = !appInfo.isTrackingUrlReady() ? "#" : appInfo.getTrackingUrlPretty();

        appsTableData.append(trackingURL).append("'>").append(appInfo.getTrackingUI()).append("</a>\"],\n");

    }
    if (appsTableData.charAt(appsTableData.length() - 2) == ',') {
        appsTableData.delete(appsTableData.length() - 2, appsTableData.length() - 1);
    }
    appsTableData.append("]");
    html.script().$type("text/javascript")._("var appsTableData=" + appsTableData)._();

    tbody._()._();
}

From source file:br.com.atmatech.sac.view.ViewAtendimento.java

private String adcQuebraPagina(String txt) {
    //ajusta solicitacao
    StringBuilder str = new StringBuilder();
    StringBuilder strt = new StringBuilder();
    int count = 0;
    Boolean fin = false;/*  w w w  .  j a  v a  2  s.c o  m*/
    if (txt != null) {
        if (txt.length() > 40) {
            str.delete(0, str.length());
            str.append("<html>");
            for (int i = 0, x = 0; i < txt.length(); i++, x++) {
                if (x == 40) {
                    str.append(txt.substring(count, i));
                    str.append("<br>");

                    count = i;
                    fin = true;
                    x = 0;
                    strt.delete(0, strt.length());
                } else {
                    fin = false;
                    strt.delete(0, strt.length());
                    strt.append(txt.substring(count, txt.length()));

                }
            }
            if (fin) {
                str.append("</html>");
            } else {
                str.append(strt);
                str.append("<br>");
                str.append("</html>");
            }

        } else {
            str.delete(0, str.length());
            str.append(txt);
        }
    }
    return str.toString();
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.S2SAdobeFormAttachmentBaseGenerator.java

/**
 * /* w w w .  ja v  a 2s .c om*/
 * This method is used to return the attachment name which comes from BudgetSubawards
 * 
 * @param budgetSubAwards(BudgetSubAwards) budget sub award entry.
 * @return String attachment name for the budget sub awards.
 */
protected String prepareAttName(BudgetSubAwardsContract budgetSubAwards) {
    StringBuilder attachmentName = new StringBuilder();
    boolean hasSameFileName = false;
    boolean isAlreadyprinted = false;
    int attachmentCount = 0;
    int suffix = 1;

    int index = 0;
    for (String budgetId : budgetIdList) {

        if (budgetSubAwards.getBudgetId().toString().equals(budgetId)) {
            if (budgetSubawardNumberList.get(index).equals(budgetSubAwards.getSubAwardNumber().toString())) {
                attachmentList.clear();
                isAlreadyprinted = true;
                break;
            }
        }
        index++;
    }
    if (isAlreadyprinted) {
        budgetIdList.clear();
        budgetSubawardNumberList.clear();
    }

    //checking organization name and replacing invalid characters
    // with underscores.
    String cleanSubAwardOrganizationName = checkAndReplaceInvalidCharacters(
            budgetSubAwards.getOrganizationName());
    attachmentName.append(cleanSubAwardOrganizationName);
    BudgetContract budget = findBudgetFromProposal();
    List<? extends BudgetSubAwardsContract> budgetSubAwardsList = budget.getBudgetSubAwards();
    ArrayList<String> attachments = new ArrayList<>();
    for (BudgetSubAwardsContract budgetSubAward : budgetSubAwardsList) {
        StringBuilder existingAttachmentName = new StringBuilder();
        String subAward_OrganizationName = checkAndReplaceInvalidCharacters(
                budgetSubAward.getOrganizationName());
        existingAttachmentName.append(subAward_OrganizationName);
        attachments.add(existingAttachmentName.toString());
    }
    for (String attachment : attachments) {
        if (attachment.equals(attachmentName.toString())) {
            attachmentCount++;
        }
    }
    if (attachmentCount > 1 && !attachmentList.contains(attachmentName.toString())) {
        attachmentList.add(attachmentName.toString());
        if (attachmentName.length() > 49) {
            attachmentName.delete(49, attachmentName.length());
        }
        attachmentName.append(1);
        hasSameFileName = true;
    } else {
        for (String attachment : attachmentList) {
            if (attachment.equals(attachmentName.toString())) {
                suffix++;
            }
        }
    }
    if (attachmentList.contains(attachmentName.toString()) && !hasSameFileName) {
        attachmentList.add(attachmentName.toString());
        if (attachmentName.length() > 49) {
            attachmentName.delete(49, attachmentName.length());
        }
        attachmentName.append(suffix);
    } else {
        attachmentList.add(attachmentName.toString());
    }
    budgetIdList.add(budgetSubAwards.getBudgetId().toString());
    budgetSubawardNumberList.add(budgetSubAwards.getSubAwardNumber().toString());
    return attachmentName.toString();
}

From source file:com.flexive.shared.scripting.groovy.GroovyScriptExporterTools.java

/**
 * Write the script code to create a group
 *
 * @param ga                          the FxGroupAssignment to be scripted
 * @param childAssignments            a List of child assignments for the given group
 * @param groupAssignments            the map of FxGroupAssignments (keys) and their respective Lists of FxAssignments (values)
 * @param isDerived                   set to "true" if the assignment to be written is derived from another property
 * @param defaultsOnly                use only default settings provided by the GTB, no analysis of assignments will be performed
 * @param callOnlyGroups              a List of FxGroupAssignments for which no options should be generated
 * @param tabCount                    the number of tabs to be added to the code's left hand side
 * @param withoutDependencies         true = do not create assignment:xpath code
 * @param differingDerivedAssignments the List of assignment ids for derived assignments differing from their base assignments
 * @return returns the partial script as a String
 *//* w  w  w.j a  va 2  s .  co m*/
public static String createGroup(FxGroupAssignment ga, List<FxAssignment> childAssignments,
        Map<FxGroupAssignment, List<FxAssignment>> groupAssignments, boolean isDerived, boolean defaultsOnly,
        List<FxGroupAssignment> callOnlyGroups, int tabCount, boolean withoutDependencies,
        List<Long> differingDerivedAssignments) {
    final StringBuilder script = new StringBuilder(200);

    if (!isDerived || withoutDependencies) {
        final FxGroup group = ga.getGroup();
        // NAME
        script.append(Indent.tabs(tabCount));
        final String groupName = keyWordNameCheck(group.getName().toUpperCase(), true);
        script.append(groupName).append("( "); // opening parenthesis + 1x \s

        // CHECK IF THIS GROUP WAS CREATED BEFOREHAND AND ONLY NEEDS TO BE CALLED FOR STRUCTURE CREATION
        if (callOnlyGroups == null || (callOnlyGroups != null && !callOnlyGroups.contains(ga))) {

            if (!defaultsOnly) {
                tabCount++; // add tabs for options
                script.append("\n");
                // label and hint
                script.append(getLabelAndHintStructure(group, true, true, tabCount));

                Map<String, String> sopts = new LinkedHashMap<String, String>();
                sopts.put("alias", "\"" + ga.getAlias() + "\"");
                sopts.put("defaultMultiplicity", ga.getDefaultMultiplicity() + "");
                sopts.put("overrideMultiplicity", group.mayOverrideBaseMultiplicity() + "");
                sopts.put("multiplicity", "new FxMultiplicity(" + group.getMultiplicity().getMin() + ","
                        + group.getMultiplicity().getMax() + ")");
                sopts.put("groupMode", "GroupMode." + ga.getMode().name());

                // FxStructureOptions via the GroovyOptionbuilder
                script.append(getStructureOptions(group, tabCount));

                // append options to script
                for (String option : sopts.keySet()) {
                    script.append(simpleOption(option, sopts.get(option), tabCount));
                }

                script.trimToSize();
                if (script.indexOf(",\n", script.length() - 2) != -1)
                    script.delete(script.length() - 2, script.length());

                --tabCount; // remove tab again
            }
        }

        script.append(") "); // closing parenthesis + 1x \s
        // if the difference analyser yields any data, change the assignment in the next line (only launch if defaultsOnly = false)
        if (!defaultsOnly) {
            final List<String> differences = AssignmentDifferenceAnalyser.analyse(ga, false);
            if (differences.size() > 0) {
                script.append(updateGroupAssignment(ga, false, differences, defaultsOnly, tabCount,
                        withoutDependencies, differingDerivedAssignments));
            }
        }
    } else { // DERIVED GROUP ASSIGNMENTS
        final List<String> differences = AssignmentDifferenceAnalyser.analyse(ga, true);
        script.append(updateGroupAssignment(ga, true, differences, defaultsOnly, tabCount, withoutDependencies,
                differingDerivedAssignments));
    }

    // add child assignments ******************************
    if (childAssignments != null && childAssignments.size() > 0) {
        script.append("{\n"); // closing parenthesis and curly bracket
        // if childAssignments != null && size() == 0, then we are calling for derived groups in derived types
        // --> remove current group from groupAssignments to avoid infinite recursions
        if (differingDerivedAssignments != null && differingDerivedAssignments.size() > 0) {
            groupAssignments.remove(ga);
        }
        script.append(createChildAssignments(childAssignments, groupAssignments, defaultsOnly, callOnlyGroups,
                ++tabCount, withoutDependencies, differingDerivedAssignments));
        script.append(Indent.tabs(--tabCount));
        script.append("}"); // closing curly bracket
    }

    script.append("\n");
    script.trimToSize();
    return script.toString();
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private ContentElement getSpecialLinks(SpanManager sm, List<Span> linkSpans, List<Link> links,
        String linkSpacer, List<String> identifers) {
    ContentElement result = new ContentElement();
    StringBuilder text = new StringBuilder();
    List<Link> localLinks = new ArrayList<Link>();

    for (int i = links.size() - 1; i >= 0; i--) {
        String identifer = getLinkNameSpace(links.get(i).getTarget());

        if (identifer != null && identifers.indexOf(identifer) != -1) {
            Link l = links.remove(i);/*from  w w  w  .  ja v a  2  s  . co  m*/
            Span s = linkSpans.remove(i);
            String linkText = sm.substring(s);
            sm.delete(s);
            l.setHomeElement(result);
            s.adjust(-s.getStart() + text.length());
            text.append(linkText + linkSpacer);
            localLinks.add(l);
            //TODO add type?
        }
    }

    int len = text.length();
    if (len != 0) {
        text.delete(len - linkSpacer.length(), len);
    }

    result.setText(text.toString());
    result.setLinks(localLinks);

    if (result.empty()) {
        return null;
    } else {
        return result;
    }
}

From source file:net.sourceforge.squirrel_sql.fw.dialects.DialectUtils.java

/**
 * Constructs the SQL for adding an index, as follows: CREATE UNIQUE INDEX indexName ON tableName USING
 * btree (column1, column2) TABLESPACE <tableSpace> WHERE constraints;
 * //from w  w  w .  j  ava 2s .com
 * @param indexName
 *           name of the index to be created
 * @param tableName
 *           name of the table
 * @param columns
 *           columns where the index should be stored for
 * @param unique
 *           true if the index should be unique
 * @param accessMethod
 *           the index access method to use (for example, b-tree, r-tree, hash, etc.)
 * @param tablespace
 *           tablespace for the index (leave empty for no tablespace)
 * @param constraints
 *           constraints for the index (leave empty for no constraints)
 * @param qualifier
 *           qualifier of the table
 * @param prefs
 *           preferences for generated sql scripts
 * @return the sql command to create an index.
 */
public static String getAddIndexSQL(HibernateDialect dialect, String indexName, String tableName,
        String accessMethod, String[] columns, boolean unique, String tablespace, String constraints,
        DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) {
    // CREATE UNIQUE INDEX indexName ON tableName USING btree (column1,
    // column2) TABLESPACE
    // WHERE constraints;
    final StringBuilder sql = new StringBuilder();

    sql.append(DialectUtils.CREATE_CLAUSE + " ");
    if (unique) {
        sql.append(DialectUtils.UNIQUE_CLAUSE + " ");
    }
    sql.append(DialectUtils.INDEX_CLAUSE + " ");
    sql.append(shapeIdentifier(indexName, prefs, dialect));
    sql.append(" ON ").append(shapeQualifiableIdentifier(tableName, qualifier, prefs, dialect)).append(" ");
    if (accessMethod != null && !"".equals(accessMethod)) {
        sql.append(" USING ");
        sql.append(accessMethod);
        sql.append(" ");
    }
    sql.append("(");
    for (final String column : columns) {
        sql.append(shapeIdentifier(column, prefs, dialect)).append(", ");
    }
    sql.delete(sql.length() - 2, sql.length()); // deletes the last ", "
    sql.append(")");

    if (tablespace != null && !tablespace.equals("")) {
        sql.append(" \n TABLESPACE ").append(tablespace);
    }

    if (constraints != null && !constraints.equals("")) {
        sql.append(" \n " + DialectUtils.WHERE_CLAUSE + " ").append(constraints);
    }

    return sql.toString();
}

From source file:com.googlecode.vfsjfilechooser2.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override//from ww w .  j a v  a 2 s .  c  o  m
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectoryObject(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}