Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

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

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:org.openymsg.network.HTTPConnectionHandler.java

/**
 * Creates a new instance, using tshe host and port as configured. This constructor may contain a collection of
 * hosts of hosts to not proxy.//from  w ww  . j av a2 s . c o  m
 * 
 * @param proxyHost
 *            Host to use.
 * @param proxyPort
 *            Port to use.
 * @param blacklist
 *            Option set of hosts explicitly forbidden to use.
 */
public HTTPConnectionHandler(String proxyHost, int proxyPort, Collection<String> blacklist) {
    if (proxyHost == null || proxyHost.length() == 0 || proxyPort <= 0 || proxyPort > 65535) {
        throw new IllegalArgumentException("Bad HTTP proxy properties");
    }
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;

    packets = new LinkedList<YMSG9Packet>();
    connected = false;

    // Names are prefixed with "http." for 1.3 and after
    Properties p = System.getProperties();
    p.put(NetworkConstants.PROXY_HOST_OLD, this.proxyHost);
    p.put(NetworkConstants.PROXY_HOST, this.proxyHost);
    p.put(NetworkConstants.PROXY_PORT_OLD, this.proxyPort + "");
    p.put(NetworkConstants.PROXY_PORT, this.proxyPort + "");
    p.put(NetworkConstants.PROXY_SET, "true");

    // Expand list to item|item|... , then store
    if (blacklist != null) {
        StringBuffer sb = new StringBuffer();
        for (String host : blacklist) {
            sb.append(host).append('|');
        }
        sb.setLength(sb.length() - 1);

        System.getProperties().put(NetworkConstants.PROXY_NON, sb.toString());
    }
}

From source file:com.hihframework.core.utils.StringHelpers.java

/**
 * ????SQL?//from  w ww.j a v  a 2  s . c  o  m
 * @param ts
 * @param parttern
 * @param wrapChar
 * @return
 * @author Xiaojf
 * @since 2011-9-14
 */
public static String join(Object[] ts, String parttern, String wrapChar) {
    StringBuffer s = new StringBuffer();
    if (ts == null)
        return s.toString();
    if (isNull(parttern))
        parttern = "";
    if (isNull(wrapChar))
        wrapChar = "";
    for (Object obj : ts) {
        if (isNull(obj))
            continue;
        s.append(wrapChar + obj + wrapChar + parttern);
    }
    if (s.length() > 0)
        s.setLength(s.length() - 1);
    return s.toString();
}

From source file:com.microsoft.tfs.core.httpclient.Wire.java

private void wire(final String header, final InputStream instream) throws IOException {
    final StringBuffer buffer = new StringBuffer();
    int ch;//w w w  .  j  a  v  a2s  . c o  m
    while ((ch = instream.read()) != -1) {
        if (ch == 13) {
            buffer.append("[\\r]");
        } else if (ch == 10) {
            buffer.append("[\\n]\"");
            buffer.insert(0, "\"");
            buffer.insert(0, header);
            log.debug(buffer.toString());
            buffer.setLength(0);
        } else if ((ch < 32) || (ch > 127)) {
            buffer.append("[0x");
            buffer.append(Integer.toHexString(ch));
            buffer.append("]");
        } else {
            buffer.append((char) ch);
        }
    }
    if (buffer.length() > 0) {
        buffer.append("\"");
        buffer.insert(0, "\"");
        buffer.insert(0, header);
        log.debug(buffer.toString());
    }
}

From source file:org.alfresco.repo.template.XSLTProcessor.java

@Override
public void process(String template, Object model, Writer out, Locale locale) {
    if (template.indexOf(StoreRef.URI_FILLER) != -1) {
        // If template is a node ref, ignore locale
        process(template, model, out);/* w  w w  .j  av  a  2 s . c  om*/
    } else {
        //Otherwise try and locate a locale specific resource.
        TemplateSource templateSource = null;
        int lastDot = template.lastIndexOf('.');
        String prefix = lastDot == -1 ? template : template.substring(0, lastDot);
        String suffix = lastDot == -1 ? "" : template.substring(lastDot);
        String localeName = LOCALE_SEPARATOR + locale.toString();
        StringBuffer buf = new StringBuffer(template.length() + localeName.length());
        buf.append(prefix);
        for (;;) {
            buf.setLength(prefix.length());
            String path = buf.append(localeName).append(suffix).toString();
            try {
                templateSource = (TemplateSource) templateLoader.findTemplateSource(path);
            } catch (IOException ex) {
                throw new TemplateException(MSG_UNABLE_TO_READ_TEMPLATE, new Object[] { ex.getMessage() }, ex);
            }
            if (templateSource != null) {
                break;
            }
            int lastUnderscore = localeName.lastIndexOf('_');
            if (lastUnderscore == -1) {
                break;
            }
            localeName = localeName.substring(0, lastUnderscore);
        }
        if (templateSource == null) {
            throw new TemplateException(MSG_ERROR_NO_TEMPLATE, new Object[] { template });
        }
        process(templateSource, model, out);
    }
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriter.java

/**
 * Writes the contents of the StringWriter to our output file
 * /*from ww  w  .  j av  a2 s.  co m*/
 * @param writer The StringWriter to read the data from
 */
private void write(Sink sink) throws IOException {

    StringWriter writer = (StringWriter) sink.getWriter();

    writer.flush();

    StringBuffer buffer = writer.getBuffer();

    // Sadly StringBuffer doesn't allow us read-only access to its internal array, so we have to copy
    String element = buffer.toString();

    Writer outputWriter = writerSource.getWriter();
    synchronized (outputWriter) {
        outputWriter.write(element);
    }

    // Reset the buffer for next time
    buffer.setLength(0);

}

From source file:org.apache.nutchbase.parse.html.HtmlParserHbase.java

public ParseHbase getParse(String url, RowPart row) {
    HTMLMetaTags metaTags = new HTMLMetaTags();

    String baseUrl = row.getBaseUrl();
    URL base;/*from   ww  w .  j a  va 2s.com*/
    try {
        base = new URL(baseUrl);
    } catch (MalformedURLException e) {
        return new ParseStatus(e).getEmptyParseHbase(getConf());
    }

    String text = "";
    String title = "";
    Outlink[] outlinks = new Outlink[0];
    Metadata metadata = new Metadata();

    // parse the content
    DocumentFragment root;
    try {
        byte[] contentInOctets = row.getContent();
        InputSource input = new InputSource(new ByteArrayInputStream(contentInOctets));

        EncodingDetector detector = new EncodingDetector(conf);
        detector.autoDetectClues(row, true);
        detector.addClue(sniffCharacterEncoding(contentInOctets), "sniffed");
        String encoding = detector.guessEncoding(row, defaultCharEncoding);

        metadata.set(Metadata.ORIGINAL_CHAR_ENCODING, encoding);
        metadata.set(Metadata.CHAR_ENCODING_FOR_CONVERSION, encoding);

        input.setEncoding(encoding);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Parsing...");
        }
        root = parse(input);
    } catch (IOException e) {
        return new ParseStatus(e).getEmptyParseHbase(getConf());
    } catch (DOMException e) {
        return new ParseStatus(e).getEmptyParseHbase(getConf());
    } catch (SAXException e) {
        return new ParseStatus(e).getEmptyParseHbase(getConf());
    } catch (Exception e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
        return new ParseStatus(e).getEmptyParseHbase(getConf());
    }

    // get meta directives
    HTMLMetaProcessor.getMetaTags(metaTags, root, base);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
    }
    // check meta directives
    if (!metaTags.getNoIndex()) { // okay to index
        StringBuffer sb = new StringBuffer();
        if (LOG.isTraceEnabled()) {
            LOG.trace("Getting text...");
        }
        utils.getText(sb, root); // extract text
        text = sb.toString();
        sb.setLength(0);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Getting title...");
        }
        utils.getTitle(sb, root); // extract title
        title = sb.toString().trim();
    }

    if (!metaTags.getNoFollow() || ignoreNoFollow) { // okay to follow links
        ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
        URL baseTag = utils.getBase(root);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Getting links...");
        }
        utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
        outlinks = l.toArray(new Outlink[l.size()]);
        if (LOG.isTraceEnabled()) {
            LOG.trace("found " + outlinks.length + " outlinks in " + url);
        }
    }

    ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
    if (metaTags.getRefresh()) {
        status.setMinorCode(ParseStatus.SUCCESS_REDIRECT);
        status.setArgs(new String[] { metaTags.getRefreshHref().toString(),
                Integer.toString(metaTags.getRefreshTime()) });
    }

    ParseHbase parse = new ParseHbase(text, title, outlinks, status);
    parse = htmlParseFilters.filter(url, row, parse, metaTags, root);

    if (metaTags.getNoCache()) { // not okay to cache
        row.putMeta(Nutch.CACHING_FORBIDDEN_KEY, Bytes.toBytes(cachingPolicy));
    }

    return parse;
}

From source file:ORG.oclc.os.SRW.Utilities.java

public static String byteArrayToString(byte array[], int offset, int length) {
    StringBuffer str = new StringBuffer();
    StringBuffer alpha = new StringBuffer();
    int stopat = length + offset;
    char c;/*  w w w  . j a v a2  s.c o m*/
    int i, type;

    for (i = 1; offset < stopat; offset++, i++) {
        if ((array[offset] & 0xff) < 16)
            str.append(" 0");
        else
            str.append(" ");
        str.append(Integer.toString(array[offset] & 0xff, 16));

        c = (char) array[offset];
        type = Character.getType(c);

        //      if (Character.isLetterOrDigit(c) || (c > )
        if (c < ' ' || c >= 0x7f)
            alpha.append('.');
        else
            alpha.append(c);

        if ((i % 16) == 0) {
            str.append("  " + alpha + newLine);
            alpha.setLength(0);
        }
    }
    while (i++ % 16 != 1)
        str.append("   ");
    offset = 0;

    str.append("  " + alpha + newLine);
    str.append(newLine);

    return str.toString();
}

From source file:org.geoserver.security.web.group.ConfirmRemovalGroupPanel.java

@Override
protected String getConfirmationMessage(GeoServerUserGroup object) throws Exception {
    StringBuffer buffer = new StringBuffer(BeanUtils.getProperty(object, "groupname"));
    if ((Boolean) getDefaultModelObject()) {
        SortedSet<GeoServerRole> roles = GeoServerApplication.get().getSecurityManager().getActiveRoleService()
                .getRolesForGroup(object.getGroupname());
        buffer.append(" [");
        for (GeoServerRole role : roles) {
            buffer.append(role.getAuthority()).append(" ");
        }//from  w ww.j  a va 2s  . c om
        if (roles.size() > 0) { // remove last delimiter
            buffer.setLength(buffer.length() - 1);
        }
        buffer.append("]");
    }
    return buffer.toString();
}

From source file:com.gtwm.pb.servlets.AppController.java

public static void carryOutAppActions(HttpServletRequest request, SessionDataInfo sessionData,
        DatabaseInfo databaseDefn, List<FileItem> multipartItems, StringBuffer appActionName)
        throws AgileBaseException, SQLException, FileUploadException, IOException, MessagingException {
    // perform any actions
    EnumSet<AppAction> appActions = EnumSet.allOf(AppAction.class);
    for (AppAction appAction : appActions) {
        // Store so exception handling has access to the action carried out
        appActionName.setLength(0);
        appActionName.append(appAction.toString());
        String appActionValue = ServletUtilMethods.getParameter(request,
                appAction.toString().toLowerCase(Locale.UK), multipartItems);
        if (appActionValue != null) {
            sessionData.setLastAppAction(appAction);
            switch (appAction) {
            // Most commonly used actions at the start
            case UPDATE_RECORD:
                ServletDataMethods.saveRecord(sessionData, request, false, databaseDefn, multipartItems);
                break;
            case SAVE_NEW_RECORD:
                ServletDataMethods.saveRecord(sessionData, request, true, databaseDefn, multipartItems);
                break;
            case CLONE_RECORD:
                ServletDataMethods.cloneRecord(sessionData, request, databaseDefn, multipartItems);
                break;
            case REMOVE_RECORD:
                ServletDataMethods.removeRecord(sessionData, request, databaseDefn);
                break;
            case GLOBAL_EDIT:
                ServletDataMethods.globalEdit(sessionData, request, databaseDefn, multipartItems);
                break;
            case CONTRACT_SECTION:
                ServletSchemaMethods.contractSection(sessionData, request, databaseDefn);
                break;
            case EXPAND_SECTION:
                ServletSchemaMethods.expandSection(sessionData, request, databaseDefn);
                break;
            case ADD_COMMENT:
                ServletDataMethods.addComment(sessionData, request, databaseDefn);
                break;
            case ADD_USER:
                ServletAuthMethods.addUser(sessionData, request, databaseDefn.getAuthManager());
                break;
            case REMOVE_USER:
                ServletAuthMethods.removeUser(sessionData, request, databaseDefn);
                break;
            case UPDATE_USER:
                ServletAuthMethods.updateUser(sessionData, request, databaseDefn.getAuthManager());
                break;
            case SEND_PASSWORD_RESET:
                ServletAuthMethods.sendPasswordReset(request, databaseDefn.getAuthManager());
                break;
            case ADD_ROLE:
                ServletAuthMethods.addRole(sessionData, request, databaseDefn.getAuthManager());
                break;
            case UPDATE_ROLE:
                ServletAuthMethods.updateRole(sessionData, request, databaseDefn.getAuthManager());
                break;
            case REMOVE_ROLE:
                ServletAuthMethods.removeRole(sessionData, request, databaseDefn);
                break;
            case ASSIGN_USER_TO_ROLE:
                ServletAuthMethods.assignUserToRole(request, databaseDefn.getAuthManager());
                break;
            case REMOVE_USER_FROM_ROLE:
                ServletAuthMethods.removeUserFromRole(request, databaseDefn);
                break;
            case ADD_PRIVILEGE:
                ServletAuthMethods.addPrivilege(request, databaseDefn);
                break;
            case REMOVE_PRIVILEGE:
                ServletAuthMethods.removePrivilege(request, databaseDefn);
                break;
            case SET_MAX_TABLE_PRIVILEGE:
                ServletAuthMethods.setMaxTablePrivilege(sessionData, request, databaseDefn);
                break;
            case CLEAR_ALL_TABLE_PRIVILEGES:
                ServletAuthMethods.clearAllTablePrivileges(request, databaseDefn);
                break;
            case ADD_TABLE:
                ServletSchemaMethods.addTable(sessionData, request, databaseDefn);
                break;
            case UPDATE_TABLE:
                ServletSchemaMethods.updateTable(sessionData, request, databaseDefn);
                break;
            case REMOVE_TABLE:
                ServletSchemaMethods.removeTable(sessionData, request, databaseDefn);
                break;
            case ADD_FIELD:
                ServletSchemaMethods.addField(sessionData, request, databaseDefn);
                break;
            case REMOVE_FIELD:
                ServletSchemaMethods.removeField(sessionData, request, databaseDefn);
                break;
            case UPDATE_FIELD:
                ServletSchemaMethods.updateField(sessionData, request, databaseDefn);
                break;
            case UPDATE_FIELD_OPTION:
                ServletSchemaMethods.updateFieldOption(sessionData, request, databaseDefn);
                break;
            case SET_FIELD_INDEX:
                ServletSchemaMethods.setFieldIndex(sessionData, request, databaseDefn);
                break;
            case ADD_REPORT:
                ServletSchemaMethods.addReport(sessionData, request, databaseDefn);
                break;
            case UPDATE_REPORT:
                ServletSchemaMethods.updateReport(sessionData, request, databaseDefn);
                break;
            case UPLOAD_CUSTOM_TEMPLATE:
                ServletSchemaMethods.uploadCustomReportTemplate(sessionData, request, databaseDefn,
                        multipartItems);
                break;
            case REMOVE_CUSTOM_TEMPLATE:
                ServletSchemaMethods.removeCustomReportTemplate(sessionData, request, databaseDefn);
                break;
            case REMOVE_REPORT:
                ServletSchemaMethods.removeReport(sessionData, request, databaseDefn);
                break;
            case ADD_FIELD_TO_REPORT:
                ServletSchemaMethods.addFieldToReport(sessionData, request, databaseDefn);
                break;
            case REMOVE_FIELD_FROM_REPORT:
                ServletSchemaMethods.removeFieldFromReport(sessionData, request, databaseDefn);
                break;
            case SET_REPORT_FIELD_INDEX:
                ServletSchemaMethods.setReportFieldIndex(sessionData, request, databaseDefn);
                break;
            case SET_REPORT_FIELD_SORTING:
                ServletSchemaMethods.setReportFieldSorting(sessionData, request, databaseDefn);
                break;
            case ADD_CALCULATION_TO_REPORT:
                ServletSchemaMethods.addCalculationToReport(sessionData, request, databaseDefn);
                break;
            case UPDATE_CALCULATION_IN_REPORT:
                ServletSchemaMethods.updateCalculationInReport(sessionData, request, databaseDefn);
                break;
            case ADD_FILTER_TO_REPORT:
                ServletSchemaMethods.addFilterToReport(sessionData, request, databaseDefn);
                break;
            case REMOVE_FILTER_FROM_REPORT:
                ServletSchemaMethods.removeFilterFromReport(sessionData, request, databaseDefn);
                break;
            case ADD_JOIN_TO_REPORT:
                ServletSchemaMethods.addJoinToReport(sessionData, request, databaseDefn);
                break;
            case REMOVE_JOIN_FROM_REPORT:
                ServletSchemaMethods.removeJoinFromReport(sessionData, request, databaseDefn);
                break;
            case ADD_GROUPING_TO_CHART:
                ServletSchemaMethods.addGroupingToChart(sessionData, request, databaseDefn);
                break;
            case REMOVE_GROUPING_FROM_CHART:
                ServletSchemaMethods.removeGroupingFromChart(sessionData, request, databaseDefn);
                break;
            case ADD_FUNCTION_TO_CHART:
                ServletSchemaMethods.addFunctionToChart(sessionData, request, databaseDefn);
                break;
            case REMOVE_FUNCTION_FROM_CHART:
                ServletSchemaMethods.removeFunctionFromChart(sessionData, request, databaseDefn);
                break;
            case SET_CHART_FILTER:
                ServletSchemaMethods.setChartFilter(sessionData, request, databaseDefn);
                break;
            case SET_CHART_FILTER_FIELD:
                ServletSchemaMethods.setChartFilterField(sessionData, request, databaseDefn);
                break;
            case SET_CHART_RANGE:
                ServletSchemaMethods.setChartRange(sessionData, request, databaseDefn);
                break;
            case SAVE_CHART:
                ServletSchemaMethods.saveChart(sessionData, request, databaseDefn);
                break;
            case REMOVE_CHART:
                ServletSchemaMethods.removeChart(sessionData, request, databaseDefn);
                break;
            case SET_WORD_CLOUD_FIELD:
                ServletSchemaMethods.setReportWordCloudField(sessionData, request, databaseDefn);
                break;
            case UPDATE_MAP:
                ServletSchemaMethods.updateMap(sessionData, request, databaseDefn);
                break;
            case SET_DASHBOARD_CHART_STATE:
                ServletDashboardMethods.setDashboardSummaryState(sessionData, request, databaseDefn);
                break;
            case CSV_IMPORT:
                ServletDataMethods.importRecords(sessionData, request, databaseDefn, multipartItems);
                break;
            case LOCK_RECORDS:
                ServletDataMethods.lockRecords(sessionData, request, databaseDefn);
                break;
            case ADD_COMPANY:
                ServletSchemaMethods.addCompany(request, databaseDefn);
                break;
            case REMOVE_COMPANY:
                ServletSchemaMethods.removeCompany(request, databaseDefn.getAuthManager());
                break;
            case ANONYMISE:
                ServletDataMethods.anonymiseTableData(sessionData, request, databaseDefn, multipartItems);
                break;
            case ADD_MODULE:
                ServletSchemaMethods.addModule(request, sessionData, databaseDefn);
                break;
            case REMOVE_MODULE:
                ServletSchemaMethods.removeModule(request, sessionData, databaseDefn);
                break;
            case UPDATE_MODULE:
                ServletSchemaMethods.updateModule(request, sessionData, databaseDefn.getAuthManager());
                break;
            case HIDE_REPORT:
                ServletSchemaMethods.hideReportFromUser(sessionData, request, databaseDefn);
                break;
            case UNHIDE_REPORT:
                ServletSchemaMethods.unhideReportFromUser(sessionData, request, databaseDefn);
                break;
            case ADD_OPERATIONAL_DASHBOARD_REPORT:
                ServletSchemaMethods.addOperationalDashboardReport(sessionData, request, databaseDefn);
                break;
            case REMOVE_OPERATIONAL_DASHBOARD_REPORT:
                ServletSchemaMethods.removeOperationalDashboardReport(sessionData, request, databaseDefn);
                break;
            case ADD_FORM_TABLE:
                ServletSchemaMethods.addFormTable(sessionData, request, databaseDefn);
                break;
            case REMOVE_FORM_TABLE:
                ServletSchemaMethods.removeFormTable(sessionData, request, databaseDefn);
                break;
            case ADD_FORM_TAB:
                ServletSchemaMethods.addFormTab(request, sessionData, databaseDefn);
                break;
            case REMOVE_FORM_TAB:
                ServletSchemaMethods.removeFormTab(request, sessionData, databaseDefn);
                break;
            case UPDATE_FORM_TAB:
                ServletSchemaMethods.updateFormTab(sessionData, request, databaseDefn);
                break;
            case SET_TABLE_FORM:
                ServletSchemaMethods.setTableForm(request, sessionData, databaseDefn);
                break;
            case SET_USER_DEFAULT_REPORT:
                ServletSchemaMethods.setUserDefaultReport(sessionData, request, databaseDefn);
                break;
            case SET_CALENDAR_SYNCABLE:
                boolean calendarSyncable = Helpers.valueRepresentsBooleanTrue(appActionValue);
                ServletSchemaMethods.setCalendarSyncable(sessionData, request, databaseDefn, calendarSyncable);
                break;
            case ENABLE_DISABLE_APP:
                ServletSchemaMethods.enableDisableApp(request, databaseDefn);
                break;
            case ADD_REPORT_DISTINCT:
                ServletSchemaMethods.addDistinctToReport(sessionData, request, databaseDefn);
                break;
            case REMOVE_REPORT_DISTINCT:
                ServletSchemaMethods.removeDistinctFromReport(sessionData, request, databaseDefn);
                break;
            }//from   w w w.j a  v  a  2  s.co  m
        }
    }
}

From source file:org.apache.bsf.engines.java.JavaEngine.java

/**
 * This is used by an application to evaluate a string containing
 * some expression. It should store the "bsf" handle where the
 * script can get to it, for callback purposes.
 * <p>//from   w  w  w. j  a v a2 s  .  c  o  m
 * Note that Java compilation imposes serious overhead,
 * but in exchange you get full Java performance
 * once the classes have been created (minus the cache lookup cost).
 * <p>
 * Nobody knows whether javac is threadsafe.
 * I'm going to serialize access to protect it.
 * <p>
 * There is no published API for invoking javac as a class. There's a trick
 * that seems to work for Java 1.1.x, but it stopped working in Java 1.2.
 * We will attempt to use it, then if necessary fall back on invoking
 * javac via the command line.
 */
public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException {
    Object retval = null;
    String classname = null;
    GeneratedFile gf = null;

    String basescript = oscript.toString();
    String script = basescript; // May be altered by $$CLASSNAME$$ expansion

    try {
        // Do we already have a class exactly matching this code?
        javaclass = (Class) codeToClass.get(basescript);

        if (javaclass != null) {
            classname = javaclass.getName();
        } else {
            gf = openUniqueFile(tempDir, "BSFJava", ".java");
            if (gf == null) {
                throw new BSFException("couldn't create JavaEngine scratchfile");
            }
            // Obtain classname
            classname = gf.className;

            // Write the kluge header to the file.
            gf.fos.write(("import java.lang.*;" + "import java.util.*;" + "public class " + classname + " {\n"
                    + "  static public Object BSFJavaEngineEntry(org.apache.bsf.BSFManager bsf) {\n")
                            .getBytes());

            // Edit the script to replace placeholder with the generated
            // classname. Note that this occurs _after_ the cache was checked!
            int startpoint = script.indexOf(placeholder);
            int endpoint;
            if (startpoint >= 0) {
                StringBuffer changed = new StringBuffer();
                for (; startpoint >= 0; startpoint = script.indexOf(placeholder, startpoint)) {
                    changed.setLength(0); // Reset for 2nd pass or later
                    if (startpoint > 0) {
                        changed.append(script.substring(0, startpoint));
                    }
                    changed.append(classname);
                    endpoint = startpoint + placeholder.length();
                    if (endpoint < script.length()) {
                        changed.append(script.substring(endpoint));
                    }
                    script = changed.toString();
                }
            }

            // MJD - debug
            //              BSFDeclaredBean tempBean;
            //              String          className;
            //              
            //              for (int i = 0; i < declaredBeans.size (); i++) {
            //              tempBean  = (BSFDeclaredBean) declaredBeans.elementAt (i);
            //              className = StringUtils.getClassName (tempBean.bean.getClass ());
            //              
            //              gf.fos.write ((className + " " +
            //              tempBean.name + " = (" + className +
            //              ")bsf.lookupBean(\"" +
            //              tempBean.name + "\");").getBytes ());
            //              }
            // MJD - debug

            // Copy the input to the file.
            // Assumes all available -- probably mistake, but same as other engines.
            gf.fos.write(script.getBytes());
            // Close the method and class
            gf.fos.write(("\n  }\n}\n").getBytes());
            gf.fos.close();

            // Compile through Java to .class file
            // May not be threadsafe. Serialize access on static object:
            synchronized (serializeCompilation) {
                JavaUtils.JDKcompile(gf.file.getPath(), classPath);
            }

            // Load class.
            javaclass = EngineUtils.loadClass(mgr, classname);

            // Stash class for reuse
            codeToClass.put(basescript, javaclass);
        }

        Object[] callArgs = { mgr };
        retval = internalCall(this, "BSFJavaEngineEntry", callArgs);
    }

    catch (Exception e) {
        e.printStackTrace();
        throw new BSFException(BSFException.REASON_IO_ERROR, e.getMessage());
    } finally {
        // Cleanup: delete the .java and .class files

        //          if(gf!=null && gf.file!=null && gf.file.exists())
        //          gf.file.delete();  // .java file

        if (classname != null) {
            // Generated class
            File file = new File(tempDir + File.separatorChar + classname + ".class");
            //              if(file.exists())
            //              file.delete();

            // Search for and clean up minor classes, classname$xxx.class
            file = new File(tempDir); // ***** Is this required?
            minorPrefix = classname + "$"; // Indirect arg to filter
            String[] minorClassfiles = file.list(new FilenameFilter() {
                // Starts with classname$ and ends with .class
                public boolean accept(File dir, String name) {
                    return (0 == name.indexOf(minorPrefix))
                            && (name.lastIndexOf(".class") == name.length() - 6);
                }
            });
            for (int i = 0; i < minorClassfiles.length; ++i) {
                file = new File(minorClassfiles[i]);
                //                  file.delete();
            }
        }
    }
    return retval;
}