Example usage for java.util LinkedList get

List of usage examples for java.util LinkedList get

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:org.apache.flink.streaming.connectors.kinesis.internals.KinesisDataFetcherTest.java

@Test
public void testSkipCorruptedRecord() throws Exception {
    final String stream = "fakeStream";
    final int numShards = 3;

    final LinkedList<KinesisStreamShardState> testShardStates = new LinkedList<>();
    final TestSourceContext<String> sourceContext = new TestSourceContext<>();

    final TestableKinesisDataFetcher<String> fetcher = new TestableKinesisDataFetcher<>(
            Collections.singletonList(stream), sourceContext, TestUtils.getStandardProperties(),
            new KinesisDeserializationSchemaWrapper<>(new SimpleStringSchema()), 1, 0, new AtomicReference<>(),
            testShardStates, new HashMap<>(), FakeKinesisBehavioursFactory
                    .nonReshardedStreamsBehaviour(Collections.singletonMap(stream, numShards)));

    // FlinkKinesisConsumer is responsible for setting up the fetcher before it can be run;
    // run the consumer until it reaches the point where the fetcher starts to run
    final DummyFlinkKinesisConsumer<String> consumer = new DummyFlinkKinesisConsumer<>(
            TestUtils.getStandardProperties(), fetcher, 1, 0);

    CheckedThread consumerThread = new CheckedThread() {
        @Override/*from  www.  ja  va2 s.co  m*/
        public void go() throws Exception {
            consumer.run(new TestSourceContext<>());
        }
    };
    consumerThread.start();

    fetcher.waitUntilRun();
    consumer.cancel();
    consumerThread.sync();

    assertEquals(numShards, testShardStates.size());

    for (int i = 0; i < numShards; i++) {
        fetcher.emitRecordAndUpdateState("record-" + i, 10L, i, new SequenceNumber("seq-num-1"));
        assertEquals(new SequenceNumber("seq-num-1"), testShardStates.get(i).getLastProcessedSequenceNum());
        assertEquals(new StreamRecord<>("record-" + i, 10L), sourceContext.removeLatestOutput());
    }

    // emitting a null (i.e., a corrupt record) should not produce any output, but still have the shard state updated
    fetcher.emitRecordAndUpdateState(null, 10L, 1, new SequenceNumber("seq-num-2"));
    assertEquals(new SequenceNumber("seq-num-2"), testShardStates.get(1).getLastProcessedSequenceNum());
    assertEquals(null, sourceContext.removeLatestOutput()); // no output should have been collected
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Minifies a CSS string by removing comments and excess white-space, as well as 
 * some unneeded tokens./*from  w w w  .ja va2  s .c  o  m*/
 * 
 * @param css The contents of a CSS file as a String
 * @param uri The URI for the CSS file
 * @return
 */
protected String minify(String css, IResource res) {

    // replace all quoted strings and url(...) patterns with unique ids so that 
    // they won't be affected by whitespace removal.
    LinkedList<String> quotedStringReplacements = new LinkedList<String>();
    Matcher m = quotedStringPattern.matcher(css);
    StringBuffer sb = new StringBuffer();
    int i = 0;
    while (m.find()) {
        String text = (m.group(1) != null) ? ("url(" + StringUtils.trim(m.group(1)) + ")") : //$NON-NLS-1$ //$NON-NLS-2$
                m.group(0);
        quotedStringReplacements.add(i, text);
        String replacement = "%%" + QUOTED_STRING_MARKER + (i++) + "__%%"; //$NON-NLS-1$ //$NON-NLS-2$
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(replacement);
    }
    m.appendTail(sb);
    css = sb.toString();

    // Get rid of extra whitespace
    css = whitespacePattern.matcher(css).replaceAll(" "); //$NON-NLS-1$
    css = endsPattern.matcher(css).replaceAll(""); //$NON-NLS-1$
    css = closeBracePattern.matcher(css).replaceAll("}"); //$NON-NLS-1$
    m = delimitersPattern.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        String text = m.group(1);
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(text.length() == 1 ? text : text.replace(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    m.appendTail(sb);
    css = sb.toString();

    // restore quoted strings and url(...) patterns
    m = QUOTED_STRING_MARKER_PAT.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        i = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(quotedStringReplacements.get(i));
    }
    m.appendTail(sb);
    css = sb.toString();

    return css.toString();
}

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

/**
 * /* w w w  . ja v a2s .c o m*/
 * @param dirname
 * @return
 * @throws IOException
 * @throws DMLUnsupportedOperationException
 */
@SuppressWarnings("all")
private static HashMap<Integer, Long> writeResults(String dirname)
        throws IOException, DMLUnsupportedOperationException {
    HashMap<Integer, Long> map = new HashMap<Integer, Long>();
    int count = 1;
    int offset = (MODEL_INTERCEPT ? 1 : 0);
    int cols = MODEL_MAX_ORDER + offset;

    for (Entry<Integer, HashMap<Integer, LinkedList<Double>>> inst : _results.entrySet()) {
        int instID = inst.getKey();
        HashMap<Integer, LinkedList<Double>> instCF = inst.getValue();

        for (Entry<Integer, LinkedList<Double>> cfun : instCF.entrySet()) {
            int tDefID = cfun.getKey();
            long ID = IDHandler.concatIntIDsToLong(instID, tDefID);
            LinkedList<Double> dmeasure = cfun.getValue();

            PerfTestDef def = _regTestDef.get(tDefID);
            LinkedList<Double> dvariable = generateSequence(def.getMin(), def.getMax(), NUM_SAMPLES_PER_TEST);
            int dlen = dvariable.size();
            int plen = def.getInternalVariables().length;

            //write variable data set
            CSVWriter writer1 = new CSVWriter(new FileWriter(dirname + count + "_in1.csv"), ',',
                    CSVWriter.NO_QUOTE_CHARACTER);
            if (plen == 1) //one dimensional function
            {
                //write 1, x, x^2, x^3, ...
                String[] sbuff = new String[cols];
                for (Double val : dvariable) {
                    for (int j = 0; j < cols; j++)
                        sbuff[j] = String.valueOf(Math.pow(val, j + 1 - offset));
                    writer1.writeNext(sbuff);
                }
            } else // multi-dimensional function
            {
                //write 1, x,y,z,x^2,y^2,z^2, xy, xz, yz, xyz

                String[] sbuff = new String[(int) Math.pow(2, plen) - 1 + plen + offset - 1];
                //String[] sbuff = new String[plen+offset];
                if (offset == 1)
                    sbuff[0] = "1";

                //init index stack
                int[] index = new int[plen];
                for (int i = 0; i < plen; i++)
                    index[i] = 0;

                //execute test 
                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 writing
                    for (int i = 1; i <= plen; i++) {
                        if (i == 1) {
                            for (int j = 0; j < plen; j++)
                                sbuff[offset + j] = String.valueOf(buff[j]);
                            for (int j = 0; j < plen; j++)
                                sbuff[offset + plen + j] = String.valueOf(Math.pow(buff[j], 2));
                        } else if (i == 2) {
                            int ix = 0;
                            for (int j = 0; j < plen - 1; j++)
                                for (int k = j + 1; k < plen; k++, ix++)
                                    sbuff[offset + 2 * plen + ix] = String.valueOf(buff[j] * buff[k]);
                        } else if (i == plen) {
                            //double tmp=1;
                            //for( int j=0; j<plen; j++ )
                            //   tmp *= buff[j];
                            //sbuff[offset+2*plen+plen*(plen-1)/2] = String.valueOf(tmp);
                        } else
                            throw new DMLUnsupportedOperationException(
                                    "More than 3 dims currently not supported.");

                    }

                    //for( int i=0; i<plen; i++ )   
                    //   sbuff[offset+i] = String.valueOf( buff[i] );

                    writer1.writeNext(sbuff);

                    //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;
                        }
                    }
                }
            }
            writer1.close();

            //write measure data set
            CSVWriter writer2 = new CSVWriter(new FileWriter(dirname + count + "_in2.csv"), ',',
                    CSVWriter.NO_QUOTE_CHARACTER);
            String[] buff2 = new String[1];
            for (Double val : dmeasure) {
                buff2[0] = String.valueOf(val);
                writer2.writeNext(buff2);
            }
            writer2.close();

            map.put(count, ID);
            count++;
        }
    }

    return map;
}

From source file:util.method.java

public static AbstractOrbacPolicy generateOrBACPolicyFromVMandHostPolicy(LinkedList VMPolicyList,
        LinkedList<VM> VMList, LinkedList HOSTPolicyList, LinkedList<HOST> HOSTList) throws COrbacException {

    COrbacCore core = COrbacCore.GetTheInstance();
    // create new policy using the Jena implementation
    AbstractOrbacPolicy p = core.CreatePolicy("policy1", XmlOrbacPolicy.class);

    // add some abstract entities to the policy
    // add an organization
    p.CreateOrganization("superCloud");
    String currentOrganization = "superCloud";
    String currentActivity = "myActivity";
    String currentContext = "default_context";

    p.CreateActivityAndInsertIntoOrg(currentActivity, "superCloud");

    p.Consider("superCloud", "deploy", currentActivity);
    p.AddAction("deploy");

    LinkedList<String> VMIDMemoryList = new LinkedList<String>();
    LinkedList<String> HOSTIDMemoryList = new LinkedList<String>();

    /*Generate OrBAC policy from VM List */

    for (int i = 0; i < VMPolicyList.size(); i++) {
        String currentRole = "Role_Permission_" + i;
        String currentView = "View_Permission_" + i;
        String currentRuleID = "Permission_" + i;

        p.CreateRoleAndInsertIntoOrg(currentRole, currentOrganization);
        p.CreateViewAndInsertIntoOrg(currentView, currentOrganization);
        //System.out.println("---------------currentRuleID"+currentRuleID);

        p.AbstractPermission("superCloud", currentRole, currentActivity, currentView, currentContext,
                currentRuleID);/*ww  w  . ja  v a 2  s .c  om*/
        ArrayList currentVMRule = (ArrayList) VMPolicyList.get(i);

        String policyType = (String) currentVMRule.get(0);
        HashMap HOSTProperty = (HashMap) currentVMRule.get(1);
        HashMap VMProperty = (HashMap) currentVMRule.get(2);

        if (policyType.equals("permission")) {
            LinkedList<String> VMIDList = findRelatedVMID(VMProperty, VMList);

            LinkedList<String> HOSTIDList = findRelatedHOSTID(HOSTProperty, HOSTList);

            if ((VMIDList.size() == 0) || (HOSTIDList.size() == 0))
                return null;

            //p.AbstractPermission ("superCloud",currentRole,currentActivity,currentView,currentContext,currentRuleID);
            for (int j = 0; j < VMIDList.size(); j++) {

                //System.out.print("----------- hahaha This is J"+j);
                //System.out.print("----------- HOSTLIST size"+HOSTList.size());
                for (int k = 0; k < HOSTIDList.size(); k++) {

                    // System.out.print("----------- hahaha This is K"+k);
                    String currentVMID = VMIDList.get(j);
                    String currentHOSTID = HOSTIDList.get(k);
                    //System.out.println("---------------currentHOSTID"+currentHOSTID);
                    //System.out.println("\n---------------currentVMID"+currentVMID);

                    if (!HOSTIDMemoryList.contains(currentHOSTID)) {
                        p.AddSubject(currentHOSTID);
                        HOSTIDMemoryList.add(currentHOSTID);

                    }

                    if (!VMIDMemoryList.contains(currentVMID)) {
                        p.AddObject(currentVMID);
                        VMIDMemoryList.add(currentVMID);

                    }

                    p.Empower(currentOrganization, currentHOSTID, currentRole);
                    p.Use(currentOrganization, currentVMID, currentView);
                }
            }

        }
    }
    /*Generate OrBAC policy from HOST List */

    for (int j1 = 0; j1 < HOSTPolicyList.size(); j1++) {

        String currentRole = "Role_Prohibition_" + j1;
        String currentView = "View_Prohibition_" + j1;
        String currentRuleID = "Prohibition_" + j1;

        p.CreateRoleAndInsertIntoOrg(currentRole, currentOrganization);
        p.CreateViewAndInsertIntoOrg(currentView, currentOrganization);

        p.AbstractProhibition(currentOrganization, currentRole, currentActivity, currentView, currentContext,
                currentRuleID);
        ArrayList currentHOSTRule = (ArrayList) HOSTPolicyList.get(j1);

        String policyType = (String) currentHOSTRule.get(0);
        HashMap HOSTProperty = (HashMap) currentHOSTRule.get(1);
        HashMap VMProperty = (HashMap) currentHOSTRule.get(2);

        if (policyType.equals("prohibition")) {
            LinkedList<String> VMIDList = findRelatedVMID(VMProperty, VMList);

            LinkedList<String> HOSTIDList = findRelatedHOSTID(HOSTProperty, HOSTList);

            // p.AbstractProhibition ("superCloud",currentRole,currentActivity,currentView,currentContext,currentRuleID);
            for (int j2 = 0; j2 < VMIDList.size(); j2++)
                for (int k2 = 0; k2 < HOSTIDList.size(); k2++) {
                    String currentHOSTID = HOSTIDList.get(k2);
                    String currentVMID = VMIDList.get(j2);

                    if (!HOSTIDMemoryList.contains(currentHOSTID)) {
                        p.AddSubject(currentHOSTID);
                        HOSTIDMemoryList.add(currentHOSTID);

                    }

                    if (!VMIDMemoryList.contains(currentVMID)) {
                        p.AddSubject(currentVMID);
                        VMIDMemoryList.add(currentVMID);

                    }

                    p.Empower(currentOrganization, currentHOSTID, currentRole);
                    p.Use(currentOrganization, currentVMID, currentView);
                }

        }

    }

    return p;
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRJobRequest.java

public List<List<String>> getValueRange(String tkn) {

    dbgLog.fine("received token=" + tkn);
    String step0 = StringUtils.strip(tkn);
    dbgLog.fine("step0=" + step0);

    // string into tokens
    String[] step1raw = step0.split(",");

    dbgLog.fine("step1raw=" + StringUtils.join(step1raw, ","));

    // remove meaningless commas if exist

    List<String> step1 = new ArrayList<String>();

    for (String el : step1raw) {
        if (!el.equals("")) {
            step1.add(el);/*from   w ww.  java 2s  . com*/
        }
    }

    dbgLog.fine("step1=" + StringUtils.join(step1, ","));

    List<List<String>> rangeData = new ArrayList<List<String>>();

    // for each token, check the range operator

    for (int i = 0; i < step1.size(); i++) {
        LinkedList<String> tmp = new LinkedList<String>(
                Arrays.asList(String2StringArray(String.valueOf(step1.get(i)))));

        Map<String, String> token = new HashMap<String, String>();
        boolean rangeMode = false;

        // .get(i) below CAN'T possibly be right (??) -- replacing
        // it with .get(0). -- L.A., v3.6
        //if ((!tmp.get(i).equals("[")) && (!tmp.get(i).equals("("))){
        if ((!tmp.get(0).equals("[")) && (!tmp.get(0).equals("("))) {
            // no LHS range operator
            // assume [
            token.put("start", "3");
        } else if (tmp.get(0).equals("[")) {
            rangeMode = true;
            token.put("start", "3");
            tmp.removeFirst();
        } else if (tmp.get(0).equals("(")) {
            rangeMode = true;
            token.put("start", "5");
            tmp.removeFirst();
        }

        if ((!tmp.getLast().equals("]")) && (!tmp.getLast().equals(")"))) {
            // no RHS range operator
            // assume ]
            token.put("end", "4");
        } else if (tmp.getLast().equals("]")) {
            rangeMode = true;
            tmp.removeLast();
            token.put("end", "4");
        } else if (tmp.getLast().equals(")")) {
            rangeMode = true;
            tmp.removeLast();
            token.put("end", "6");
        }

        // I'm now enforcing the following rules:
        // the "rangeMode" above - a range must have at least one range
        // operator, a square bracket or parenthesis, on one end, at
        // least; i.e., either on the left, or on the right. 
        // If there are no range operators, even if there are dashes
        // inside the token, they are not going to be interpreted as 
        // range definitions.  
        // still TODO: (possibly?) add more validation; figure out how 
        // to encode *date* ranges ("-" is not optimal, since dates already
        // contain dashes... although, since dates are (supposed to be) 
        // normalized it should still be possible to parse it unambiguously)
        //          -- L.A., v3.6

        if (rangeMode) {
            // after these steps, the string does not have range operators;
            // i.e., '-9--3', '--9', '-9-','-9', '-1-1', '1', '3-4', '6-'

            if ((tmp.get(0).equals("!")) && (tmp.get(1).equals("="))) {
                // != negation string is found
                token.put("start", "2");
                token.put("end", "");
                token.put("v1", StringUtils.join(tmp.subList(2, tmp.size()), ""));
                token.put("v2", "");
                dbgLog.fine("value=" + StringUtils.join(tmp.subList(2, tmp.size()), ","));

            } else if ((tmp.get(0).equals("-")) && (tmp.get(1).equals("-"))) {
                // type 2: --9
                token.put("v1", "");
                tmp.removeFirst();
                token.put("v2", StringUtils.join(tmp, ""));
            } else if ((tmp.get(0).equals("-")) && (tmp.getLast().equals("-"))) {
                // type 3: -9-
                token.put("v2", "");
                tmp.removeLast();
                token.put("v1", StringUtils.join(tmp, ""));
            } else if ((!tmp.get(0).equals("-")) && (tmp.getLast().equals("-"))) {
                // type 8: 6-
                token.put("v2", "");
                tmp.removeLast();
                token.put("v1", StringUtils.join(tmp, ""));
            } else {
                int count = 0;
                List<Integer> index = new ArrayList<Integer>();
                for (int j = 0; j < tmp.size(); j++) {
                    if (tmp.get(j).equals("-")) {
                        count++;
                        index.add(j);
                    }
                }

                if (count >= 2) {
                    // range type
                    // divide the second hyphen
                    // types 1 and 5: -9--3, -1-1
                    // token.put("v1", StringUtils.join(tmp[0..($index[1]-1)],"" ));
                    token.put("v2", StringUtils.join(tmp.subList((index.get(1) + 1), tmp.size()), ""));

                } else if (count == 1) {
                    if (tmp.get(0).equals("-")) {
                        // point negative type
                        // type 4: -9 or -inf,9
                        // do nothing
                        if ((token.get("start").equals("5"))
                                && ((token.get("end").equals("6")) || (token.get("end").equals("4")))) {
                            token.put("v1", "");
                            tmp.removeFirst();
                            token.put("v2", StringUtils.join(tmp, ""));
                        } else {
                            token.put("v1", StringUtils.join(tmp, ""));
                            token.put("v2", StringUtils.join(tmp, ""));
                        }
                    } else {
                        // type 7: 3-4
                        // both positive value and range type
                        String[] vset = (StringUtils.join(tmp, "")).split("-");
                        token.put("v1", vset[0]);
                        token.put("v2", vset[1]);
                    }

                } else {
                    // type 6: 1
                    token.put("v1", StringUtils.join(tmp, ""));
                    token.put("v2", StringUtils.join(tmp, ""));
                }
            }
        } else {
            // assume that this is NOT a range; treat the entire sequence 
            // of symbols as a single token:
            // type 6: 1
            token.put("v1", StringUtils.join(tmp, ""));
            token.put("v2", StringUtils.join(tmp, ""));
        }

        dbgLog.fine(i + "-th result=" + token.get("start") + "|" + token.get("v1") + "|" + token.get("end")
                + "|" + token.get("v2"));

        List<String> rangeSet = new ArrayList<String>();
        rangeSet.add(token.get("start"));
        rangeSet.add(token.get("v1"));
        rangeSet.add(token.get("end"));
        rangeSet.add(token.get("v2"));
        rangeData.add(rangeSet);

    }

    dbgLog.fine("rangeData:\n" + rangeData);
    return rangeData;
}

From source file:au.edu.ausstage.networks.SearchManager.java

/**
 * A method to undertake a collaborator search
 *
 * @param query      the name of the collaborator
 * @param formatType the type of data format for the response
 * @param sortType   the type of sort to undertake on the data
 * @param limit      the maximum number of collaborators to return
 *
 * @return           the results of the search
 *///from  www.ja  va2 s.  co m
public String doCollaboratorSearch(String query, String formatType, String sortType, int limit) {

    // double check the parameters
    if (InputUtils.isValid(query) == false || InputUtils.isValid(formatType) == false
            || InputUtils.isValid(sortType) == false) {
        throw new IllegalArgumentException("All of the parameters for this method are required");
    }

    // define a Tree Set to store the results
    java.util.LinkedList<Collaborator> collaborators = new java.util.LinkedList<Collaborator>();

    // define other helper variables
    QuerySolution row = null;
    Collaborator collaborator = null;
    boolean underLimit = true;
    int resultCount = 0;

    // define the base sparql query
    String sparqlQuery = "PREFIX foaf:       <" + FOAF.NS + ">" + "PREFIX ausestage:  <" + AuseStage.NS + "> "
            + "SELECT ?collaborator ?familyName ?givenName ?function ?collaboratorCount " + "WHERE {   "
            + "       ?collaborator a foaf:Person; " + "                     foaf:familyName ?familyName; "
            + "                     foaf:givenName  ?givenName; "
            + "                     foaf:name       ?name; "
            + "                     ausestage:collaboratorCount ?collaboratorCount;  "
            + "                     ausestage:function ?function. " + "       FILTER regex(?name, \"" + query
            + "\", \"i\") " + "}";

    // define the ordering of the result set
    if (sortType.equals("name") == true) {
        sparqlQuery += " ORDER BY ?familyName ?givenName ";
    } else if (sortType.equals("id") == true) {
        // TODO implement the use of a custom function for ordering
    }

    //debug code
    System.out.println("###" + sparqlQuery + "###");

    // execute the query
    ResultSet results = database.executeSparqlQuery(sparqlQuery);

    // build the dataset
    // use a numeric sort order
    while (results.hasNext() && underLimit) {
        // loop though the resulset
        // get a new row of data
        row = results.nextSolution();

        // instantiate a collaborator object
        collaborator = new Collaborator(AusStageURI.getId(row.get("collaborator").toString()));

        // check to see if the list contains this collaborator
        if (collaborators.indexOf(collaborator) != -1) {
            // collaborator is already in the list
            collaborator = collaborators.get(collaborators.indexOf(collaborator));

            // update the function
            collaborator.setFunction(row.get("function").toString());

        } else {
            // collaborator is not on the list

            // have we reached the limit yet
            if (resultCount <= limit) {

                // increment the count
                resultCount++;

                // get the name
                collaborator.setGivenName(row.get("givenName").toString());
                collaborator.setFamilyName(row.get("familyName").toString(), true);

                // get the collaboration count
                collaborator
                        .setCollaborations(Integer.toString(row.get("collaboratorCount").asLiteral().getInt()));

                // add the url
                collaborator.setUrl(AusStageURI.getURL(row.get("collaborator").toString()));

                // add the function
                collaborator.setFunction(row.get("function").toString());

                collaborators.add(collaborator);
            } else {
                // limit reached so stop the loop
                underLimit = false;
            }
        }
    }

    // play nice and tidy up
    database.tidyUp();

    // define a variable to store the data
    String dataString = null;

    if (formatType.equals("html") == true) {
        dataString = createHTMLOutput(collaborators);
    } else if (formatType.equals("xml") == true) {
        dataString = createXMLOutput(collaborators);
    } else if (formatType.equals("json") == true) {
        dataString = createJSONOutput(collaborators);
    }

    // return the data
    return dataString;

}

From source file:util.method.java

public static AbstractOrbacPolicy generateOrBACPolicyFromVMandHostPolicy(LinkedList VMPolicyList,
        LinkedList<VM> VMList, LinkedList HOSTPolicyList, LinkedList<HOST> HOSTList, int VMNumber,
        int HOSTNumber) throws COrbacException {

    COrbacCore core = COrbacCore.GetTheInstance();
    // create new policy using the Jena implementation
    AbstractOrbacPolicy p = core.CreatePolicy("policy" + VMNumber + HOSTNumber, XmlOrbacPolicy.class);

    // add some abstract entities to the policy
    // add an organization
    p.CreateOrganization("superCloud");
    String currentOrganization = "superCloud";
    String currentActivity = "myActivity";
    String currentContext = "default_context";

    p.CreateActivityAndInsertIntoOrg(currentActivity, "superCloud");

    p.Consider("superCloud", "deploy", currentActivity);
    p.AddAction("deploy");

    LinkedList<String> VMIDMemoryList = new LinkedList<String>();
    LinkedList<String> HOSTIDMemoryList = new LinkedList<String>();

    /*Generate OrBAC policy from VM List */

    for (int i = 0; i < VMPolicyList.size(); i++) {
        String currentRole = "Role_Permission_" + i;
        String currentView = "View_Permission_" + i;
        String currentRuleID = "Permission_" + i;

        p.CreateRoleAndInsertIntoOrg(currentRole, currentOrganization);
        p.CreateViewAndInsertIntoOrg(currentView, currentOrganization);
        //System.out.println("---------------currentRuleID"+currentRuleID);

        p.AbstractPermission("superCloud", currentRole, currentActivity, currentView, currentContext,
                currentRuleID);//  w  w w . j  av a 2 s. com
        ArrayList currentVMRule = (ArrayList) VMPolicyList.get(i);

        String policyType = (String) currentVMRule.get(0);
        HashMap HOSTProperty = (HashMap) currentVMRule.get(1);
        HashMap VMProperty = (HashMap) currentVMRule.get(2);

        if (policyType.equals("permission")) {
            LinkedList<String> VMIDList = findRelatedVMID(VMProperty, VMList);

            LinkedList<String> HOSTIDList = findRelatedHOSTID(HOSTProperty, HOSTList);

            if ((VMIDList.size() == 0) || (HOSTIDList.size() == 0))
                return null;

            //p.AbstractPermission ("superCloud",currentRole,currentActivity,currentView,currentContext,currentRuleID);
            for (int j = 0; j < VMIDList.size(); j++) {

                //System.out.print("----------- hahaha This is J"+j);
                //System.out.print("----------- HOSTLIST size"+HOSTList.size());
                for (int k = 0; k < HOSTIDList.size(); k++) {

                    // System.out.print("----------- hahaha This is K"+k);
                    String currentVMID = VMIDList.get(j);
                    String currentHOSTID = HOSTIDList.get(k);
                    //System.out.println("---------------currentHOSTID"+currentHOSTID);
                    //System.out.println("\n---------------currentVMID"+currentVMID);

                    if (!HOSTIDMemoryList.contains(currentHOSTID)) {
                        p.AddSubject(currentHOSTID);
                        HOSTIDMemoryList.add(currentHOSTID);

                    }

                    if (!VMIDMemoryList.contains(currentVMID)) {
                        p.AddObject(currentVMID);
                        VMIDMemoryList.add(currentVMID);

                    }

                    p.Empower(currentOrganization, currentHOSTID, currentRole);
                    p.Use(currentOrganization, currentVMID, currentView);
                }
            }

        }
    }
    /*Generate OrBAC policy from HOST List */

    for (int j1 = 0; j1 < HOSTPolicyList.size(); j1++) {

        String currentRole = "Role_Prohibition_" + j1;
        String currentView = "View_Prohibition_" + j1;
        String currentRuleID = "Prohibition_" + j1;

        p.CreateRoleAndInsertIntoOrg(currentRole, currentOrganization);
        p.CreateViewAndInsertIntoOrg(currentView, currentOrganization);

        p.AbstractProhibition(currentOrganization, currentRole, currentActivity, currentView, currentContext,
                currentRuleID);
        ArrayList currentHOSTRule = (ArrayList) HOSTPolicyList.get(j1);

        String policyType = (String) currentHOSTRule.get(0);
        HashMap HOSTProperty = (HashMap) currentHOSTRule.get(1);
        HashMap VMProperty = (HashMap) currentHOSTRule.get(2);

        if (policyType.equals("prohibition")) {
            LinkedList<String> VMIDList = findRelatedVMID(VMProperty, VMList);

            LinkedList<String> HOSTIDList = findRelatedHOSTID(HOSTProperty, HOSTList);

            // p.AbstractProhibition ("superCloud",currentRole,currentActivity,currentView,currentContext,currentRuleID);
            for (int j2 = 0; j2 < VMIDList.size(); j2++)
                for (int k2 = 0; k2 < HOSTIDList.size(); k2++) {
                    String currentHOSTID = HOSTIDList.get(k2);
                    String currentVMID = VMIDList.get(j2);

                    if (!HOSTIDMemoryList.contains(currentHOSTID)) {
                        p.AddSubject(currentHOSTID);
                        HOSTIDMemoryList.add(currentHOSTID);

                    }

                    if (!VMIDMemoryList.contains(currentVMID)) {
                        p.AddSubject(currentVMID);
                        VMIDMemoryList.add(currentVMID);

                    }

                    p.Empower(currentOrganization, currentHOSTID, currentRole);
                    p.Use(currentOrganization, currentVMID, currentView);
                }

        }

    }

    return p;
}

From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java

private void reorder(int inicio, int fin) {

    boolean sentido = inicio < fin;

    LinkedList<Object> aSubir = new LinkedList<Object>();
    LinkedList<Object> resultado = new LinkedList<Object>();

    for (Object o : right.getSelectedValues()) {
        aSubir.add(o);//from www. ja v  a2  s  .c o  m
    }

    final DefaultListModel defaultListModel = (DefaultListModel) right.getModel();

    if (log.isTraceEnabled()) {
        log.trace("Elementos seleccionados:");
        for (Object o : aSubir) {
            log.trace(o + " " + o.getClass());
        }
    }

    for (int i = inicio; (sentido ? i <= fin : fin <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = defaultListModel.get(i);
        if (aSubir.contains(o) && i != inicio) {
            Object siguiente = resultado.pollLast();
            log.trace("Cambiamos " + o + " por " + siguiente);
            resultado.add(o);
            resultado.add(siguiente);
        } else {
            log.trace("Aadimos " + o);
            resultado.add(o);
        }
    }

    ((DefaultListModel) right.getModel()).removeAllElements();
    log.trace("Nueva lista: ");

    int inicio2 = (sentido ? 0 : resultado.size() - 1);
    int fin2 = (sentido ? resultado.size() - 1 : 0);
    for (int i = inicio2; (sentido ? i <= fin2 : fin2 <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = resultado.get(i);
        log.trace("Nueva lista >" + o);
        ((DefaultListModel) right.getModel()).addElement(o);
    }

    int seleccion[] = new int[aSubir.size()];
    int k = 0;
    for (Integer i = 0; i < right.getModel().getSize(); i++) {
        if (aSubir.contains(right.getModel().getElementAt(i))) {
            seleccion[k++] = i;
        }
    }

    right.setSelectedIndices(seleccion);

    right.updateUI();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Minifies a CSS string by removing comments and excess white-space, as well as
 * some unneeded tokens./* w w w  .j a va2s .c  o  m*/
 *
 * @param css The contents of a CSS file as a String
 * @param res The resource for the CSS file
 * @return the minified css
 */
protected String minify(String css, IResource res) {
    // replace all quoted strings and url(...) patterns with unique ids so that
    // they won't be affected by whitespace removal.
    LinkedList<String> quotedStringReplacements = new LinkedList<String>();
    Matcher m = quotedStringPattern.matcher(css);
    StringBuffer sb = new StringBuffer();
    int i = 0;
    while (m.find()) {
        String text = (m.group(1) != null) ? ("url(" + StringUtils.trim(m.group(1)) + ")") : //$NON-NLS-1$ //$NON-NLS-2$
                m.group(0);
        quotedStringReplacements.add(i, text);
        String replacement = "%%" + QUOTED_STRING_MARKER + (i++) + "__%%"; //$NON-NLS-1$ //$NON-NLS-2$
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(replacement);
    }
    m.appendTail(sb);
    css = sb.toString();

    // Get rid of extra whitespace
    css = whitespacePattern.matcher(css).replaceAll(" "); //$NON-NLS-1$
    css = endsPattern.matcher(css).replaceAll(""); //$NON-NLS-1$
    css = closeBracePattern.matcher(css).replaceAll("}"); //$NON-NLS-1$
    m = delimitersPattern.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        String text = m.group(1);
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(text.length() == 1 ? text : text.replace(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    m.appendTail(sb);
    css = sb.toString();

    // restore quoted strings and url(...) patterns
    m = QUOTED_STRING_MARKER_PAT.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        i = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(quotedStringReplacements.get(i));
    }
    m.appendTail(sb);
    css = sb.toString();

    return css.toString();
}

From source file:util.method.java

public static LinkedList<HOST> readHostFileAndGenerateHOSTList(String fileNames)
        throws IOException, ParseException {
    ArrayList fileNameList = readContractListFromFile(fileNames);

    JSONParser parser = new JSONParser();

    LinkedList<HOST> HOSTList = new LinkedList<HOST>();

    for (int k = 0; k < fileNameList.size(); k++) {

        String fileName = (String) fileNameList.get(k);
        /*Read file and store in file related format*/
        Object obj = parser.parse(new FileReader(fileName));

        JSONObject jsonObject = (JSONObject) obj;

        String ID = (String) jsonObject.get("name");

        HashMap<String, Integer> serviceDescription = (HashMap) jsonObject.get("serviceDescription");

        //method.printHashMap(serviceDescription);

        HashMap gauranteeTerm = (HashMap) jsonObject.get("gauranteeTerm");

        // method.printHashMap(gauranteeTerm);

        //ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");

        //method.printArrayList(creationConstraint);

        /*Extract information and put it into VMlist*/
        /*1. Servcie Description*/

        Iterator iter1 = serviceDescription.entrySet().iterator();
        while (iter1.hasNext()) {

            HashMap.Entry entry = (HashMap.Entry) iter1.next();
            Object key = entry.getKey();

            try {
                float value = Float.parseFloat((String) entry.getValue());
                if (HOSTList.size() == 0) {

                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addServiceDescription((String) key, value);
                    HOSTList.add(newHOST);

                }/*from   ww w. j  a v  a 2  s  .  c  om*/

                boolean find = false;
                for (int i = 0; i < HOSTList.size(); i++) {
                    HOST currentHOST = HOSTList.get(i);

                    if (currentHOST.getID().equals(ID))

                    {
                        currentHOST.addServiceDescription((String) key, value);

                        find = true;

                    }

                }

                if (find == false) {

                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addServiceDescription((String) key, value);
                    HOSTList.add(newHOST);
                }

                // is an integer!
            } catch (NumberFormatException e) {
                // not an integer!
                String value = (String) entry.getValue();
                if (HOSTList.size() == 0) {

                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addServiceDescription((String) key, value);
                    HOSTList.add(newHOST);

                }

                boolean find = false;
                for (int i = 0; i < HOSTList.size(); i++) {
                    HOST currentHOST = HOSTList.get(i);

                    if (currentHOST.getID().equals(ID))

                    {
                        currentHOST.addServiceDescription((String) key, value);

                        find = true;

                    }

                }

                if (find == false) {

                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addServiceDescription((String) key, value);
                    HOSTList.add(newHOST);
                }

            }

            /*2 Gaurantee term*/

            Iterator iter2 = gauranteeTerm.entrySet().iterator();

            while (iter2.hasNext()) {
                HashMap.Entry entry2 = (HashMap.Entry) iter2.next();
                Object key2 = entry2.getKey();
                Object value2 = entry2.getValue();

                if (HOSTList.size() == 0) {
                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addGauranteeTerm((String) key2, (String) value2);

                }

                boolean find2 = false;
                for (int i = 0; i < HOSTList.size(); i++) {
                    HOST currentHOST = HOSTList.get(i);

                    if (currentHOST.getID().equals(ID))

                        currentHOST.addGauranteeTerm((String) key2, (String) value2);

                    find2 = true;

                }

                if (find2 == false) {
                    HOST newHOST = new HOST(ID, new HashMap(), new HashMap());
                    newHOST.addGauranteeTerm((String) key2, (String) value2);

                }
            }

        }

    }

    return HOSTList;

}