Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.chinamobile.bcbsp.bspcontroller.JobInProgress.java

/**
 * get aggregate result from superstepcontainer
 * @param ssrcs// ww w .ja  v a2 s. com
 *        contains the aggregate values after a super step
 * @return aggregate values from all superstepreportcontainers
 */
@SuppressWarnings("unchecked")
public String[] generalAggregate(SuperStepReportContainer[] ssrcs) {
    String[] results = null;
    if (Constants.USER_BC_BSP_JOB_TYPE_C.equals(job.get(Constants.USER_BC_BSP_JOB_TYPE, ""))) {
        LOG.info("[generalAggregate]: jobtype is c++");
        //      if (null == this.application) {
        //        try {
        //          LOG.info("jobC path is: " + job.getJobExe());
        //          LOG.info("BSPController localDir is : " + controller.getLocalDirs());
        //          LOG.info("BSP.local.dir is: " + conf.get("bcbsp.local.dir"));
        //          LOG.info("localJarFile is" + localJarFile);
        //          LOG.info("jobID is :" + this.getJobID());
        //          Path jobC = new Path(conf.get("bcbsp.local.dir")
        //              + "/controller/jobC_" + this.getJobID());
        //          String jarFile = job.getJobExe();
        //          String dir = controller.getSystemDir();
        //          // Path systemDirectory=new Path(dir);
        //          // alter by gtt
        //          // FileSystem systemFS = systemDirectory.getFileSystem(conf);
        //          BSPFileSystem bspsystemFS = new BSPFileSystemImpl(dir, conf);
        //          bspsystemFS.copyToLocalFile(new Path(jarFile), jobC);
        //          this.application = new Application(job, "WorkerManager",
        //              jobC.toString());
        //          // LOG.info("new application");
        //        } catch (IOException e1) {
        //          // TODO Auto-generated catch block
        //          // LOG.info("bspcontroller catch exception while new application" +
        //          // e1);
        //          throw new RuntimeException("bspcontroller catch"
        //              + "exception while new application", e1);
        //          // e1.printStackTrace();
        //        } catch (InterruptedException e1) {
        //          // TODO Auto-generated catch block
        //          throw new RuntimeException("bspcontroller catch"
        //              + "exception while new application", e1);
        //        }
        //      } else {
        //        LOG.info("application is not null");
        //      }
        //      for (int i = 0; i < ssrcs.length; i++) {
        //        String[] aggValues = ssrcs[i].getAggValues();
        //        if (null != aggValues) {
        //          // for (int j = 0; j < aggValues.length; j++) {
        //          // LOG.info("aggValue is: " + aggValues[j]);
        //          // }
        //          try {
        //            application.getDownlink().sendNewAggregateValue(aggValues);
        //          } catch (IOException e) {
        //            // TODO Auto-generated catch block
        //            throw new RuntimeException("send aggregateValue Exception! ", e);
        //          } catch (Throwable e) {
        //            // TODO Auto-generated catch block
        //            throw new RuntimeException("send aggregateValue Exception! ", e);
        //          }
        //        }
        //        // results=aggValues;
        //      }
        //      LOG.info("before superstep");
        //      try {
        //        application.getDownlink().runASuperStep();
        //        LOG.info("after superstep");
        //        LOG.info("wait for superstep  to finish");
        //        this.application.waitForFinish();
        //        ArrayList<String> aggregateValue = null;
        //        aggregateValue = this.application.getHandler().getAggregateValue();
        //        LOG.info("aggregateValue size is: " + aggregateValue.size());
        //        results = aggregateValue.toArray(new String[0]);
        //        for (int k = 0; k < results.length; k++) {
        //          LOG.info("aggregate results is: " + results[k]);
        //        }
        //        this.application.getHandler().getAggregateValue().clear();
        //      } catch (IOException e) {
        //        // TODO Auto-generated catch block
        //        throw new RuntimeException("get aggvalue Exception! ", e);
        //      } catch (Throwable e) {
        //        // TODO Auto-generated catch block
        //        throw new RuntimeException("get aggvalue Exception! ", e);
        //      }
    } else {
        // To get the aggregation values from the ssrcs.
        for (int i = 0; i < ssrcs.length; i++) {
            String[] aggValues = ssrcs[i].getAggValues();
            for (int j = 0; j < aggValues.length; j++) {
                String[] aggValueRecord = aggValues[j].split(Constants.KV_SPLIT_FLAG);
                String aggName = aggValueRecord[0];
                String aggValueString = aggValueRecord[1];
                AggregateValue aggValue = null;
                try {
                    aggValue = this.nameToAggregateValue.get(aggName).newInstance();
                    aggValue.initValue(aggValueString); // init the aggValue from its
                                                        // string form.
                } catch (InstantiationException e1) {
                    // LOG.error("InstantiationException", e1);
                    throw new RuntimeException("InstantiationException", e1);
                } catch (IllegalAccessException e2) {
                    // LOG.error("IllegalAccessException", e2);
                    throw new RuntimeException("IllegalAccessException", e2);
                } // end-try
                if (aggValue != null) {
                    ArrayList<AggregateValue> list = this.aggregateValues.get(aggName);
                    list.add(aggValue); // put the value to the values' list for
                                        // aggregation ahead.
                } // end-if
            } // end-for
        } // end-for
          // To aggregate the values from the aggregateValues.
        this.aggregateResults.clear(); // Clear the results' container before a
                                       // new
                                       // calculation.
                                       // To calculate the aggregations.
        for (Entry<String, Class<? extends Aggregator<?>>> entry : this.nameToAggregator.entrySet()) {
            Aggregator<AggregateValue> aggregator = null;
            try {
                aggregator = (Aggregator<AggregateValue>) entry.getValue().newInstance();
            } catch (InstantiationException e1) {
                // LOG.error("InstantiationException", e1);
                throw new RuntimeException("InstantiationException", e1);
            } catch (IllegalAccessException e2) {
                // LOG.error("IllegalAccessException", e2);
                throw new RuntimeException("IllegalAccessException", e2);
            }
            if (aggregator != null) {
                ArrayList<AggregateValue> aggVals = this.aggregateValues.get(entry.getKey());
                AggregateValue resultValue = aggregator.aggregate(aggVals);
                this.aggregateResults.put(entry.getKey(), resultValue);
                aggVals.clear(); // Clear the initial aggregate values after
                                 // aggregation completes.
            }
        } // end-for
        /**
         * To encapsulate the aggregation values to the String[] results. The
         * aggValues should be in form as follows: [ AggregateName \t
         * AggregateValue.toString() ]
         */
        int aggSize = this.aggregateResults.size();
        results = new String[aggSize];
        int i_a = 0;
        for (Entry<String, AggregateValue> entry : this.aggregateResults.entrySet()) {
            results[i_a] = entry.getKey() + Constants.KV_SPLIT_FLAG + entry.getValue().toString();
            i_a++;
        }
    }
    return results;
}

From source file:com.yoctopuce.YoctoAPI.YSerialPort.java

/**
 * Reads data from the receive buffer as a list of bytes, starting at current stream position.
 * If data at current stream position is not available anymore in the receive buffer, the
 * function performs a short read.// w  ww  .ja va  2 s .c o m
 *
 * @param nChars : the maximum number of bytes to read
 *
 * @return a sequence of bytes with receive buffer contents
 *
 * @throws YAPI_Exception on error
 */
public ArrayList<Integer> readArray(int nChars) throws YAPI_Exception {
    byte[] buff;
    int bufflen;
    int mult;
    int endpos;
    int idx;
    int b;
    ArrayList<Integer> res = new ArrayList<Integer>();
    if (nChars > 65535) {
        nChars = 65535;
    }
    // may throw an exception
    buff = _download(String.format("rxdata.bin?pos=%d&len=%d", _rxptr, nChars));
    bufflen = (buff).length - 1;
    endpos = 0;
    mult = 1;
    while ((bufflen > 0) && (buff[bufflen] != 64)) {
        endpos = endpos + mult * (buff[bufflen] - 48);
        mult = mult * 10;
        bufflen = bufflen - 1;
    }
    _rxptr = endpos;
    res.clear();
    idx = 0;
    while (idx < bufflen) {
        b = buff[idx];
        res.add(b);
        idx = idx + 1;
    }
    return res;
}

From source file:com.flexive.ejb.beans.ScriptingEngineBean.java

/**
 * Execute all runOnce scripts in the resource denoted by prefix if param is "false"
 *
 * @param param           boolean parameter that will be flagged as "true" once the scripts are run
 * @param dropName        the drop application name
 * @param prefix          resource directory prefix
 * @param applicationName the corresponding application name (for debug messages)
 * @throws FxApplicationException on errors
 *//*from   w  w w.j  a va 2s. c  o m*/
private void runOnce(Parameter<Boolean> param, String dropName, String prefix, String applicationName)
        throws FxApplicationException {
    synchronized (RUNONCE_LOCK) {
        try {
            Boolean executed = getDivisionConfigurationEngine().get(param);
            if (executed) {
                return;
            }
        } catch (FxApplicationException e) {
            LOG.error(e);
            return;
        }
        //noinspection unchecked
        final ArrayList<FxScriptRunInfo> divisionRunOnceInfos = Lists
                .newArrayList(getDivisionConfigurationEngine().get(SystemParameters.DIVISION_RUNONCE_INFOS));

        LocalScriptingCache.runOnceInfos = new CopyOnWriteArrayList<FxScriptRunInfo>();
        LocalScriptingCache.runOnceInfos.addAll(divisionRunOnceInfos);

        FxContext.get().setExecutingRunOnceScripts(true);
        try {
            executeInitializerScripts("runonce", dropName, prefix, applicationName,
                    new RunonceScriptExecutor(applicationName));
        } finally {
            FxContext.get().setExecutingRunOnceScripts(false);
        }

        // TODO: this fails to update the script infos when the transaction was rolled back because of a script error
        FxContext.get().runAsSystem();
        try {
            divisionRunOnceInfos.clear();
            divisionRunOnceInfos.addAll(LocalScriptingCache.runOnceInfos);
            getDivisionConfigurationEngine().put(SystemParameters.DIVISION_RUNONCE_INFOS, divisionRunOnceInfos);
            getDivisionConfigurationEngine().put(param, true);
            LocalScriptingCache.runOnceInfos = null;
        } finally {
            FxContext.get().stopRunAsSystem();
        }
    }
}

From source file:isl.FIMS.servlet.imports.ImportXML.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("EisagwghXML_RDF");
    String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";
    String displayMsg = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    //  ArrayList<String> notValidMXL = new ArrayList<String>();
    HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap();
    if (!ServletFileUpload.isMultipartContent(request)) {
        displayMsg = "form";
    } else {// w w  w.j  a v a  2 s.c  o  m
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);
        ArrayList<String> savedIDs = new ArrayList<String>();

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;
        int xmlCount = 0;
        String[] id = null;
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    Utils.unzip(fileName, uploadPath);
                    File dir = new File(uploadPath);

                    String[] extensions = new String[] { "xml", "x3ml" };
                    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
                    xmlCount = files.size();
                    for (File file : files) {
                        // saves the file on disk
                        Document doc = ParseXMLFile.parseFile(file.getPath());
                        String xmlContent = doc.getDocumentElement().getTextContent();
                        String uri_name = "";
                        try {
                            uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
                        } catch (DMSException ex) {
                            ex.printStackTrace();
                        }
                        String uriValue = this.URI_Reference_Path + uri_name + "/";
                        boolean insertEntity = false;
                        if (xmlContent.contains(uriValue) || file.getName().contains(type)) {
                            insertEntity = true;
                        }
                        Element root = doc.getDocumentElement();
                        Node admin = Utils.removeNode(root, "admin", true);

                        //  File rename = new File(uploadPath + File.separator + id[0] + ".xml");
                        //  boolean isRename = storeFile.renameTo(rename);
                        //   ParseXMLFile.saveXMLDocument(rename.getPath(), doc);
                        String schemaFilename = "";
                        schemaFilename = type;

                        SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd");
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        StringWriter writer = new StringWriter();
                        transformer.transform(new DOMSource(doc), new StreamResult(writer));
                        String xmlString = writer.getBuffer().toString().replaceAll("\r", "");

                        //without admin
                        boolean isValid = sch.validate(xmlString);
                        if ((!isValid && insertEntity)) {
                            notValidMXL.put(file.getName(), null);
                        } else if (insertEntity) {
                            id = initInsertFile(type, false);
                            doc = createAdminPart(id[0], type, doc, username);
                            writer = new StringWriter();
                            transformer.transform(new DOMSource(doc), new StreamResult(writer));
                            xmlString = writer.getBuffer().toString().replaceAll("\r", "");
                            DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser,
                                    this.DBpassword);
                            DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile");
                            dbF.setXMLAsString(xmlString);
                            dbF.store();
                            ArrayList<String> externalFiles = new <String>ArrayList();
                            ArrayList<String> externalDBFiles = new <String>ArrayList();

                            String q = "//*[";
                            for (String attrSet : this.uploadAttributes) {
                                String[] temp = attrSet.split("#");
                                String func = temp[0];
                                String attr = temp[1];
                                if (func.contains("text")) {
                                    q += "@" + attr + "]/text()";
                                } else {
                                    q = "data(//*[@" + attr + "]/@" + attr + ")";
                                }
                                String[] res = dbF.queryString(q);
                                for (String extFile : res) {
                                    externalFiles.add(extFile + "#" + attr);
                                }
                            }
                            q = "//";
                            if (!dbSchemaPath[0].equals("")) {
                                for (String attrSet : this.dbSchemaPath) {
                                    String[] temp = attrSet.split("#");
                                    String func = temp[0];
                                    String path = temp[1];
                                    if (func.contains("text")) {
                                        q += path + "//text()";
                                    } else {
                                        q = "data(//" + path + ")";
                                    }
                                    String[] res = dbF.queryString(q);
                                    for (String extFile : res) {
                                        externalDBFiles.add(extFile);
                                    }
                                }
                            }
                            ArrayList<String> missingExternalFiles = new <String>ArrayList();
                            for (String extFile : externalFiles) {
                                extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                List<File> f = (List<File>) FileUtils.listFiles(dir,
                                        FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                if (f.size() == 0) {
                                    missingExternalFiles.add(extFile);
                                }
                            }
                            if (missingExternalFiles.size() > 0) {
                                notValidMXL.put(file.getName(), missingExternalFiles);
                            }

                            XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type,
                                    this.DBuser, this.DBpassword, type, id[0]);

                            ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type,
                                    this.DBuser, this.DBpassword);
                            if (worngFiles.size() > 0) {
                                //dbF.remove();
                                notValidMXL.put(file.getName(), worngFiles);
                            }
                            //remove duplicates from externalFiles if any
                            HashSet hs = new HashSet();
                            hs.addAll(missingExternalFiles);
                            missingExternalFiles.clear();
                            missingExternalFiles.addAll(hs);
                            if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) {

                                for (String extFile : externalFiles) {
                                    String attr = extFile.substring(extFile.lastIndexOf("#") + 1,
                                            extFile.length());
                                    extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                    List<File> f = (List<File>) FileUtils.listFiles(dir,
                                            FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                    File uploadFile = f.iterator().next();
                                    String content = FileUtils.readFileToString(uploadFile);

                                    DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection,
                                            "Uploads.xml", this.DBuser, this.DBpassword);
                                    String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr);
                                    String uniqueName = Utils.createUniqueFilename(uploadFile.getName());
                                    File uploadFileUnique = new File(uploadFile.getPath().substring(0,
                                            uploadFile.getPath().lastIndexOf(File.separator)) + File.separator
                                            + uniqueName);
                                    uploadFile.renameTo(uploadFileUnique);
                                    xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName);
                                    String upload_path = this.systemUploads + type;
                                    File upload_dir = null;
                                    ;
                                    if (mime.equals("Photos")) {
                                        upload_path += File.separator + mime + File.separator + "original"
                                                + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "thumbs"), thumbSize);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "normal"), normalSize);
                                        xmlString = xmlString.replace("</versions>",
                                                "</versions>" + "\n" + "<type>Photos</type>");
                                    } else {
                                        upload_path += File.separator + mime + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                    }
                                    if (!dbSchemaFolder.equals("")) {
                                        if (externalDBFiles.contains(extFile)) {
                                            try {
                                                DBCollection colSchema = new DBCollection(this.DBURI,
                                                        dbSchemaFolder, this.DBuser, this.DBpassword);
                                                DBFile dbFSchema = colSchema.createFile(uniqueName,
                                                        "XMLDBFile");
                                                dbFSchema.setXMLAsString(content);
                                                dbFSchema.store();
                                            } catch (Exception e) {
                                            }
                                        }
                                    }
                                    uploadFileUnique.renameTo(uploadFile);

                                }
                                dbF.setXMLAsString(xmlString);
                                dbF.store();
                                Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser);
                                Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser, lang);
                                savedIDs.add(id[0]);
                            } else {
                                dbF.remove();
                            }

                        }
                    }

                }
            }
            Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml");
            Element root = doc.getDocumentElement();
            Element contextTag = (Element) root.getElementsByTagName("context").item(0);
            String uri_name = "";
            try {
                uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
            } catch (DMSException ex) {
            }
            if (notValidMXL.size() == 0) {
                xsl = conf.DISPLAY_XSL;
                displayMsg = Messages.ACTION_SUCCESS;
                displayMsg += Messages.NL + Messages.NL + Messages.URI_ID;
                String uriValue = "";
                xml.append("<Display>").append(displayMsg).append("</Display>\n");
                xml.append("<backPages>").append('2').append("</backPages>\n");

                for (String saveId : savedIDs) {
                    uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL;
                    xml.append("<codeValue>").append(uriValue).append("</codeValue>\n");

                }

            } else if (notValidMXL.size() >= 1) {
                xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";

                Iterator it = notValidMXL.keySet().iterator();
                while (it.hasNext()) {

                    String key = (String) it.next();
                    ArrayList<String> value = notValidMXL.get(key);

                    if (value != null) {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace("?", key);
                        for (String mis_res : value) {

                            displayMsg += mis_res + ",";
                        }
                        displayMsg = displayMsg.substring(0, displayMsg.length() - 1);
                        displayMsg += ".";
                        displayMsg += "</line>";

                    } else {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace(";", key);
                        displayMsg += "</line>";
                    }
                    displayMsg += "<line>";
                    displayMsg += "</line>";
                }
                if (notValidMXL.size() < xmlCount) {
                    displayMsg += "<line>";
                    Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0);
                    displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                    displayMsg += "</line>";
                    for (String saveId : savedIDs) {
                        displayMsg += "<line>";
                        String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId;
                        select = (Element) contextTag.getElementsByTagName("URI_ID").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": "
                                + uriValue;
                        displayMsg += "</line>";
                    }
                }
            }
            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
            displayMsg += Messages.NOT_VALID_IMPORT;
        }

    }
    xml.append("<Display>").append(displayMsg).append("</Display>\n");
    xml.append("<EntityType>").append(type).append("</EntityType>\n");
    xml.append(this.xmlEnd());
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:org.powertac.server.CompetitionControlService.java

private boolean configurePlugins() {
    List<InitializationService> initializers = SpringApplicationContext
            .listBeansOfType(InitializationService.class);

    ArrayList<String> completedPlugins = new ArrayList<String>();
    ArrayList<InitializationService> deferredInitializers = new ArrayList<InitializationService>();
    for (InitializationService initializer : initializers) {
        if (bootstrapMode) {
            if (initializer.equals(visualizerProxyService) || initializer.equals(jmsManagementService)) {
                log.info("Skipping initialization of " + initializer.toString());
                continue;
            }/*from   w  ww  .ja  v  a 2  s.c o  m*/
        }

        log.info("attempt to initialize " + initializer.toString());
        String success = initializer.initialize(competition, completedPlugins);
        if (success == null) {
            // defer this one
            log.info("deferring " + initializer.toString());
            deferredInitializers.add(initializer);
        } else if (success.equals("fail")) {
            log.error("Failed to initialize plugin " + initializer.toString());
            return false;
        } else {
            log.info("completed " + success);
            completedPlugins.add(success);
        }
    }

    int tryCounter = deferredInitializers.size();
    while (deferredInitializers.size() > 0 && tryCounter > 0) {
        InitializationService initializer = deferredInitializers.get(0);
        log.info("additional attempt to initialize " + initializer.toString());
        if (deferredInitializers.size() > 1) {
            deferredInitializers.remove(0);
        } else {
            deferredInitializers.clear();
        }
        String success = initializer.initialize(competition, completedPlugins);
        if (success == null) {
            // defer this one
            log.info("deferring " + initializer.toString());
            deferredInitializers.add(initializer);
            tryCounter -= 1;
        } else {
            log.info("completed " + success);
            completedPlugins.add(success);
        }
    }
    for (InitializationService initializer : deferredInitializers) {
        log.error("Failed to initialize " + initializer.toString());
    }
    return true;
}

From source file:com.baidu.cafe.local.record.WebElementRecorder.java

public void handleWebElementRecordEventQueue() {
    new Thread(new Runnable() {
        public void run() {
            ArrayList<WebElementRecordEvent> events = new ArrayList<WebElementRecordEvent>();
            while (true) {
                WebElementRecordEvent lastRecordEvent = null;
                long endTime = System.currentTimeMillis() + TIMEOUT_NEXT_EVENT;
                WebElementRecordEvent e = null;
                while (true) {
                    e = null;//from w  ww  .j  av a2  s  .  c  om
                    if ((e = pollWebElementRecordEventQueue()) != null) {
                        // here comes a record event
                        endTime = System.currentTimeMillis() + TIMEOUT_NEXT_EVENT;
                        if (lastRecordEvent == null) {
                            // if e is the first record event
                            events.add(e);
                            lastRecordEvent = e;
                        } else {
                            if (e.time > lastRecordEvent.time
                                    && e.familyString.equals(lastRecordEvent.familyString)) {
                                events.add(e);
                                lastRecordEvent = e;
                            } else {
                                offerOutputEventQueue(events);
                                lastRecordEvent = null;
                                events.clear();
                            }
                        }
                    } else {
                        // wait until timeout, then offerOutputEventQueue
                        if (System.currentTimeMillis() > endTime) {
                            offerOutputEventQueue(events);
                            lastRecordEvent = null;
                            events.clear();
                            sleep(50);
                            break;
                        }
                    }
                    sleep(10);
                }
            }
        }
    }).start();
}

From source file:gdsc.core.clustering.ClusteringEngine.java

/**
 * Join valid links between clusters. Resets the link candidates. Use the neighbour count property to flag if the
 * candidate was joined to another cluster.
 * /*from   ww  w.  ja  va 2  s.  c  om*/
 * @param grid
 * @param nXBins
 * @param nYBins
 * @param r2
 * @param candidates
 *            Re-populate will all the remaining clusters
 * @param singles
 *            Add any clusters with no neighbours
 * @return The number of joins that were made
 */
private int joinLinks(Cluster[][] grid, int nXBins, int nYBins, double r2, ArrayList<Cluster> candidates,
        ArrayList<Cluster> joined, ArrayList<Cluster> singles) {
    candidates.clear();
    joined.clear();

    double min = r2;
    Cluster cluster1 = null, cluster2 = null;
    for (int yBin = 0; yBin < nYBins; yBin++) {
        for (int xBin = 0; xBin < nXBins; xBin++) {
            Cluster previous = null;
            for (Cluster c1 = grid[xBin][yBin]; c1 != null; c1 = c1.next) {
                int joinFlag = 0;
                if (c1.validLink()) {
                    // Check if each cluster only has 1 neighbour
                    if (c1.neighbour == 1 && c1.closest.neighbour == 1) {
                        //System.out.printf("Joining pairs with no neighbours @ %f\n", Math.sqrt(c1.d2));
                        c1.add(c1.closest);
                        joined.add(c1.closest);
                        joinFlag = 1;
                    } else if (c1.d2 < min) {
                        // Otherwise find the closest pair in case no joins are made
                        min = c1.d2;
                        cluster1 = c1;
                        cluster2 = c1.closest;
                    }
                }
                // Reset the link candidates
                c1.closest = null;

                // Check for singles
                if (c1.neighbour == 0) {
                    // Add singles to the singles list and remove from the grid
                    singles.add(c1);
                    if (previous == null)
                        grid[xBin][yBin] = c1.next;
                    else
                        previous.next = c1.next;
                } else {
                    previous = c1;

                    // Store all remaining clusters
                    if (c1.n != 0) {
                        candidates.add(c1);
                        c1.neighbour = joinFlag;
                    }
                }
            }
        }
    }

    //// If no joins were made then join the closest pair
    //if (joined.isEmpty() && cluster1 != null)

    // Always join the closest pair if it has not been already
    if (cluster1 != null && cluster1.neighbour == 0) {
        //System.out.printf("Joining closest pair @ %f\n", Math.sqrt(cluster1.d2));
        cluster1.add(cluster2);
        // Remove cluster 2 from the candidates
        candidates.remove(cluster2);
        joined.add(cluster2);
        cluster1.neighbour = 1;
    }

    return joined.size();
}

From source file:com.mci.firstidol.activity.MainActivity.java

@Override
protected void initData() {
    // ???/*from  w  w w . j a  va 2s  .  c  o  m*/
    Bundle pBundle = getIntent().getExtras();
    if (pBundle != null) {
        String customContent = pBundle.getString(Constant.IntentKey.customContent);
        if (!TextUtils.isEmpty(customContent)) {// ?
            obtainBaiduPushClickEvent(customContent);
        }
    }

    // ?????
    if (!dataManager.isLogin) {
        return;
    }

    ArrayList<HashMap<String, String>> loginDays = (ArrayList<HashMap<String, String>>) PreferencesUtils
            .getComplexObject(context, "LoginDays");
    // if (loginDays!=null) {
    // loginDays.clear();
    // }
    //
    // PreferencesUtils.putComplexObject(context, "LoginDays", loginDays);

    if (loginDays != null && loginDays.size() > 0) {// ?
        HashMap<String, String> lastDayDict = loginDays.get(loginDays.size() - 1);// ????

        // ?
        String result = lastDayDict.get(DateHelper.getCurrentDate("yyyy-MM-dd"));
        if ("Y".equals(result)) {// ?
            // ???
        } else {// 
            // ?
            // ???
            String value = lastDayDict.get(DateHelper.addDay(DateHelper.getCurrentDate("yyyy-MM-dd"), -1));
            if ("Y".equals(value)) {// 
                // ?
                if (loginDays.size() == 6) {// ?6
                    ToastUtils.showPointToast("10");
                    HashMap<String, String> pointDict = new HashMap<String, String>();
                    pointDict.put(DateHelper.getCurrentDate("yyyy-MM-dd"), "Y");
                    loginDays.add(pointDict);
                } else if (loginDays.size() == 7) {// 8??
                    loginDays.clear();
                    HashMap<String, String> pointDict = new HashMap<String, String>();
                    pointDict.put(DateHelper.getCurrentDate("yyyy-MM-dd"), "Y");
                    loginDays.add(pointDict);
                } else {// ?7
                    HashMap<String, String> pointDict = new HashMap<String, String>();
                    pointDict.put(DateHelper.getCurrentDate("yyyy-MM-dd"), "Y");
                    loginDays.add(pointDict);
                }
                // ?
                PreferencesUtils.putComplexObject(context, "LoginDays", loginDays);
            } else {// 
                ToastUtils.showPointToast("5");
                loginDays.clear();
                PreferencesUtils.putComplexObject(context, "LoginDays", loginDays);
            }
        }
    } else {// 
        ToastUtils.showPointToast("5");

        loginDays = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> pointDict = new HashMap<String, String>();
        pointDict.put(DateHelper.getCurrentDate("yyyy-MM-dd"), "Y");
        loginDays.add(pointDict);

        // ?
        PreferencesUtils.putComplexObject(context, "LoginDays", loginDays);
    }
}

From source file:org.kuali.student.myplan.course.controller.CourseSearchController.java

/**
 * Gets the CluIds from the given search requests
 *
 * @param requests//w w w .j a  va 2s  .co  m
 * @return
 * @throws MissingParameterException
 */
public ArrayList<Hit> processSearchRequests(List<SearchRequestInfo> requests) throws MissingParameterException {
    logger.info("Start of processSearchRequests of CourseSearchController:" + System.currentTimeMillis());

    ArrayList<Hit> hits = new ArrayList<Hit>();
    ArrayList<Hit> tempHits = new ArrayList<Hit>();
    List<String> courseIds = new ArrayList<String>();
    for (SearchRequestInfo request : requests) {
        SearchResultInfo searchResult = null;
        try {
            searchResult = getLuService().search(request, CourseSearchConstants.CONTEXT_INFO);
        } catch (InvalidParameterException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (OperationFailedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (PermissionDeniedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        for (SearchResultRow row : searchResult.getRows()) {
            String id = SearchHelper.getCellValue(row, "lu.resultColumn.cluId");
            if (!courseIds.contains(id)) {
                /* hitCourseID(courseMap, id);*/
                courseIds.add(id);
                Hit hit = new Hit(id);
                tempHits.add(hit);

            }

        }
        tempHits.removeAll(hits);
        hits.addAll(tempHits);
        tempHits.clear();
    }

    logger.info("End of processSearchRequests of CourseSearchController:" + System.currentTimeMillis());
    return hits;
}

From source file:com.jomp16.google.Google.java

@Override
public void onGenericMessage(GenericMessageEvent event) throws Exception {
    ArrayList<String> args = new ArrayList<>();
    Matcher matcher = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'").matcher(event.getMessage());
    while (matcher.find()) {
        if (matcher.group(1) != null) {
            // Add double-quoted string without the quotes
            args.add(matcher.group(1));//from   ww w .j  a  va2  s  .c  o m
        } else if (matcher.group(2) != null) {
            // Add single-quoted string without the quotes
            args.add(matcher.group(2));
        } else {
            // Add unquoted word
            args.add(matcher.group());
        }
    }
    if (args.get(0).toLowerCase().equals(prefix + "google")) {
        if (args.size() >= 2) {
            String url = String.format(GOOGLE, URLEncoder.encode(args.get(1), "UTF-8"));
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(Request.Get(url).execute().returnContent().asStream()));
            GoogleSearch search = new Gson().fromJson(reader, GoogleSearch.class);

            reader.close();
            if (!search.responseStatus.equals("200")) {
                event.respond(languageManager.getString("Error"));
                return;
            }
            if (search.responseData.results.size() <= 0) {
                event.respond(languageManager.getString("NoResultsFound"));
                return;
            }

            if (args.size() >= 3) {
                for (int i = 0; i < Integer.parseInt(args.get(2)); i++) {
                    String title = StringEscapeUtils
                            .unescapeHtml4(search.responseData.results.get(i).titleNoFormatting);
                    String url2 = URLDecoder.decode(search.responseData.results.get(i).unescapedUrl, "UTF-8");
                    event.respond(languageManager.getString("Result", (i + 1), title, url2));
                }
            } else {
                String title = StringEscapeUtils
                        .unescapeHtml4(search.responseData.results.get(0).titleNoFormatting);
                String url2 = URLDecoder.decode(search.responseData.results.get(0).unescapedUrl, "UTF-8");
                event.respond(languageManager.getString("Result", 1, title, url2));
            }
        } else {
            event.respond(languageManager.getString("CommandSyntax", prefix));
        }
        args.clear();
    }
}