Example usage for java.util LinkedList size

List of usage examples for java.util LinkedList size

Introduction

In this page you can find the example usage for java.util LinkedList size.

Prototype

int size

To view the source code for java.util LinkedList size.

Click Source Link

Usage

From source file:org.mycard.net.network.Connection.java

/***
 * Process requests in queue/*ww  w  .  jav  a  2  s.c  o  m*/
 * pipelines requests
 */
void processRequests(Request firstRequest) {
    Request req = null;
    boolean empty;
    int error = EventHandler.OK;
    Exception exception = null;

    LinkedList<Request> pipe = new LinkedList<Request>();

    int minPipe = MIN_PIPE, maxPipe = MAX_PIPE;
    int state = SEND;

    while (state != DONE) {
        /** If a request was cancelled, give other cancel requests
           some time to go through so we don't uselessly restart
           connections */
        if (mActive == STATE_CANCEL_REQUESTED) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException x) {
                /** ignore */
            }
            mActive = STATE_NORMAL;
        }

        switch (state) {
        case SEND: {
            if (pipe.size() == maxPipe) {
                state = READ;
                break;
            }
            /** get a request */
            if (firstRequest == null) {
                req = mRequestFeeder.getRequest(mHost);
            } else {
                req = firstRequest;
                firstRequest = null;
            }
            if (req == null) {
                state = DRAIN;
                break;
            }
            req.setConnection(this);

            /** Don't work on cancelled requests. */
            if (req.mCancelled) {
                req.complete();
                break;
            }

            if (mHttpClientConnection == null || !mHttpClientConnection.isOpen()) {
                /** If this call fails, the address is bad or
                   the net is down.  Punt for now.
                        
                   FIXME: blow out entire queue here on
                   connection failure if net up? */

                if (!openHttpConnection(req)) {
                    state = DONE;
                    break;
                }
            }

            /** we have a connection, let the event handler
             * know of any associated certificate,
             * potentially none.
             */
            //req.mEventHandler.certificate(mCertificate);

            try {
                /** FIXME: don't increment failure count if old
                   connection?  There should not be a penalty for
                   attempting to reuse an old connection */
                req.sendRequest(mHttpClientConnection);
            } catch (HttpException e) {
                exception = e;
                error = EventHandler.ERROR;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /** retry request if not permanent failure
                       or cancelled */
                    pipe.addLast(req);
                }
                exception = null;
                state = clearPipe(pipe) ? DONE : SEND;
                minPipe = maxPipe = 1;
                break;
            }

            pipe.addLast(req);
            if (!mCanPersist)
                state = READ;
            break;

        }
        case DRAIN:
        case READ: {
            empty = !mRequestFeeder.haveRequest(mHost);
            int pipeSize = pipe.size();
            if (state != DRAIN && pipeSize < minPipe && !empty && mCanPersist) {
                state = SEND;
                break;
            } else if (pipeSize == 0) {
                /** Done if no other work to do */
                state = empty ? DONE : SEND;
                break;
            }

            req = (Request) pipe.removeFirst();

            try {
                req.readResponse(mHttpClientConnection);
            } catch (ParseException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /** retry request if not permanent failure
                       or cancelled */
                    req.reset();
                    pipe.addFirst(req);
                }
                exception = null;
                mCanPersist = false;
            }
            if (!mCanPersist) {

                closeConnection();

                mHttpContext.removeAttribute(HTTP_CONNECTION);
                clearPipe(pipe);
                minPipe = maxPipe = 1;
                state = SEND;
            }
            break;
        }
        }
    }
}

From source file:com.android.deskclock.timer.TimerFullScreenFragment.java

public void updateAllTimesUpTimers() {
    boolean notifyChange = false;
    //  To avoid race conditions where a timer was dismissed and it is still in the timers list
    // and can be picked again, create a temporary list of timers to be removed first and
    // then removed them one by one
    LinkedList<TimerObj> timesupTimers = new LinkedList<>();
    for (int i = 0; i < mAdapter.getCount(); i++) {
        TimerObj timerObj = mAdapter.getItem(i);
        if (timerObj.mState == TimerObj.STATE_TIMESUP) {
            timesupTimers.addFirst(timerObj);
            notifyChange = true;//from www .j  a v  a2  s.  c  o  m
        }
    }

    while (timesupTimers.size() > 0) {
        final TimerObj t = timesupTimers.remove();
        onStopButtonPressed(t);
    }

    if (notifyChange) {
        mPrefs.edit().putBoolean(Timers.REFRESH_UI_WITH_LATEST_DATA, true).apply();
    }
}

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

/**
 * /* w  w  w .  j a  v a2s  . c  o  m*/
 * @throws DMLRuntimeException
 * @throws DMLUnsupportedOperationException
 * @throws IOException
 */
private static void executeTest() throws DMLRuntimeException, DMLUnsupportedOperationException, IOException {
    System.out.println("SystemML PERFORMANCE TEST TOOL:");

    //foreach registered instruction   
    for (Entry<Integer, Instruction> inst : _regInst.entrySet()) {
        int instID = inst.getKey();
        System.out.println("Running INSTRUCTION " + _regInst_IDNames.get(instID));

        Integer[] testDefIDs = _regInst_IDTestDef.get(instID);
        boolean vectors = _regInst_IDVectors.get(instID);
        IOSchema schema = _regInst_IDIOSchema.get(instID);

        //create tmp program block and set instruction
        Program prog = new Program();
        ProgramBlock pb = new ProgramBlock(prog);
        ArrayList<Instruction> ainst = new ArrayList<Instruction>();
        ainst.add(inst.getValue());
        pb.setInstructions(ainst);

        ExecutionContext ec = ExecutionContextFactory.createContext();

        //foreach registered test configuration
        for (Integer defID : testDefIDs) {
            PerfTestDef def = _regTestDef.get(defID);
            TestMeasure m = def.getMeasure();
            TestVariable lv = def.getVariable();
            DataFormat df = def.getDataformat();
            InternalTestVariable[] pv = def.getInternalVariables();
            double min = def.getMin();
            double max = def.getMax();
            double samples = def.getNumSamples();

            System.out.println("Running TESTDEF(measure=" + m + ", variable=" + String.valueOf(lv) + " "
                    + pv.length + ", format=" + String.valueOf(df) + ")");

            //vary input variable
            LinkedList<Double> dmeasure = new LinkedList<Double>();
            LinkedList<Double> dvariable = generateSequence(min, max, samples);
            int plen = pv.length;

            if (plen == 1) //1D function 
            {
                for (Double var : dvariable) {
                    dmeasure.add(executeTestCase1D(m, pv[0], df, var, pb, vectors, schema, ec));
                }
            } else //multi-dim function
            {
                //init index stack
                int[] index = new int[plen];
                for (int i = 0; i < plen; i++)
                    index[i] = 0;

                //execute test 
                int dlen = dvariable.size();
                double[] buff = new double[plen];
                while (index[0] < dlen) {
                    //set buffer values
                    for (int i = 0; i < plen; i++)
                        buff[i] = dvariable.get(index[i]);

                    //core execution
                    dmeasure.add(executeTestCaseMD(m, pv, df, buff, pb, schema, ec)); //not applicable for vector flag

                    //increment indexes
                    for (int i = plen - 1; i >= 0; i--) {
                        if (i == plen - 1)
                            index[i]++;
                        else if (index[i + 1] >= dlen) {
                            index[i]++;
                            index[i + 1] = 0;
                        }
                    }
                }
            }

            //append values to results
            if (!_results.containsKey(instID))
                _results.put(instID, new HashMap<Integer, LinkedList<Double>>());
            _results.get(instID).put(defID, dmeasure);

        }
    }
}

From source file:fr.univlorraine.mondossierweb.views.RechercheMobileView.java

private List<ResultatDeRecherche> quickSearch(String valueString) {

    List<ResultatDeRecherche> listeReponses = new LinkedList<ResultatDeRecherche>();

    String value = valueString;//from   w w w  .j a  va2 s .co m
    if (StringUtils.hasText(value) && value.length() > 2) {

        ///////////////////////////////////////////////////////
        //appel elasticSearch
        ///////////////////////////////////////////////////////
        //transformation de la chaine recherche en fonction des besoins
        String valueselasticSearch = value;

        //valueselasticSearch = valueselasticSearch+"*";
        List<Map<String, Object>> lobjresult = ElasticSearchService.findObj(valueselasticSearch,
                Utils.NB_MAX_RESULT_QUICK_SEARCH * 5, true);

        //Liste des types autoriss
        LinkedList<String> listeTypeAutorise = new LinkedList();
        if (casesAcocherVet) {
            listeTypeAutorise.add(Utils.VET);
        }
        if (casesAcocherElp) {
            listeTypeAutorise.add(Utils.ELP);
        }
        if (casesAcocherEtudiant) {
            listeTypeAutorise.add(Utils.ETU);
        }

        ///////////////////////////////////////////////////////
        // recuperation des obj ElasticSearch
        ///////////////////////////////////////////////////////
        if (lobjresult != null && listeTypeAutorise.size() > 0) {
            for (Map<String, Object> obj : lobjresult) {
                if (listeReponses.size() < Utils.NB_MAX_RESULT_QUICK_SEARCH) {
                    if (obj != null) {
                        if (listeTypeAutorise.contains((String) obj.get(Utils.ES_TYPE))) {
                            if (listeReponses.size() > 0) {
                                boolean triOk = true;
                                int rang = 0;
                                //On evite des doublons
                                while (triOk && rang < listeReponses.size()) {
                                    //En quickSearch on prend la description et non pas le libelle
                                    if ((listeReponses.get(rang).lib.toUpperCase())
                                            .equals((new ResultatDeRecherche(obj)).lib.toUpperCase())) {
                                        triOk = false;
                                    }
                                    rang++;
                                }
                                if (triOk) {
                                    //En quickSearch on prend la description et non pas le libelle
                                    listeReponses.add(new ResultatDeRecherche(obj));
                                }
                            } else {
                                //En quickSearch on prend la description et non pas le libelle
                                listeReponses.add(new ResultatDeRecherche(obj));
                            }
                        }
                    }
                }
            }
        }

    }

    return listeReponses;

}

From source file:com.github.lindenb.jvarkit.tools.misc.BamTile.java

@Override
public Collection<Throwable> call(final String inputName) throws Exception {
    SAMRecordIterator iter = null;/* w  ww .  ja  v  a 2s .co m*/
    SamReader sfr = null;
    SAMFileWriter sfw = null;
    try {
        sfr = openSamReader(inputName);

        SAMFileHeader header1 = sfr.getFileHeader();
        if (header1 == null) {
            return wrapException("File header missing");
        }

        if (header1.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
            return wrapException("File header not sorted on coordinate");
        }

        SAMFileHeader header2 = header1.clone();
        header2.addComment(getName() + ":" + getVersion() + ":" + getProgramCommandLine());

        sfw = openSAMFileWriter(header2, true);

        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header1);
        iter = sfr.iterator();
        LinkedList<SAMRecord> buffer = new LinkedList<>();
        for (;;) {
            SAMRecord rec = null;
            if (iter.hasNext()) {
                rec = progress.watch(iter.next());
                if (rec.getReadUnmappedFlag())
                    continue;
                if (!buffer.isEmpty()) {
                    SAMRecord last = buffer.getLast();
                    if (last.getReferenceIndex() == rec.getReferenceIndex()
                            && last.getAlignmentStart() <= rec.getAlignmentStart()
                            && last.getAlignmentEnd() >= rec.getAlignmentEnd()) {
                        continue;
                    }
                }
            }
            if (rec == null
                    || (!buffer.isEmpty() && buffer.getLast().getReferenceIndex() != rec.getReferenceIndex())) {
                while (!buffer.isEmpty()) {
                    sfw.addAlignment(buffer.removeFirst());
                }
                if (rec == null)
                    break;
            }
            buffer.add(rec);

            if (buffer.size() > 2) {
                int index = buffer.size();
                SAMRecord prev = buffer.get(index - 3);
                SAMRecord curr = buffer.get(index - 2);
                SAMRecord next = buffer.get(index - 1);

                if (prev.getAlignmentEnd() >= next.getAlignmentStart()
                        || curr.getAlignmentEnd() <= prev.getAlignmentEnd()) {
                    buffer.remove(index - 2);
                } else if (curr.getAlignmentStart() == prev.getAlignmentStart()
                        && curr.getAlignmentEnd() > prev.getAlignmentEnd()) {
                    buffer.remove(index - 3);
                }

            }
            while (buffer.size() > 3) {
                sfw.addAlignment(buffer.removeFirst());
            }

        }
        progress.finish();
        LOG.info("done");
        return Collections.emptyList();
    } catch (Exception err) {
        return wrapException(err);
    } finally {
        CloserUtil.close(iter);
        CloserUtil.close(sfr);
        CloserUtil.close(sfw);
    }
}

From source file:cz.opendata.unifiedviews.dpus.ckan.CKANBatchLoader.java

@Override
protected void innerExecute() throws DPUException {
    logger.debug("Querying metadata for datasets");

    LinkedList<String> datasets = new LinkedList<String>();
    for (Map<String, Value> map : executeSelectQuery(
            "SELECT ?d WHERE {?d a <" + CKANLoaderVocabulary.DCAT_DATASET_CLASS + ">}")) {
        datasets.add(map.get("d").stringValue());
    }/*w  w w. j  a v a2  s . c  om*/

    int current = 0;
    int total = datasets.size();

    JSONArray outArray = new JSONArray();

    ContextUtils.sendShortInfo(ctx, "Found {0} datasets", total);

    for (String datasetURI : datasets) {
        current++;
        ContextUtils.sendShortInfo(ctx, "Querying metadata for dataset {0}/{1}: {2}", current, total,
                datasetURI);

        String datasetID = executeSimpleSelectQuery("SELECT ?did WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.LODCZCKAN_DATASET_ID + "> ?did }", "did");
        if (datasetID.isEmpty()) {
            ContextUtils.sendWarn(ctx, "Dataset has missing CKAN ID", "Dataset {0} has missing CKAN ID",
                    datasetURI);
            continue;
        }

        String orgID = executeSimpleSelectQuery("SELECT ?orgid WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.LODCZCKAN_ORG_ID + "> ?orgid }", "orgid");
        String apiURI = config.getApiUri();

        String title = executeSimpleSelectQuery("SELECT ?title WHERE {<" + datasetURI + "> <" + DCTERMS.TITLE
                + "> ?title FILTER(LANGMATCHES(LANG(?title), \"cs\"))}", "title");
        String description = executeSimpleSelectQuery("SELECT ?description WHERE {<" + datasetURI + "> <"
                + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \"cs\"))}",
                "description");
        String periodicity = executeSimpleSelectQuery("SELECT ?periodicity WHERE {<" + datasetURI + "> <"
                + DCTERMS.ACCRUAL_PERIODICITY + "> ?periodicity }", "periodicity");
        String temporalStart = executeSimpleSelectQuery("SELECT ?temporalStart WHERE {<" + datasetURI + "> <"
                + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }",
                "temporalStart");
        String temporalEnd = executeSimpleSelectQuery("SELECT ?temporalEnd WHERE {<" + datasetURI + "> <"
                + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }",
                "temporalEnd");
        String spatial = executeSimpleSelectQuery(
                "SELECT ?spatial WHERE {<" + datasetURI + "> <" + DCTERMS.SPATIAL + "> ?spatial }", "spatial");
        String schemaURL = executeSimpleSelectQuery(
                "SELECT ?schema WHERE {<" + datasetURI + "> <" + DCTERMS.REFERENCES + "> ?schema }", "schema");
        String contactPoint = executeSimpleSelectQuery(
                "SELECT ?contact WHERE {<" + datasetURI + "> <" + CKANLoaderVocabulary.ADMS_CONTACT_POINT
                        + ">/<" + CKANLoaderVocabulary.VCARD_HAS_EMAIL + "> ?contact }",
                "contact");
        String issued = executeSimpleSelectQuery(
                "SELECT ?issued WHERE {<" + datasetURI + "> <" + DCTERMS.ISSUED + "> ?issued }", "issued");
        String modified = executeSimpleSelectQuery(
                "SELECT ?modified WHERE {<" + datasetURI + "> <" + DCTERMS.MODIFIED + "> ?modified }",
                "modified");
        String license = executeSimpleSelectQuery(
                "SELECT ?license WHERE {<" + datasetURI + "> <" + DCTERMS.LICENSE + "> ?license }", "license");
        String author = executeSimpleSelectQuery("SELECT ?author WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.LODCZCKAN_AUTHOR + "> ?author }", "author");
        String maintainer = executeSimpleSelectQuery(
                "SELECT ?maintainer WHERE {<" + datasetURI + "> <" + DCTERMS.PUBLISHER + "> ?maintainer }",
                "maintainer");

        LinkedList<String> themes = new LinkedList<String>();
        for (Map<String, Value> map : executeSelectQuery("SELECT ?theme WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.DCAT_THEME + "> ?theme }")) {
            themes.add(map.get("theme").stringValue());
        }

        LinkedList<String> keywords = new LinkedList<String>();
        for (Map<String, Value> map : executeSelectQuery("SELECT ?keyword WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.DCAT_KEYWORD + "> ?keyword }")) {
            keywords.add(map.get("keyword").stringValue());
        }

        LinkedList<String> distributions = new LinkedList<String>();
        for (Map<String, Value> map : executeSelectQuery("SELECT ?distribution WHERE {<" + datasetURI + "> <"
                + CKANLoaderVocabulary.DCAT_DISTRIBUTION + "> ?distribution }")) {
            distributions.add(map.get("distribution").stringValue());
        }

        boolean exists = false;
        Map<String, String> resUrlIdMap = new HashMap<String, String>();
        Map<String, String> resDistroIdMap = new HashMap<String, String>();

        logger.debug("Querying for the dataset in CKAN");
        CloseableHttpClient queryClient = HttpClientBuilder.create()
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpGet httpGet = new HttpGet(apiURI + "/" + datasetID);
        CloseableHttpResponse queryResponse = null;
        try {
            queryResponse = queryClient.execute(httpGet);
            if (queryResponse.getStatusLine().getStatusCode() == 200) {
                logger.info("Dataset found");
                exists = true;

                JSONObject response = new JSONObject(EntityUtils.toString(queryResponse.getEntity()));
                JSONArray resourcesArray = response.getJSONArray("resources");
                for (int i = 0; i < resourcesArray.length(); i++) {
                    try {
                        String id = resourcesArray.getJSONObject(i).getString("id");
                        String url = resourcesArray.getJSONObject(i).getString("url");
                        resUrlIdMap.put(url, id);

                        if (resourcesArray.getJSONObject(i).has("distro_url")) {
                            String distro = resourcesArray.getJSONObject(i).getString("distro_url");
                            resDistroIdMap.put(distro, id);
                        }
                    } catch (JSONException e) {
                        logger.error(e.getLocalizedMessage(), e);
                    }
                }

            } else {
                String ent = EntityUtils.toString(queryResponse.getEntity());
                logger.info("Dataset not found: " + ent);
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getLocalizedMessage(), e);
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage(), e);
        } catch (ParseException e) {
            logger.error(e.getLocalizedMessage(), e);
        } catch (JSONException e) {
            logger.error(e.getLocalizedMessage(), e);
        } finally {
            if (queryResponse != null) {
                try {
                    queryResponse.close();
                    queryClient.close();
                } catch (IOException e) {
                    logger.error(e.getLocalizedMessage(), e);
                }
            }
        }

        logger.debug("Creating JSON");
        try {
            JSONObject root = new JSONObject();

            JSONArray tags = new JSONArray();
            //tags.put(keywords);
            for (String keyword : keywords)
                tags.put(keyword);

            JSONArray resources = new JSONArray();

            //JSONObject extras = new JSONObject();

            if (!datasetID.isEmpty())
                root.put("name", datasetID);
            root.put("url", datasetURI);
            root.put("title", title);
            root.put("notes", description);
            root.put("maintainer", maintainer);
            root.put("author", author);
            root.put("author_email", contactPoint);
            root.put("metadata_created", issued);
            root.put("metadata_modified", modified);

            //TODO: Matching?
            root.put("license_id", "other-open");
            root.put("license_link", license);
            root.put("temporalStart", temporalStart);
            root.put("temporalEnd", temporalEnd);
            root.put("accrualPeriodicity", periodicity);
            root.put("schema", schemaURL);
            root.put("spatial", spatial);

            String concatThemes = "";
            for (String theme : themes) {
                concatThemes += theme + " ";
            }
            root.put("themes", concatThemes);

            //Distributions
            for (String distribution : distributions) {
                JSONObject distro = new JSONObject();

                String dtitle = executeSimpleSelectQuery("SELECT ?title WHERE {<" + distribution + "> <"
                        + DCTERMS.TITLE + "> ?title FILTER(LANGMATCHES(LANG(?title), \"cs\"))}", "title");
                String ddescription = executeSimpleSelectQuery(
                        "SELECT ?description WHERE {<" + distribution + "> <" + DCTERMS.DESCRIPTION
                                + "> ?description FILTER(LANGMATCHES(LANG(?description), \"cs\"))}",
                        "description");
                String dtemporalStart = executeSimpleSelectQuery(
                        "SELECT ?temporalStart WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<"
                                + CKANLoaderVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }",
                        "temporalStart");
                String dtemporalEnd = executeSimpleSelectQuery(
                        "SELECT ?temporalEnd WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<"
                                + CKANLoaderVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }",
                        "temporalEnd");
                String dspatial = executeSimpleSelectQuery(
                        "SELECT ?spatial WHERE {<" + distribution + "> <" + DCTERMS.SPATIAL + "> ?spatial }",
                        "spatial");
                String dschemaURL = executeSimpleSelectQuery("SELECT ?schema WHERE {<" + distribution + "> <"
                        + CKANLoaderVocabulary.WDRS_DESCRIBEDBY + "> ?schema }", "schema");
                String dschemaType = executeSimpleSelectQuery(
                        "SELECT ?schema WHERE {<" + distribution + "> <"
                                + CKANLoaderVocabulary.POD_DISTRIBUTION_DESCRIBREBYTYPE + "> ?schema }",
                        "schema");
                String dissued = executeSimpleSelectQuery(
                        "SELECT ?issued WHERE {<" + distribution + "> <" + DCTERMS.ISSUED + "> ?issued }",
                        "issued");
                String dmodified = executeSimpleSelectQuery(
                        "SELECT ?modified WHERE {<" + distribution + "> <" + DCTERMS.MODIFIED + "> ?modified }",
                        "modified");
                String dlicense = executeSimpleSelectQuery(
                        "SELECT ?license WHERE {<" + distribution + "> <" + DCTERMS.LICENSE + "> ?license }",
                        "license");
                String dformat = executeSimpleSelectQuery(
                        "SELECT ?format WHERE {<" + distribution + "> <" + DCTERMS.FORMAT + "> ?format }",
                        "format");
                String dwnld = executeSimpleSelectQuery("SELECT ?dwnld WHERE {<" + distribution + "> <"
                        + CKANLoaderVocabulary.DCAT_DOWNLOADURL + "> ?dwnld }", "dwnld");

                // RDF SPECIFIC - VOID
                String sparqlEndpoint = executeSimpleSelectQuery(
                        "SELECT ?sparqlEndpoint WHERE {<" + distribution + "> <"
                                + CKANLoaderVocabulary.VOID_SPARQLENDPOINT + "> ?sparqlEndpoint }",
                        "sparqlEndpoint");

                LinkedList<String> examples = new LinkedList<String>();
                for (Map<String, Value> map : executeSelectQuery(
                        "SELECT ?exampleResource WHERE {<" + distribution + "> <"
                                + CKANLoaderVocabulary.VOID_EXAMPLERESOURCE + "> ?exampleResource }")) {
                    examples.add(map.get("exampleResource").stringValue());
                }

                if (!sparqlEndpoint.isEmpty()) {
                    //Start of Sparql Endpoint resource
                    JSONObject sparqlEndpointJSON = new JSONObject();

                    sparqlEndpointJSON.put("name", "SPARQL Endpoint");
                    sparqlEndpointJSON.put("url", sparqlEndpoint);
                    sparqlEndpointJSON.put("format", "api/sparql");
                    sparqlEndpointJSON.put("resource_type", "api");

                    if (resUrlIdMap.containsKey(sparqlEndpoint))
                        sparqlEndpointJSON.put("id", resUrlIdMap.get(sparqlEndpoint));

                    resources.put(sparqlEndpointJSON);
                    // End of Sparql Endpoint resource

                }

                for (String example : examples) {
                    // Start of Example resource text/turtle
                    JSONObject exTurtle = new JSONObject();

                    exTurtle.put("format", "example/turtle");
                    exTurtle.put("resource_type", "file");
                    //exTurtle.put("description","Generated by Virtuoso FCT");
                    exTurtle.put("name", "Example resource in Turtle");

                    String exUrl;

                    try {
                        if (sparqlEndpoint.isEmpty())
                            exUrl = example;
                        else
                            exUrl = sparqlEndpoint + "?query="
                                    + URLEncoder.encode("DESCRIBE <" + example + ">", "UTF-8") + "&output="
                                    + URLEncoder.encode("text/turtle", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        exUrl = "";
                        logger.error(e.getLocalizedMessage(), e);
                    }
                    exTurtle.put("url", exUrl);

                    if (resUrlIdMap.containsKey(exUrl))
                        exTurtle.put("id", resUrlIdMap.get(exUrl));

                    resources.put(exTurtle);
                    // End of text/turtle resource

                    // Start of Example resource html
                    JSONObject exHTML = new JSONObject();

                    exHTML.put("format", "HTML");
                    exHTML.put("resource_type", "file");
                    //exHTML.put("description","Generated by Virtuoso FCT");
                    exHTML.put("name", "Example resource");
                    exHTML.put("url", example);

                    if (resUrlIdMap.containsKey(example))
                        exHTML.put("id", resUrlIdMap.get(example));

                    resources.put(exHTML);
                    // End of html resource

                }

                // END OF RDF VOID SPECIFICS

                distro.put("name", dtitle);
                distro.put("description", ddescription);
                distro.put("license_link", dlicense);
                distro.put("temporalStart", dtemporalStart);
                distro.put("temporalEnd", dtemporalEnd);
                distro.put("describedBy", dschemaURL);
                distro.put("describedByType", dschemaType);
                distro.put("format", dformat);
                distro.put("url", dwnld);
                distro.put("distro_url", distribution);

                if (resDistroIdMap.containsKey(distribution))
                    distro.put("id", resDistroIdMap.get(distribution));
                else if (resUrlIdMap.containsKey(dwnld))
                    distro.put("id", resUrlIdMap.get(dwnld));

                distro.put("created", dissued);
                distro.put("last_modified", dmodified);

                distro.put("spatial", dspatial);

                resources.put(distro);
            }

            root.put("tags", tags);
            root.put("resources", resources);
            //root.put("extras", extras);

            if (!exists && config.isLoadToCKAN()) {
                JSONObject createRoot = new JSONObject();

                createRoot.put("name", datasetID);
                createRoot.put("title", title);
                if (!orgID.isEmpty())
                    createRoot.put("owner_org", orgID);

                logger.debug("Creating dataset in CKAN");
                CloseableHttpClient client = HttpClientBuilder.create()
                        .setRedirectStrategy(new LaxRedirectStrategy()).build();
                HttpPost httpPost = new HttpPost(apiURI);
                httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey()));

                String json = createRoot.toString();

                logger.debug("Creating dataset with: " + json);

                httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

                CloseableHttpResponse response = null;

                try {
                    response = client.execute(httpPost);
                    if (response.getStatusLine().getStatusCode() == 201) {
                        logger.info("Dataset created OK");
                        logger.info("Response: " + EntityUtils.toString(response.getEntity()));
                    } else if (response.getStatusLine().getStatusCode() == 409) {
                        String ent = EntityUtils.toString(response.getEntity());
                        logger.error("Dataset already exists: " + ent);
                        ContextUtils.sendError(ctx, "Dataset already exists",
                                "Dataset already exists: {0}: {1}", response.getStatusLine().getStatusCode(),
                                ent);
                    } else {
                        String ent = EntityUtils.toString(response.getEntity());
                        logger.error("Response:" + ent);
                        ContextUtils.sendError(ctx, "Error creating dataset",
                                "Response while creating dataset: {0}: {1}",
                                response.getStatusLine().getStatusCode(), ent);
                    }
                } catch (ClientProtocolException e) {
                    logger.error(e.getLocalizedMessage(), e);
                } catch (IOException e) {
                    logger.error(e.getLocalizedMessage(), e);
                } finally {
                    if (response != null) {
                        try {
                            response.close();
                            client.close();
                        } catch (IOException e) {
                            logger.error(e.getLocalizedMessage(), e);
                            ContextUtils.sendError(ctx, "Error creating dataset", e.getLocalizedMessage());
                        }
                    }
                }
            }

            outArray.put(root);

            if (!ctx.canceled() && config.isLoadToCKAN()) {
                logger.debug("Posting to CKAN");
                CloseableHttpClient client = HttpClients.createDefault();
                URIBuilder uriBuilder = new URIBuilder(apiURI + "/" + datasetID);
                HttpPost httpPost = new HttpPost(uriBuilder.build().normalize());
                httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey()));

                String json = root.toString();
                logger.trace(json);

                httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

                CloseableHttpResponse response = null;

                try {
                    response = client.execute(httpPost);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        logger.info("Response:" + EntityUtils.toString(response.getEntity()));
                    } else {
                        String ent = EntityUtils.toString(response.getEntity());
                        logger.error("Response:" + ent);
                        ContextUtils.sendError(ctx, "Error updating dataset",
                                "Response while updating dataset: {0}: {1}",
                                response.getStatusLine().getStatusCode(), ent);
                    }
                } catch (ClientProtocolException e) {
                    logger.error(e.getLocalizedMessage(), e);
                } catch (IOException e) {
                    logger.error(e.getLocalizedMessage(), e);
                } finally {
                    if (response != null) {
                        try {
                            response.close();
                            client.close();
                        } catch (IOException e) {
                            logger.error(e.getLocalizedMessage(), e);
                            ContextUtils.sendError(ctx, "Error updating dataset", e.getLocalizedMessage());
                        }
                    }
                }
            }
        } catch (JSONException e) {
            logger.error(e.getLocalizedMessage(), e);
        } catch (URISyntaxException e) {
            logger.error(e.getLocalizedMessage(), e);
        }

        if (ctx.canceled())
            break;
    }

    File outfile = outFileSimple.create(config.getFilename());
    try {
        FileUtils.writeStringToFile(outfile, outArray.toString());
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
    }

}

From source file:edu.cmu.tetrad.search.SearchGraphUtils.java

public static Graph bestGuessCycleOrientation(Graph graph, IndependenceTest test) {
    while (true) {
        List<Node> cycle = GraphUtils.directedCycle(graph);

        if (cycle == null) {
            break;
        }//from w  w w .  j  a va2s. c  om

        LinkedList<Node> _cycle = new LinkedList<Node>(cycle);

        Node first = _cycle.getFirst();
        Node last = _cycle.getLast();

        _cycle.addFirst(last);
        _cycle.addLast(first);

        int _j = -1;
        double minP = Double.POSITIVE_INFINITY;

        for (int j = 1; j < _cycle.size() - 1; j++) {
            int i = j - 1;
            int k = j + 1;

            Node x = test.getVariable(_cycle.get(i).getName());
            Node y = test.getVariable(_cycle.get(j).getName());
            Node z = test.getVariable(_cycle.get(k).getName());

            test.isIndependent(x, z, Collections.singletonList(y));

            double p = test.getPValue();

            if (p < minP) {
                _j = j;
                minP = p;
            }
        }

        Node x = _cycle.get(_j - 1);
        Node y = _cycle.get(_j);
        Node z = _cycle.get(_j + 1);

        graph.removeEdge(x, y);
        graph.removeEdge(z, y);
        graph.addDirectedEdge(x, y);
        graph.addDirectedEdge(z, y);
    }

    return graph;
}

From source file:edu.csun.ecs.cs.multitouchj.ui.graphic.WindowManager.java

private void dispatchObjectEventControls(ObjectEvent objectEvent) {
    List<Control> cursors = null;
    synchronized (cursorHandler) {
        cursors = cursorHandler.getCursors();
    }/*from   w w  w . j  a  va 2  s.  c o  m*/

    Control activeControl = null;
    LinkedList<ObjectObserverEvent> consumedOoes = new LinkedList<ObjectObserverEvent>();
    ListIterator<Control> listIterator = controls.listIterator(controls.size());
    while (listIterator.hasPrevious()) {
        Control control = listIterator.previous();
        if ((!control.isVisible()) || (cursors.contains(control))) {
            continue;
        }

        ObjectEvent copiedObjectEvent = objectEvent.copy();
        // check how many of Ooes are within this control
        LinkedList<ObjectObserverEvent> ooes = new LinkedList<ObjectObserverEvent>();
        for (ObjectObserverEvent ooe : objectEvent.getObjectObserverEvents()) {
            if (!consumedOoes.contains(ooe)) {
                if (control.isWithin(new Point(ooe.getX(), ooe.getY()))) {
                    ooes.add(ooe);
                    consumedOoes.add(ooe);
                }
            }
        }
        copiedObjectEvent.setObjectObserverEvents(ooes);

        ObjectObserverEvent targetOoe = objectEvent.getTargetObjectObserverEvent();
        if (ooes.contains(targetOoe)) {
            activeControl = control;
        } else {
            targetOoe = null;
        }
        copiedObjectEvent.setTargetObjectObserverEvent(targetOoe);

        //log.debug("Ooes: "+ooes.size());
        if (ooes.size() > 0) {
            log.debug(control.getClass().toString() + "[" + control.getPosition().toString() + "]"
                    + ": Sending " + ooes.size() + " ooes");
            control.dispatchEvent(copiedObjectEvent);
        }
    }

    if ((activeControl != null) && (!activeControl.equals(backgroundControl))) {
        if (!activeControl.equals(controls.getLast())) {
            controls.remove(activeControl);
            controls.add(activeControl);
        }
    }
}

From source file:edu.csun.ecs.cs.multitouchj.application.whiteboard.Whiteboard.java

private void loadImages() throws Exception {
    interactiveCanvas = new InteractiveCanvas();
    WindowManager.getInstance().setBackgroundControl(interactiveCanvas);
    interactiveCanvas.setSize(new Size(displayMode.getWidth(), displayMode.getHeight()));
    interactiveCanvas.setTopLeftPosition(new Point(0.0f, 0.0f));
    clearCanvas();/*  www  .  j a v  a 2  s  . c o  m*/

    // pens
    updatePens(new BasicStroke(5.0f), Color.BLACK);

    // color buttons
    int totalButtonsWidth = 0;
    LinkedList<TexturedControl> buttons = new LinkedList<TexturedControl>();
    for (Object[] button : COLOR_BUTTONS) {
        final Stroke stroke = (Stroke) button[1];
        final Color color = (Color) button[2];

        TexturedControl texturedControl = new TexturedControl();
        texturedControl.setTexture(getClass().getResource((String) button[0]));
        texturedControl.addTouchListener(new TouchListener() {
            public void touchEnded(TouchEvent touchEvent) {
            }

            public void touchMoved(TouchEvent touchEvent) {
            }

            public void touchStarted(TouchEvent touchEvent) {
                updatePens(stroke, color);
            }
        });
        buttons.add(texturedControl);

        totalButtonsWidth += texturedControl.getSize().getWidth();
    }

    int numberOfPaddings = COLOR_BUTTONS.length + 1;
    int padding = (int) Math.floor(((displayMode.getWidth() - totalButtonsWidth) / (double) numberOfPaddings));
    for (int i = 0; i < buttons.size(); i++) {
        TexturedControl texturedControl = buttons.get(i);
        texturedControl.setTopLeftPosition(
                new Point((((i + 1) * padding) + (i * texturedControl.getSize().getWidth())), 15));
    }

    // clear button
    TexturedControl clearButton = new TexturedControl();
    clearButton.setTexture(getClass().getResource(CLEAR_BUTTON));
    clearButton.addTouchListener(new TouchListener() {
        public void touchEnded(TouchEvent touchEvent) {
        }

        public void touchMoved(TouchEvent touchEvent) {
        }

        public void touchStarted(TouchEvent touchEvent) {
            clearCanvas();
        }
    });
    clearButton.setTopLeftPosition(new Point((displayMode.getWidth() - 10 - clearButton.getSize().getWidth()),
            (displayMode.getHeight() - 10 - clearButton.getSize().getHeight())));
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

/**
 *  get all the keys of the new items since a specified time.
 * @return/*w  ww.j a v a 2s  .co m*/
 */
public String getNewSyncItemKeys() throws OperationFailureException {
    if (log.isInfoEnabled()) {
        log.info("Executing method: getNewSyncItemKeys() from:" + configLoader.getServerTimeStr(lastSyncTime)
                + " to  :" + configLoader.getServerTimeStr(beginSyncTime));
    }
    try {
        String req = configLoader.getServerProperty(Def.SERVER_URI) + "/" + getSourceName() + "/keys/new";

        String response = sendGetRequest(req, configLoader.getServerTime(lastSyncTime),
                configLoader.getServerTime(beginSyncTime));

        if (log.isTraceEnabled()) {
            log.trace("RESPONSE getNewSyncItemKeys: \n" + response);
        }
        JSONArray arrayOfKeys = JSONObject.fromObject(response).getJSONObject("data").getJSONArray("keys");

        LinkedList<String> items = configLoader.getNewItems(sourceName, testName);
        if (expectItemsFromServer) {
            if (items.size() != arrayOfKeys.size()) {
                log.error("------------- ERROR [" + sourceName + ":" + testName + "]");
                log.error("ERROR Expected :" + items.size() + " found " + arrayOfKeys.size());
                log.error("ERROR Expected :" + items);
                log.error("ERROR Found    :" + arrayOfKeys);
            }
        } else {
            if (arrayOfKeys.size() != 0) {
                log.error("------------- ERROR [" + sourceName + ":" + testName + "]");
                log.error("ERROR : the syncType specified does not expect any keys returned");
            }
        }

        return response;
    } catch (IOOperationException ex) {
        throw new OperationFailureException("Error retrieving new items ", ex);
    }
}