List of usage examples for java.util LinkedList removeFirst
public E removeFirst()
From source file:com.zimbra.cs.imap.ImapMessage.java
static void serializeStructure(PrintStream ps, MimeMessage root, boolean extensions) throws IOException, MessagingException { LinkedList<LinkedList<MPartInfo>> queue = new LinkedList<LinkedList<MPartInfo>>(); LinkedList<MPartInfo> level = new LinkedList<MPartInfo>(); level.add(Mime.getParts(root).get(0)); queue.add(level);//from w w w. ja va 2 s . c o m boolean pop = false; while (!queue.isEmpty()) { level = queue.getLast(); if (level.isEmpty()) { queue.removeLast(); pop = true; continue; } MPartInfo mpi = level.getFirst(); MimePart mp = mpi.getMimePart(); boolean hasChildren = mpi.getChildren() != null && !mpi.getChildren().isEmpty(); // we used to force unset charsets on text/plain parts to US-ASCII, but that always seemed unwise... ContentType ctype = new ContentType(mp.getHeader("Content-Type", null)) .setContentType(mpi.getContentType()); String primary = nATOM(ctype.getPrimaryType()), subtype = nATOM(ctype.getSubType()); if (!pop) ps.write('('); if (primary.equals("\"MULTIPART\"")) { if (!pop) { // 7.4.2: "Multiple parts are indicated by parenthesis nesting. Instead of a body type // as the first element of the parenthesized list, there is a sequence of one // or more nested body structures. The second element of the parenthesized // list is the multipart subtype (mixed, digest, parallel, alternative, etc.)." if (!hasChildren) { ps.print("NIL"); } else { queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren())); continue; } } ps.write(' '); ps.print(subtype); if (extensions) { // 7.4.2: "Extension data follows the multipart subtype. Extension data is never // returned with the BODY fetch, but can be returned with a BODYSTRUCTURE // fetch. Extension data, if present, MUST be in the defined order. The // extension data of a multipart body part are in the following order: // body parameter parenthesized list, body disposition, body language, // body location" ps.write(' '); nparams(ps, ctype); ps.write(' '); ndisposition(ps, mp.getHeader("Content-Disposition", null)); ps.write(' '); nlist(ps, mp.getContentLanguage()); ps.write(' '); nstring(ps, mp.getHeader("Content-Location", null)); } } else { if (!pop) { // 7.4.2: "The basic fields of a non-multipart body part are in the following order: // body type, body subtype, body parameter parenthesized list, body id, body // description, body encoding, body size." String cte = mp.getEncoding(); cte = (cte == null || cte.trim().equals("") ? "7bit" : cte); aSTRING(ps, ctype.getPrimaryType()); ps.write(' '); aSTRING(ps, ctype.getSubType()); ps.write(' '); nparams(ps, ctype); ps.write(' '); nstring(ps, mp.getContentID()); ps.write(' '); nstring2047(ps, mp.getDescription()); ps.write(' '); aSTRING(ps, cte); ps.write(' '); ps.print(Math.max(mp.getSize(), 0)); } boolean rfc822 = primary.equals("\"MESSAGE\"") && subtype.equals("\"RFC822\""); if (rfc822) { // 7.4.2: "A body type of type MESSAGE and subtype RFC822 contains, immediately // after the basic fields, the envelope structure, body structure, and // size in text lines of the encapsulated message." if (!pop) { if (!hasChildren) { ps.print(" NIL NIL"); } else { MimeMessage mm = (MimeMessage) mpi.getChildren().get(0).getMimePart(); ps.write(' '); serializeEnvelope(ps, mm); ps.write(' '); queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren())); continue; } } ps.write(' '); ps.print(getLineCount(mp)); } else if (primary.equals("\"TEXT\"")) { // 7.4.2: "A body type of type TEXT contains, immediately after the basic fields, the // size of the body in text lines. Note that this size is the size in its // content transfer encoding and not the resulting size after any decoding." ps.write(' '); ps.print(getLineCount(mp)); } if (extensions) { // 7.4.2: "Extension data follows the basic fields and the type-specific fields // listed above. Extension data is never returned with the BODY fetch, // but can be returned with a BODYSTRUCTURE fetch. Extension data, if // present, MUST be in the defined order. The extension data of a // non-multipart body part are in the following order: body MD5, body // disposition, body language, body location" ps.write(' '); nstring(ps, mp.getContentMD5()); ps.write(' '); ndisposition(ps, mp.getHeader("Content-Disposition", null)); ps.write(' '); nlist(ps, mp.getContentLanguage()); ps.write(' '); nstring(ps, mp.getHeader("Content-Location", null)); } } ps.write(')'); level.removeFirst(); pop = false; } }
From source file:elh.eus.absa.Features.java
/** * Function fills the attribute vectors for the instances existing in the Conll tabulated formatted corpus given. * Attribute vectors contain the features loaded by the creatFeatureSet() function. * /*from w ww.j av a 2 s . c om*/ * @param boolean save : whether the Instances file should be saved to an arff file or not. * @return Weka Instances object containing the attribute vectors filled with the features specified * in the parameter file. */ public Instances loadInstancesConll(boolean save, String prefix) { String savePath = params.getProperty("fVectorDir") + File.separator + "arff" + File.separator + "train_" + prefix; HashMap<String, Opinion> trainExamples = corpus.getOpinions(); String nafdir = params.getProperty("kafDir"); int trainExamplesNum = trainExamples.size(); int bowWin = 0; if (params.containsKey("window")) { bowWin = Integer.parseInt(params.getProperty("window")); savePath = savePath + "_w" + bowWin; } //System.out.println("train examples: "+trainExamplesNum); //Create the Weka object for the training set Instances rsltdata = new Instances("train", atts, trainExamplesNum); // setting class attribute (last attribute in train data. //traindata.setClassIndex(traindata.numAttributes() - 1); System.err.println("Features: loadInstancesConll() - featNum: " + this.featNum + " - trainset attrib num -> " + rsltdata.numAttributes() + " - "); System.out.println("Features: loadInstancesConll() - featNum: " + this.featNum + " - trainset attrib num -> " + rsltdata.numAttributes() + " - "); int instId = 1; // fill the vectors for each training example for (String oId : trainExamples.keySet()) { //System.err.println("sentence: "+ corpus.getOpinionSentence(o.getId())); //value vector double[] values = new double[featNum]; // first element is the instanceId values[rsltdata.attribute("instanceId").index()] = instId; LinkedList<String> ngrams = new LinkedList<String>(); int ngramDim; try { ngramDim = Integer.valueOf(params.getProperty("wfngrams")); } catch (Exception e) { ngramDim = 0; } boolean polNgrams = false; if (params.containsKey("polNgrams")) { polNgrams = params.getProperty("polNgrams").equalsIgnoreCase("yes"); } String nafPath = nafdir + File.separator + trainExamples.get(oId).getsId().replace(':', '_'); String taggedFile = ""; try { if (!FileUtilsElh.checkFile(nafPath + ".kaf")) { nafPath = NLPpipelineWrapper.tagSentence(corpus.getOpinionSentence(oId), nafPath, corpus.getLang(), params.getProperty("pos-model"), postagger); } else { nafPath = nafPath + ".kaf"; } InputStream reader = new FileInputStream(new File(nafPath)); taggedFile = IOUtils.toString(reader); reader.close(); } catch (IOException | JDOMException fe) { // TODO Auto-generated catch block fe.printStackTrace(); } String[] noWindow = taggedFile.split("\n"); //counter for opinion sentence token number. Used for computing relative values of the features int tokNum = noWindow.length; //System.err.println("Features::loadInstancesConll - tagged File read lines:"+tokNum); List<String> window = Arrays.asList(noWindow); Integer end = corpus.getOpinion(oId).getTo(); // apply window if window active (>0) and if the target is not null (to=0) if ((bowWin > 0) && (end > 0)) { Integer start = corpus.getOpinion(oId).getFrom(); Integer from = start - bowWin; if (from < 0) { from = 0; } Integer to = end + bowWin; if (to > noWindow.length - 1) { to = noWindow.length - 1; } window = Arrays.asList(Arrays.copyOfRange(noWindow, from, to)); } //System.out.println("Sentence: "+corpus.getOpinionSentence(oId)+" - target: "+corpus.getOpinion(oId).getTarget()+ // "\n window: from-> "+window.get(0).getForm()+" to-> "+window.get(window.size()-1)+" .\n"); //System.err.println(Arrays.toString(window.toArray())); // word form ngram related features for (String wf : window) { String[] fields = wf.split("\\s"); String wfStr = normalize(fields[0], params.getProperty("normalization", "none")); // blank line means we found a sentence end. Empty n-gram list and reiniciate. if (wf.equals("")) { // add ngrams to the feature vector checkNgramFeatures(ngrams, values, "", 1, true); //toknum // since wf is empty no need to check for clusters and other features. continue; } if (params.containsKey("wfngrams") && ngramDim > 0) { if (!savePath.contains("_wf" + ngramDim)) { savePath = savePath + "_wf" + ngramDim; } //if the current word form is in the ngram list activate the feature in the vector if (ngrams.size() >= ngramDim) { ngrams.removeFirst(); } ngrams.add(wfStr); // add ngrams to the feature vector checkNgramFeatures(ngrams, values, "", 1, false); //toknum } // Clark cluster info corresponding to the current word form if (params.containsKey("clark") && attributeSets.get("ClarkCl").containsKey(wfStr)) { if (!savePath.contains("_cl")) { savePath = savePath + "_cl"; } values[rsltdata.attribute("ClarkClId_" + attributeSets.get("ClarkCl").get(wfStr)).index()]++; } // Clark cluster info corresponding to the current word form if (params.containsKey("brown") && attributeSets.get("BrownCl").containsKey(wfStr)) { if (!savePath.contains("_br")) { savePath = savePath + "_br"; } values[rsltdata.attribute("BrownClId_" + attributeSets.get("BrownCl").get(wfStr)).index()]++; } // Clark cluster info corresponding to the current word form if (params.containsKey("word2vec") && attributeSets.get("w2vCl").containsKey(wfStr)) { if (!savePath.contains("_w2v")) { savePath = savePath + "_w2v"; } values[rsltdata.attribute("w2vClId_" + attributeSets.get("w2vCl").get(wfStr)).index()]++; } } //empty ngram list and add remaining ngrams to the feature list checkNgramFeatures(ngrams, values, "", 1, true); //toknum // PoS tagger related attributes: lemmas and pos tags if (params.containsKey("lemmaNgrams") || (params.containsKey("pos") && !params.getProperty("pos").equalsIgnoreCase("0")) || params.containsKey("polarLexiconGeneral") || params.containsKey("polarLexiconDomain")) { ngrams = new LinkedList<String>(); if (params.containsKey("lemmaNgrams") && (!params.getProperty("lemmaNgrams").equalsIgnoreCase("0"))) { ngramDim = Integer.valueOf(params.getProperty("lemmaNgrams")); } else { ngramDim = 3; } LinkedList<String> posNgrams = new LinkedList<String>(); int posNgramDim = 0; if (params.containsKey("pos")) { posNgramDim = Integer.valueOf(params.getProperty("pos")); } for (String t : window) { //lemmas // && (!params.getProperty("lemmaNgrams").equalsIgnoreCase("0")) if ((params.containsKey("lemmaNgrams")) || params.containsKey("polarLexiconGeneral") || params.containsKey("polarLexiconDomain")) { if (!savePath.contains("_l" + ngramDim)) { savePath = savePath + "_l" + ngramDim; } //blank line means we found a sentence end. Empty n-gram list and reiniciate. if (t.equals("")) { // check both lemma n-grams and polarity lexicons, and add values to the feature vector checkNgramsAndPolarLexicons(ngrams, values, "lemma", 1, tokNum, true, polNgrams); //toknum // since t is empty no need to check for clusters and other features. continue; } String[] fields = t.split("\\s"); if (fields.length < 2) { continue; } String lemma = normalize(fields[1], params.getProperty("normalization", "none")); if (ngrams.size() >= ngramDim) { ngrams.removeFirst(); } ngrams.add(lemma); // check both lemma n-grams and polarity lexicons, and add values to the feature vector checkNgramsAndPolarLexicons(ngrams, values, "lemma", 1, tokNum, false, polNgrams); } //pos tags if (params.containsKey("pos") && !params.getProperty("pos").equalsIgnoreCase("0")) { if (!savePath.contains("_p")) { savePath = savePath + "_p"; } if (posNgrams.size() >= posNgramDim) { posNgrams.removeFirst(); } String[] fields = t.split("\\s"); if (fields.length < 3) { continue; } String pos = fields[2]; posNgrams.add(pos); // add ngrams to the feature vector checkNgramFeatures(posNgrams, values, "pos", 1, false); } } //endFor //empty ngram list and add remaining ngrams to the feature list // check both lemma n-grams and polarity lexicons, and add values to the feature vector checkNgramsAndPolarLexicons(ngrams, values, "", 1, tokNum, true, polNgrams); //empty pos ngram list and add remaining pos ngrams to the feature list checkNgramFeatures(posNgrams, values, "pos", 1, true); } // add sentence length as a feature if (params.containsKey("sentenceLength") && (!params.getProperty("sentenceLength").equalsIgnoreCase("no"))) { values[rsltdata.attribute("sentenceLength").index()] = tokNum; } // compute uppercase ratio before normalization (if needed) //double upRatio =0.0; //if (params.getProperty("upperCaseRatio", "no").equalsIgnoreCase("yes")) //{ // String upper = opNormalized.replaceAll("[a-z]", ""); // upRatio = (double)upper.length() / (double)opNormalized.length(); // values[rsltdata.attribute("upperCaseRation").index()] = upRatio; //} //create object for the current instance and associate it with the current train dataset. Instance inst = new SparseInstance(1.0, values); inst.setDataset(rsltdata); // add category attributte values String cat = trainExamples.get(oId).getCategory(); if (params.containsKey("categories") && params.getProperty("categories").compareTo("E&A") == 0) { if (cat.compareTo("NULL") == 0) { inst.setValue(rsltdata.attribute("entCat").index(), cat); inst.setValue(rsltdata.attribute("attCat").index(), cat); } else { String[] splitCat = cat.split("#"); inst.setValue(rsltdata.attribute("entCat").index(), splitCat[0]); inst.setValue(rsltdata.attribute("attCat").index(), splitCat[1]); } //inst.setValue(attIndexes.get("entAttCat"), cat); } else if (params.containsKey("categories") && params.getProperty("categories").compareTo("E#A") == 0) { inst.setValue(rsltdata.attribute("entAttCat").index(), cat); } if (params.containsKey("polarity") && params.getProperty("polarity").compareTo("yes") == 0) { // add class value as a double (Weka stores all values as doubles ) String pol = normalizePolarity(trainExamples.get(oId).getPolarity()); if (pol != null && !pol.isEmpty()) { inst.setValue(rsltdata.attribute("polarityCat"), pol); } else { //System.err.println("polarity: _"+pol+"_"); inst.setMissing(rsltdata.attribute("polarityCat")); } } //add instance to train data rsltdata.add(inst); //store opinion Id and instance Id this.opInst.put(oId, instId); instId++; } System.err.println("Features : loadInstancesConll() - training data ready total number of examples -> " + trainExamplesNum + " - " + rsltdata.numInstances()); if (save) { try { savePath = savePath + ".arff"; System.err.println("arff written to: " + savePath); ArffSaver saver = new ArffSaver(); saver.setInstances(rsltdata); saver.setFile(new File(savePath)); saver.writeBatch(); } catch (IOException e1) { e1.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } } return rsltdata; }
From source file:org.opendaylight.vtn.manager.it.northbound.VtnNorthboundIT.java
/** * Test case for MAC mapping APIs./*from w w w.j av a 2s .com*/ * * <p> * This method is called by {@link #testVBridgeAPI(String, String)}. * </p> * * @param tname The name of existing virtual tenant. * @param bname1 The name of existing vBridge. * @param bname2 The name of existing vBridge. * @throws JSONException An error occurred. */ private void testMacMappingAPI(String tname, String bname1, String bname2) throws JSONException { LOG.info("Starting MAC Mapping JAX-RS client."); String qparam = "?param1=1¶m2=2"; String mapUri = createURI("default/vtns", tname, "vbridges", bname1, "macmap"); String mapUri2 = createURI("default/vtns", tname, "vbridges", bname2, "macmap"); // Ensure that no MAC mapping is configured. assertNoMacMapping(mapUri); assertNoMacMapping(mapUri2); LinkedList<String> allowedHosts = new LinkedList<String>(); allowedHosts.add(null); allowedHosts.add(null); byte[] allowedAddr = { (byte) 0x10, (byte) 0x20, (byte) 0x30, (byte) 0x40, (byte) 0x50, (byte) 0x00, }; for (int i = 0; i < 20; i++) { String mac; if ((i & 1) == 0) { mac = null; } else { allowedAddr[5] = (byte) i; mac = ByteUtils.toHexString(allowedAddr); } String vlan = (i == 0) ? "4095" : String.valueOf(i); allowedHosts.add(mac); allowedHosts.add(vlan); } LinkedList<String> deniedHosts = new LinkedList<String>(); byte[] deniedAddr = { (byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, (byte) 0x00, (byte) 0xf5, }; for (int i = 0; i < 20; i++) { deniedAddr[4] = (byte) i; String mac = ByteUtils.toHexString(deniedAddr); String vlan = String.valueOf(i + 100); deniedHosts.add(mac); deniedHosts.add(vlan); } deniedHosts.add("00:00:ff:ff:ff:0f"); deniedHosts.add(null); // Install MAC mapping configuration. JSONObject config = createMacMapConfig(allowedHosts, deniedHosts); JSONObject configExpected = completeMacMapConfig(config); String cf = config.toString(); getJsonResult(mapUri + qparam, HTTP_PUT, cf); assertResponse(HTTP_CREATED); Assert.assertEquals(mapUri, httpLocation); for (String method : new String[] { HTTP_PUT, HTTP_POST }) { getJsonResult(mapUri, method, cf); assertResponse(HTTP_NO_CONTENT); } assertMacMapping(mapUri, configExpected); // Try to create MAC mapping with specifying invalid MAC address. String[] badMacs = { // broken "invalid_mac_address", // zero "00:00:00:00:00:00", // broadcast "ff:ff:ff:ff:ff:ff", // multicast "81:00:11:22:33:44", }; String[] acls = { "allow", "deny" }; for (String mac : badMacs) { JSONObject machost = new JSONObject(); machost.put("address", mac); machost.put("vlan", 1); JSONArray maclist = new JSONArray(); maclist.put(machost); JSONObject set = new JSONObject(); set.put("machost", maclist); for (String acl : acls) { String uri = createRelativeURI(mapUri, acl, mac, "1"); getJsonResult(uri, HTTP_PUT); assertResponse(HTTP_BAD_REQUEST); for (String method : new String[] { HTTP_PUT, HTTP_POST }) { JSONObject conf = new JSONObject(); conf.put(acl, set); getJsonResult(mapUri, method, conf.toString()); assertResponse(HTTP_BAD_REQUEST); uri = createRelativeURI(mapUri, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_BAD_REQUEST); } } } // Try to create MAC mapping with specifying invalid VLAN ID. int[] badVlans = { -1, 4096, 10000, }; for (int vlan : badVlans) { String mac = "00:00:00:00:00:10"; JSONObject machost = new JSONObject(); machost.put("address", mac); machost.put("vlan", vlan); JSONArray maclist = new JSONArray(); maclist.put(machost); JSONObject set = new JSONObject(); set.put("machost", maclist); for (String acl : acls) { String uri = createRelativeURI(mapUri, acl, mac, String.valueOf(vlan)); getJsonResult(uri, HTTP_PUT); assertResponse(HTTP_BAD_REQUEST); for (String method : new String[] { HTTP_PUT, HTTP_POST }) { JSONObject conf = new JSONObject(); conf.put(acl, set); getJsonResult(mapUri, method, conf.toString()); assertResponse(HTTP_BAD_REQUEST); uri = createRelativeURI(mapUri, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_BAD_REQUEST); } } } // Try to register NULL address to deny set. for (String method : new String[] { HTTP_POST, HTTP_PUT }) { String acl = "deny"; JSONObject set = createMacHostSet(null, "110"); JSONObject conf = new JSONObject(); conf.put(acl, set); getJsonResult(mapUri, method, conf.toString()); assertResponse(HTTP_BAD_REQUEST); String uri = createRelativeURI(mapUri, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_BAD_REQUEST); } // Try to remove hosts that are not registered. String remove = "?action=remove"; LinkedList<String> allowedHosts1 = new LinkedList<String>(); for (int i = 0; i < 5; i++) { String mac; if ((i & 1) == 0) { mac = null; } else { allowedAddr[5] = (byte) i; mac = ByteUtils.toHexString(allowedAddr); } String vlan = String.valueOf(i + 100); allowedHosts1.add(mac); allowedHosts1.add(vlan); } for (int i = 5; i < 10; i++) { String mac; if ((i & 1) == 0) { allowedAddr[5] = (byte) (i + 1); mac = ByteUtils.toHexString(allowedAddr); } else { mac = null; } String vlan = String.valueOf(i); allowedHosts1.add(mac); allowedHosts1.add(vlan); } LinkedList<String> deniedHosts1 = new LinkedList<String>(); for (int i = 0; i < 5; i++) { deniedAddr[4] = (byte) (i + 1); String mac = ByteUtils.toHexString(deniedAddr); String vlan = String.valueOf(i + 100); deniedHosts1.add(mac); deniedHosts1.add(vlan); } for (int i = 5; i < 10; i++) { deniedAddr[4] = (byte) i; String mac = ByteUtils.toHexString(deniedAddr); String vlan = String.valueOf(i + 1000); deniedHosts1.add(mac); deniedHosts1.add(vlan); } JSONObject allow1 = createMacHostSet(allowedHosts1); JSONObject deny1 = createMacHostSet(deniedHosts1); config = new JSONObject(); config.put("allow", allow1).put("deny", deny1); getJsonResult(createRelativeURI(mapUri + remove), HTTP_POST, config.toString()); assertResponse(HTTP_NO_CONTENT); for (String acl : acls) { JSONObject set; LinkedList<String> hostList; if (acl.equals("allow")) { set = allow1; hostList = allowedHosts1; } else { set = deny1; hostList = deniedHosts1; } getJsonResult(createRelativeURI(mapUri, acl + remove), HTTP_POST, set.toString()); assertResponse(HTTP_NO_CONTENT); Iterator<String> it = hostList.iterator(); while (it.hasNext()) { String m = it.next(); String v = it.next(); String uri = createRelativeURI(mapUri, acl, (m == null) ? "ANY" : m, (v == null) ? "0" : v); getJsonResult(uri, HTTP_DELETE); assertResponse(HTTP_NO_CONTENT); } } String[] allowedArray = allowedHosts.toArray(new String[0]); for (int i = 0; i < allowedArray.length; i += 2) { String acl = "allow"; String mac = allowedArray[i]; String vlan = allowedArray[i + 1]; // Try to map MAC addresses which are already mapped by another // vBridge. String uri = createRelativeURI(mapUri2, acl, (mac == null) ? "ANY" : mac, (vlan == null) ? "0" : vlan); getJsonResult(uri, HTTP_PUT); assertResponse(HTTP_CONFLICT); JSONObject set = createMacHostSet(mac, vlan); JSONObject conf = new JSONObject(); conf.put(acl, set); for (String method : new String[] { HTTP_POST, HTTP_PUT }) { getJsonResult(mapUri2, method, conf.toString()); assertResponse(HTTP_CONFLICT); uri = createRelativeURI(mapUri2, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_CONFLICT); } if (mac == null) { continue; } // Try to register duplicate MAC address. uri = createRelativeURI(mapUri, acl, mac, "1000"); getJsonResult(uri, HTTP_PUT); assertResponse(HTTP_CONFLICT); set = createMacHostSet(mac, "1000"); conf = new JSONObject(); conf.put(acl, set); String method = HTTP_POST; getJsonResult(mapUri, method, conf.toString()); assertResponse(HTTP_CONFLICT); uri = createRelativeURI(mapUri, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_CONFLICT); } // Duplicate MAC address in allow set. String acl = "allow"; String mac = "00:11:22:33:55:88"; JSONObject set = createMacHostSet(mac, "1000", mac, "1001"); for (String method : new String[] { HTTP_POST, HTTP_PUT }) { JSONObject conf = new JSONObject(); conf.put(acl, set); getJsonResult(mapUri, method, conf.toString()); assertResponse(HTTP_BAD_REQUEST); String uri = createRelativeURI(mapUri, acl); getJsonResult(uri, method, set.toString()); assertResponse(HTTP_BAD_REQUEST); } // Configuration should not be affected. assertMacMapping(mapUri, configExpected); // Remove 2 hosts from both list. for (int i = 0; i < 4; i++) { allowedHosts.removeFirst(); deniedHosts.removeFirst(); } config = createMacMapConfig(allowedHosts, deniedHosts); getJsonResult(mapUri, HTTP_PUT, config.toString()); assertResponse(HTTP_OK); configExpected = completeMacMapConfig(config); assertMacMapping(mapUri, configExpected); for (String acl1 : acls) { LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; // Remove 2 hosts by specifying the list. String mac1 = hostList.removeFirst(); String vlan1 = hostList.removeFirst(); String mac2 = hostList.removeFirst(); String vlan2 = hostList.removeFirst(); JSONObject set1 = createMacHostSet(mac1, vlan1, mac2, vlan2); String uri = createRelativeURI(mapUri, acl1 + remove); getJsonResult(uri, HTTP_POST, set1.toString()); assertResponse(HTTP_OK); assertMacMapping(mapUri, allowedHosts, deniedHosts); } // Remove 2 hosts from both lists. config = new JSONObject(); for (String acl1 : acls) { LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; String mac1 = hostList.removeFirst(); String vlan1 = hostList.removeFirst(); String mac2 = hostList.removeFirst(); String vlan2 = hostList.removeFirst(); JSONObject set1 = createMacHostSet(mac1, vlan1, mac2, vlan2); config.put(acl1, set1); } getJsonResult(mapUri + remove, HTTP_POST, config.toString()); assertResponse(HTTP_OK); assertMacMapping(mapUri, allowedHosts, deniedHosts); // Remove 3 hosts by DELETE. for (String acl1 : acls) { LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; for (int i = 0; i < 3; i++) { String m = hostList.removeFirst(); String v = hostList.removeFirst(); String uri = createRelativeURI(mapUri, acl1, (m == null) ? "ANY" : m, (v == null) ? "0" : v); getJsonResult(uri, HTTP_DELETE); assertResponse(HTTP_OK); } } assertMacMapping(mapUri, allowedHosts, deniedHosts); // Remove 3 hosts, and add 4 hosts by PUT. byte[] base = { (byte) 0xa0, (byte) 0xa1, (byte) 0xa2, (byte) 0x00, (byte) 0xa4, (byte) 0xa5, }; for (String acl1 : acls) { LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; for (int i = 0; i < 6; i++) { hostList.removeFirst(); } for (int i = 0; i < 4; i++) { base[3] = (byte) i; hostList.add(ByteUtils.toHexString(base)); hostList.add(String.valueOf(i + 500)); } } config = createMacMapConfig(allowedHosts, deniedHosts); configExpected = completeMacMapConfig(config); getJsonResult(mapUri, HTTP_PUT, config.toString()); assertResponse(HTTP_OK); assertMacMapping(mapUri, allowedHosts, deniedHosts); for (String acl1 : acls) { LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; for (int i = 0; i < 6; i++) { hostList.removeFirst(); } for (int i = 20; i < 24; i++) { base[3] = (byte) i; hostList.add(ByteUtils.toHexString(base)); hostList.add(String.valueOf(i + 500)); } JSONObject set1 = createMacHostSet(hostList); getJsonResult(createRelativeURI(mapUri, acl1), HTTP_PUT, set1.toString()); assertResponse(HTTP_OK); assertMacMapping(mapUri, allowedHosts, deniedHosts); } // Remove MAC mapping by specifying host list. LinkedList<String> saveAllowed = new LinkedList<String>(allowedHosts); LinkedList<String> saveDenied = new LinkedList<String>(deniedHosts); for (int i = 0; i < acls.length; i++) { String acl1 = acls[i]; LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts; hostList.clear(); String uri = createRelativeURI(mapUri, acl1); getJsonResult(uri, HTTP_DELETE); assertResponse(HTTP_OK); if (i == acls.length - 1) { assertNoMacMapping(mapUri); } else { assertMacMapping(mapUri, allowedHosts, deniedHosts); } } // Install the same MAC mapping to another vBridge. config = createMacMapConfig(saveAllowed, saveDenied); configExpected = completeMacMapConfig(config); getJsonResult(mapUri2, HTTP_PUT, config.toString()); assertResponse(HTTP_CREATED); assertMacMapping(mapUri2, configExpected); getJsonResult(mapUri2, HTTP_DELETE); assertResponse(HTTP_OK); assertNoMacMapping(mapUri2); // Create MAC mapping by installing a host to the specific URI. mac = "00:11:22:33:44:55"; String vlan = "4095"; JSONObject hostSet = createMacHostSet(mac, vlan); List<String> empty = new LinkedList<String>(); for (String acl1 : acls) { JSONObject set1; if (acl1.equals("allow")) { set1 = createMacHostSet(saveAllowed); config = createMacMapConfig(saveAllowed, empty); } else { set1 = createMacHostSet(saveDenied); config = createMacMapConfig(empty, saveDenied); } configExpected = completeMacMapConfig(config); String uri = createRelativeURI(mapUri2, acl1); for (String method : new String[] { HTTP_PUT, HTTP_POST }) { getJsonResult(uri + qparam, method, set1.toString()); assertResponse(HTTP_CREATED); Assert.assertEquals(uri, httpLocation); assertMacMapping(mapUri2, configExpected); getJsonResult(uri, HTTP_DELETE); assertResponse(HTTP_OK); assertNoMacMapping(mapUri2); } config = new JSONObject(); config.put(acl1, hostSet); String hostUri = createRelativeURI(uri, mac, vlan); getJsonResult(hostUri + qparam, HTTP_PUT); assertResponse(HTTP_CREATED); Assert.assertEquals(hostUri, httpLocation); assertMacMapping(mapUri2, config); getJsonResult(hostUri, HTTP_DELETE); assertResponse(HTTP_OK); assertNoMacMapping(mapUri2); } }