Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

In this page you can find the example usage for java.util StringTokenizer countTokens.

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * //ww  w .j  a va 2s. c  o m
 * @param valStr
 * @return
 */
private static double[] parseParams(String valStr) {
    StringTokenizer st = new StringTokenizer(valStr, XML_ELEMENT_DELIMITER);
    double[] params = new double[st.countTokens()];
    for (int i = 0; i < params.length; i++)
        params[i] = Double.parseDouble(st.nextToken());
    return params;
}

From source file:henplus.commands.ConnectCommand.java

/**
 * execute the command given./*  w  w w  . j av a2  s . c o  m*/
 */
@Override
public int execute(final SQLSession currentSession, final String cmd, final String param) {
    SQLSession session = null;

    final StringTokenizer st = new StringTokenizer(param);
    final int argc = st.countTokens();

    if ("sessions".equals(cmd)) {
        showSessions();
        return SUCCESS;
    }

    else if ("connect".equals(cmd)) {
        if (argc < 1 || argc > 4) {
            return SYNTAX_ERROR;
        }
        String url = (String) st.nextElement();
        String alias = (argc >= 2) ? st.nextToken() : null;
        String user = (argc >= 3) ? st.nextToken() : null;
        String password = (argc >= 4) ? st.nextToken() : null;
        if (alias == null) {
            /*
             * we only got one parameter. So the that single parameter might
             * have been an alias. let's see..
             */
            if (_knownUrls.containsKey(url)) {
                final String possibleAlias = url;
                url = _knownUrls.get(url);
                if (!possibleAlias.equals(url)) {
                    alias = possibleAlias;
                }
            }
        }
        try {
            session = new SQLSession(url, user, password);
            _knownUrls.put(url, url);
            if (alias != null) {
                _knownUrls.put(alias, url);
            }
            _currentSessionName = createSessionName(session, alias);
            _sessionManager.addSession(_currentSessionName, session);
            _sessionManager.setCurrentSession(session);
        } catch (final Exception e) {
            HenPlus.msg().println(e.toString());
            return EXEC_FAILED;
        }
    } else if ("switch".equals(cmd)) {
        String sessionName = null;
        if (argc != 1 && _sessionManager.getSessionCount() != 2) {
            return SYNTAX_ERROR;
        }
        if (argc == 0 && _sessionManager.getSessionCount() == 2) {
            final Iterator<String> it = _sessionManager.getSessionNames().iterator();
            while (it.hasNext()) {
                sessionName = it.next();
                if (!sessionName.equals(_currentSessionName)) {
                    break;
                }
            }
        } else {
            sessionName = (String) st.nextElement();
        }
        session = _sessionManager.getSessionByName(sessionName);
        if (session == null) {
            HenPlus.msg().println("'" + sessionName + "': no such session");
            return EXEC_FAILED;
        }
        _currentSessionName = sessionName;
    } else if ("rename-session".equals(cmd)) {
        String sessionName = null;
        if (argc != 1) {
            return SYNTAX_ERROR;
        }
        sessionName = (String) st.nextElement();
        if (sessionName.length() < 1) {
            return SYNTAX_ERROR;
        }

        /*
         * // moved to sessionmanager.renameSession
         * 
         * if (_sessionManager.sessionNameExists(sessionName)) {
         * HenPlus.err().println("A session with that name already exists");
         * return EXEC_FAILED; }
         * 
         * session =
         * _sessionManager.removeSessionWithName(currentSessionName); if
         * (session == null) { return EXEC_FAILED; }
         * _sessionManager.addSession(sessionName, session);
         */
        final int renamed = _sessionManager.renameSession(_currentSessionName, sessionName);
        if (renamed == EXEC_FAILED) {
            return EXEC_FAILED;
        }

        _currentSessionName = sessionName;
        session = _sessionManager.getCurrentSession();
    } else if ("disconnect".equals(cmd)) {
        _currentSessionName = null;
        if (argc != 0) {
            return SYNTAX_ERROR;
        }
        _sessionManager.closeCurrentSession();
        HenPlus.msg().println("session closed.");

        if (_sessionManager.hasSessions()) {
            _currentSessionName = _sessionManager.getFirstSessionName();
            session = _sessionManager.getSessionByName(_currentSessionName);
        }
    }

    if (_currentSessionName != null) {
        _henplus.setPrompt(_currentSessionName + "> ");
    } else {
        _henplus.setDefaultPrompt();
    }
    _henplus.setCurrentSession(session);

    return SUCCESS;
}

From source file:hudson.model.DirectoryBrowserSupport.java

/**
 * Builds a list of {@link Path} that represents ancestors
 * from a string like "/foo/bar/zot"./*  w w w . j  a v a2 s.com*/
 */
private List<Path> buildParentPath(String pathList, int restSize) {
    List<Path> r = new ArrayList<Path>();
    StringTokenizer tokens = new StringTokenizer(pathList, "/");
    int total = tokens.countTokens();
    int current = 1;
    while (tokens.hasMoreTokens()) {
        String token = tokens.nextToken();
        r.add(new Path(createBackRef(total - current + restSize), token, true, 0, true));
        current++;
    }
    return r;
}

From source file:edu.ucla.stat.SOCR.chart.SuperXYZChart.java

public void setDataTable(String input) {
    hasExample = true;// ww w. j av a  2 s  .  co m
    StringTokenizer lnTkns = new StringTokenizer(input, ";");
    String line;
    int rowCt = lnTkns.countTokens();
    resetTableRows(rowCt);
    resetTableColumns(3);
    int r = 0;
    while (lnTkns.hasMoreTokens()) {
        line = lnTkns.nextToken();

        //   String tb[] =line.split("\t");
        StringTokenizer cellTkns = new StringTokenizer(line, ",");// IE use "space" Mac use tab as cell separator
        int cellCnt = cellTkns.countTokens();
        String tb[] = new String[cellCnt];
        int r1 = 0;
        while (cellTkns.hasMoreTokens()) {
            dataTable.setValueAt(cellTkns.nextToken(), r, 3 * r1);
            dataTable.setValueAt(cellTkns.nextToken(), r, 3 * r1 + 1);
            dataTable.setValueAt(cellTkns.nextToken(), r, 3 * r1 + 2);
            r++;
        }
    }

    // this will update the mapping panel     
    resetTableColumns(dataTable.getColumnCount());
}

From source file:edu.tsinghua.lumaqq.qq.Util.java

/**
 * ?16//ww  w  .j  av  a 2 s  . c om
 * 
 * @param s
 *          16?
 * @return nullnull
 */
public static byte[] convertHexStringToByte(String s) {
    try {
        s = s.trim();
        StringTokenizer st = new StringTokenizer(s, " ");
        byte[] ret = new byte[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++) {
            String byteString = st.nextToken();

            // 216?null
            if (byteString.length() > 2)
                return null;

            ret[i] = (byte) (Integer.parseInt(byteString, 16) & 0xFF);
        }
        return ret;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.alfresco.web.app.servlet.BaseDownloadContentServlet.java

/**
 * Processes the download request using the current context i.e. no authentication checks are made, it is presumed
 * they have already been done.//  w ww  .  j  a  v  a 2  s.  c  om
 * 
 * @param req
 *           The HTTP request
 * @param res
 *           The HTTP response
 * @param allowLogIn
 *           Indicates whether guest users without access to the content should be redirected to the log in page. If
 *           <code>false</code>, a status 403 forbidden page is displayed instead.
 */
protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res, boolean allowLogIn,
        boolean transmitContent) throws ServletException, IOException {
    Log logger = getLogger();
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled()) {
        String queryString = req.getQueryString();
        logger.debug("Processing URL: " + uri
                + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();

    t.nextToken(); // skip servlet name

    // attachment mode (either 'attach' or 'direct')
    String attachToken = t.nextToken();
    boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken);

    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());

    // get or calculate the noderef and filename to download as
    NodeRef nodeRef;
    String filename;

    // do we have a path parameter instead of a NodeRef?
    String path = req.getParameter(ARG_PATH);
    if (path != null && path.length() != 0) {
        // process the name based path to resolve the NodeRef and the Filename element
        try {
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), path);
            nodeRef = pathInfo.NodeRef;
            filename = pathInfo.Filename;
        } catch (IllegalArgumentException e) {
            Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
                    HttpServletResponse.SC_NOT_FOUND, logger);
            return;
        }
    } else {
        // a NodeRef must have been specified if no path has been found
        if (tokenCount < 6) {
            throw new IllegalArgumentException("Download URL did not contain all required args: " + uri);
        }

        // assume 'workspace' or other NodeRef based protocol for remaining URL elements
        StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken()));
        String id = URLDecoder.decode(t.nextToken());

        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);

        if (tokenCount > 6) {
            // found additional relative path elements i.e. noderefid/images/file.txt
            // this allows a url to reference siblings nodes via a cm:name based relative path
            // solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc.
            List<String> paths = new ArrayList<String>(tokenCount - 5);
            while (t.hasMoreTokens()) {
                paths.add(URLDecoder.decode(t.nextToken()));
            }
            filename = paths.get(paths.size() - 1);

            try {
                NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef();
                FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths);
                nodeRef = fileInfo.getNodeRef();
            } catch (FileNotFoundException e) {
                Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
                        HttpServletResponse.SC_NOT_FOUND, logger);
                return;
            }
        } else {
            // filename is last remaining token
            filename = t.nextToken();
        }
    }

    // get qualified of the property to get content from - default to ContentModel.PROP_CONTENT
    QName propertyQName = ContentModel.PROP_CONTENT;
    String property = req.getParameter(ARG_PROPERTY);
    if (property != null && property.length() != 0) {
        propertyQName = QName.createQName(property);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Found NodeRef: " + nodeRef);
        logger.debug("Will use filename: " + filename);
        logger.debug("For property: " + propertyQName);
        logger.debug("With attachment mode: " + attachment);
    }

    // get the services we need to retrieve the content
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();

    // Check that the node still exists
    if (!nodeService.exists(nodeRef)) {
        Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND,
                HttpServletResponse.SC_NOT_FOUND, logger);
        return;
    }

    try {
        // check that the user has at least READ_CONTENT access - else redirect to an error or login page
        if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn)) {
            return;
        }

        // check If-Modified-Since header and set Last-Modified header as appropriate
        Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
        if (modified != null) {
            long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE);
            if (modifiedSince > 0L) {
                // round the date to the ignore millisecond value which is not supplied by header
                long modDate = (modified.getTime() / 1000L) * 1000L;
                if (modDate <= modifiedSince) {
                    if (logger.isDebugEnabled())
                        logger.debug("Returning 304 Not Modified.");
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }
            res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime());
            res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate, max-age=0");
            res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\"");
        }

        if (attachment == true) {
            setHeaderContentDisposition(req, res, filename);
        }

        // get the content reader
        ContentReader reader = contentService.getReader(nodeRef, propertyQName);
        // ensure that it is safe to use
        reader = FileContentReader.getSafeContentReader(reader,
                Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING), nodeRef, reader);

        String mimetype = reader.getMimetype();
        // fall back if unable to resolve mimetype property
        if (mimetype == null || mimetype.length() == 0) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            mimetype = MIMETYPE_OCTET_STREAM;
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeMap.getMimetype(ext);
            }
        }

        // explicitly set the content disposition header if the content is powerpoint
        if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE)
                || mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE))) {
            setHeaderContentDisposition(req, res, filename);
        }

        // get the content and stream directly to the response output stream
        // assuming the repo is capable of streaming in chunks, this should allow large files
        // to be streamed directly to the browser response stream.
        res.setHeader(HEADER_ACCEPT_RANGES, "bytes");

        // for a GET request, transmit the content else just the headers are sent
        if (transmitContent) {
            try {
                boolean processedRange = false;
                String range = req.getHeader(HEADER_CONTENT_RANGE);
                if (range == null) {
                    range = req.getHeader(HEADER_RANGE);
                }
                if (range != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Found content range header: " + range);

                    // ensure the range header is starts with "bytes=" and process the range(s)
                    if (range.length() > 6) {
                        HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService);
                        processedRange = rangeProcessor.processRange(res, reader, range.substring(6), nodeRef,
                                propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT));
                    }
                }
                if (processedRange == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Sending complete file content...");

                    // set mimetype for the content and the character encoding for the stream
                    res.setContentType(mimetype);
                    res.setCharacterEncoding(reader.getEncoding());

                    // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files
                    if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html")
                            || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) {
                        String content = reader.getContentString();

                        if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) {
                            // process with HTML stripper
                            content = StringUtils.stripUnsafeHTMLTags(content, false);
                        } else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) {
                            // IE supports "behaviour" which means that css can load a .htc file that could
                            // contain XSS code in the form of jscript, vbscript etc, to stop it form being
                            // evaluated we set the contient type to text/plain
                            res.setContentType("text/plain");
                        }

                        String encoding = reader.getEncoding();
                        byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes();
                        res.setContentLength(bytes.length);
                        res.getOutputStream().write(bytes);

                        return;
                    }

                    // return the complete entity range
                    long size = reader.getSize();
                    res.setHeader(HEADER_CONTENT_RANGE,
                            "bytes 0-" + Long.toString(size - 1L) + "/" + Long.toString(size));
                    res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size));
                    reader.getContent(res.getOutputStream());
                }
            } catch (SocketException e1) {
                // the client cut the connection - our mission was accomplished apart from a little error message
                if (logger.isDebugEnabled())
                    logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
            } catch (ContentIOException e2) {
                if (logger.isInfoEnabled())
                    logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage());
            } catch (Throwable err) {
                if (err.getCause() instanceof SocketException) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    if (logger.isDebugEnabled())
                        logger.debug(
                                "Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
                } else
                    throw err;
            }
        } else {
            if (logger.isDebugEnabled())
                logger.debug("HEAD request processed - no content sent.");
            res.getOutputStream().close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException(
                "Error during download content servlet processing: " + err.getMessage(), err);
    }
}

From source file:bboss.org.apache.velocity.anakia.AnakiaTask.java

/**
 * Hacky method to figure out the relative path
 * that we are currently in. This is good for getting
 * the relative path for images and anchor's.
 *//*from ww w  .j a va2  s.  co m*/
private String getRelativePath(String file) {
    if (file == null || file.length() == 0)
        return "";
    StringTokenizer st = new StringTokenizer(file, "/\\");
    // needs to be -1 cause ST returns 1 even if there are no matches. huh?
    int slashCount = st.countTokens() - 1;
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < slashCount; i++) {
        sb.append("../");
    }

    if (sb.toString().length() > 0) {
        return StringUtils.chop(sb.toString(), 1);
    }

    return ".";
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * // w w w.  jav  a  2 s. c om
 * @param vars
 * @return
 */
private static InternalTestVariable[] parseTestVariables(String vars) {
    StringTokenizer st = new StringTokenizer(vars, XML_ELEMENT_DELIMITER);
    InternalTestVariable[] v = new InternalTestVariable[st.countTokens()];
    for (int i = 0; i < v.length; i++)
        v[i] = InternalTestVariable.valueOf(st.nextToken());
    return v;
}

From source file:com.sun.identity.saml2.plugins.SAML2IDPProxyFRImpl.java

public List getSupportedAuthnContextsByIDP(String realm, String hostEntityId) {
    List authnContextList = null;
    List supportedClassRef = null;

    supportedClassRef = getAttributeListValueFromIDPSSOConfig(realm, hostEntityId,
            SAML2Constants.IDP_AUTHNCONTEXT_CLASSREF_MAPPING);

    if (supportedClassRef != null && !supportedClassRef.isEmpty()) {
        Iterator it = supportedClassRef.iterator();
        while (it.hasNext()) {
            StringTokenizer tokenizer = new StringTokenizer((String) it.next(), "|");
            if (tokenizer.countTokens() > 1) {
                authnContextList.add(tokenizer.nextToken());
            }//w w  w .  j a  v a2 s.  co  m
        }
    }
    return authnContextList;
}

From source file:org.apache.cocoon.components.language.programming.java.EclipseJavaCompiler.java

public boolean compile() throws IOException {
    final String targetClassName = makeClassName(sourceFile);
    final ClassLoader classLoader = ClassUtils.getClassLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    class CompilationUnit implements ICompilationUnit {

        String className;//w  ww  .j a  v a2 s. c om
        String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        public char[] getFileName() {
            return className.toCharArray();
        }

        public char[] getContents() {
            char[] result = null;
            FileReader fr = null;
            try {
                fr = new FileReader(sourceFile);
                Reader reader = new BufferedReader(fr);
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuffer buf = new StringBuffer();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                handleError(className, -1, -1, e.getMessage());
            }
            return result;
        }

        public char[] getMainTypeName() {
            int dot = className.lastIndexOf('.');
            if (dot > 0) {
                return className.substring(dot + 1).toCharArray();
            }
            return className.toCharArray();
        }

        public char[][] getPackageName() {
            StringTokenizer izer = new StringTokenizer(className, ".");
            char[][] result = new char[izer.countTokens() - 1][];
            for (int i = 0; i < result.length; i++) {
                String tok = izer.nextToken();
                result[i] = tok.toCharArray();
            }
            return result;
        }
    }

    final INameEnvironment env = new INameEnvironment() {

        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i > 0) {
                    result.append(".");
                }
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                if (i > 0) {
                    result.append(".");
                }
                result.append(packageName[i]);
            }
            result.append(".");
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {

            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit);
                }
                String resourceName = className.replace('.', '/') + ".class";
                InputStream is = classLoader.getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader);
                }
            } catch (IOException exc) {
                handleError(className, -1, -1, exc.getMessage());
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                handleError(className, -1, -1, exc.getMessage());
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = classLoader.getResourceAsStream(resourceName);
            return is == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            StringBuffer result = new StringBuffer();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i > 0) {
                        result.append(".");
                    }
                    result.append(parentPackageName[i]);
                }
            }
            String str = new String(packageName);
            if (Character.isUpperCase(str.charAt(0)) && !isPackage(result.toString())) {
                return false;
            }
            result.append(".");
            result.append(str);
            return isPackage(result.toString());
        }

        public void cleanup() {
            // EMPTY
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map settings = new HashMap(9);
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
    if (sourceEncoding != null) {
        settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding);
    }
    if (debug) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }
    // Set the sourceCodeVersion
    switch (this.compilerComplianceLevel) {
    case 150:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
    }
    // Set the target platform
    switch (SystemUtils.JAVA_VERSION_INT) {
    case 150:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasErrors()) {
                    IProblem[] errors = result.getErrors();
                    for (int i = 0; i < errors.length; i++) {
                        IProblem error = errors[i];
                        String name = new String(errors[i].getOriginatingFileName());
                        handleError(name, error.getSourceLineNumber(), -1, error.getMessage());
                    }
                } else {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuffer className = new StringBuffer();
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                className.append(".");
                            }
                            className.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = destDir + "/" + className.toString().replace('.', '/') + ".class";
                        FileOutputStream fout = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fout);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    };
    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory);
    compiler.compile(compilationUnits);
    return errors.size() == 0;
}