List of usage examples for java.util ArrayList remove
public boolean remove(Object o)
From source file:com.hygenics.parser.ForceConformity.java
private void iter() { log.info("Starting Enforcement @ " + Calendar.getInstance().getTime().toString() + " | UTC " + Calendar.getInstance().getTimeInMillis()); String sql;//from ww w . j a v a 2s. c o m boolean add = true; ArrayList<String> columns = null; ArrayList<String> tablecolumns = null; Quicksort<String> qs = new Quicksort<String>(); Levenshtein lev = new Levenshtein(); // iterate through each table for (String table : schema_columns.keySet()) { log.info("Checking for Table Existance " + table); String schema = null; try { schema = table.split("\\.")[0]; } catch (IndexOutOfBoundsException e) { try { throw new SQLMalformedException("FATAL ERROR: Table name " + table + " malformed"); } catch (SQLMalformedException e2) { e2.printStackTrace(); System.exit(-1); } } log.info("Checking table: " + table + "&& schema: " + schema); if (template.checkTable(table, schema)) { log.info("Conforming: " + table); // get the arraylist tablecolumns = template.getColumns(table); if (insensitive == true) { for (int i = 0; i < tablecolumns.size(); i++) { tablecolumns.set(i, tablecolumns.get(i).toLowerCase()); } } columns = (ArrayList<String>) schema_columns.get(table); if (insensitive == true) { for (int i = 0; i < columns.size(); i++) { columns.set(i, columns.get(i).toLowerCase()); } } if (exclude != null) { // remove unmatchable columns if (exclude.size() > 0) { for (String col : exclude) { tablecolumns.remove(col); columns.remove(col); } } } // sort each arraylist qs.setTosortlist(columns); columns = qs.sort(); qs.setTosortlist(tablecolumns); tablecolumns = qs.sort(); // check each remaining column for (int i = 0; i < columns.size(); i++) { if (tablecolumns.contains(columns.get(i).trim()) == false || (insensitive == true && tablecolumns.contains(columns.get(i).toLowerCase().trim()) == false)) { if (correct) { int dist = Levenshtein.getLevenshteinDistance(tablecolumns.get(i), columns.get(i)); add = false; log.info("Distance was " + dist + " Cutoff is " + levcutoff); // check lev. distances if requested and ensure some // match with fuzzy (use at your own risk) if (levcutoff > -1 & dist <= levcutoff) { log.info("Approximate Match: Correcting Column"); // if distance is within 1 or specified // distances, correct it sql = "ALTER TABLE " + table + " RENAME COLUMN " + tablecolumns.get(i) + " TO " + columns.get(i); template.execute(sql); // get the table columns tablecolumns = template.getColumns(table); qs.setTosortlist(tablecolumns); tablecolumns = qs.sort(); } else { add = true; } } if (add) { // add column if necessary sql = "Alter Table " + table + " ADD COLUMN " + columns.get(i) + " text"; template.execute(sql); // get the table columns again and resort them tablecolumns = template.getColumns(table); if (exclude != null) { if (exclude.size() > 0) { for (String ex : exclude) { tablecolumns.remove(ex); columns.remove(ex); } } } qs.setTosortlist(tablecolumns); tablecolumns = qs.sort(); } // iterate backward so that the integrety is assured i--; } } } else { try { throw new SQLMalformedException("WARNING: Table " + table + " is missing"); } catch (SQLMalformedException e) { e.printStackTrace(); } } } log.info("Finishing Enforcement @ " + Calendar.getInstance().getTime().toString() + " | UTC " + Calendar.getInstance().getTimeInMillis()); }
From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java
private void checkAndRemoveDuplicates(MaterialInstance materialInstance, List<Modification> newChanges, ArrayList<Modification> list) { if (!new SystemEnvironment().get(SystemEnvironment.CHECK_AND_REMOVE_DUPLICATE_MODIFICATIONS)) { return;/*from w w w . j a va 2 s. co m*/ } DetachedCriteria criteria = DetachedCriteria.forClass(Modification.class); criteria.setProjection(Projections.projectionList().add(Projections.property("revision"))); criteria.add(Restrictions.eq("materialInstance.id", materialInstance.getId())); ArrayList<String> revisions = new ArrayList<>(); for (Modification modification : newChanges) { revisions.add(modification.getRevision()); } criteria.add(Restrictions.in("revision", revisions)); List<String> matchingRevisionsFromDb = (List<String>) getHibernateTemplate().findByCriteria(criteria); if (!matchingRevisionsFromDb.isEmpty()) { for (final String revision : matchingRevisionsFromDb) { Modification modification = list.stream().filter(item -> item.getRevision().equals(revision)) .findFirst().orElse(null); list.remove(modification); } } if (!newChanges.isEmpty() && list.isEmpty()) { LOGGER.debug("All modifications already exist in db [{}]", revisions); } if (!matchingRevisionsFromDb.isEmpty()) { LOGGER.info("Saving revisions for material [{}] after removing the following duplicates {}", materialInstance.toOldMaterial(null, null, null).getLongDescription(), matchingRevisionsFromDb); } }
From source file:com.viettel.util.StringUtils.java
public static void buidQuery(String name, HashMap<String, Object> searchParams, StringBuilder strQuery, Map<String, Object> params, String... prefix) { ArrayList<String> arrQuery = new ArrayList<String>(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); HashMap<String, Object> searchParamsCopy = new HashMap<>(searchParams); for (Map.Entry<String, Object> entry : searchParams.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value == null || value.toString().equals("")) { searchParamsCopy.remove(key); }//from w w w . j av a 2 s . c om } String pref = prefix != null && prefix.length > 0 ? prefix[0] + "." : ""; for (Map.Entry<String, Object> entry : searchParamsCopy.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); /* * if (value == null || value.toString().equals("") || (value * instanceof Long && 0 >= (int) value)) { continue; } */ if (arrQuery.size() > 0) { arrQuery.add(" AND "); } if (value instanceof Date || DateUtil.isValidDateWithFormat(value.toString(), "yyyy-MM-dd")) { try { if (key.startsWith("from")) { String cl = key.replace("from", ""); if (searchParamsCopy.containsKey("to" + cl)) { arrQuery.add(String.format("%1$s BETWEEN :%2$s", pref + cl, key)); params.put(key, formatter.parse(value.toString())); Object objTo = searchParamsCopy.get("to" + cl); if (objTo != null) { arrQuery.add(String.format(" AND :%s", "to" + cl)); params.put("to" + cl, formatter.parse(objTo.toString())); } } else { arrQuery.add(String.format("%1$s >= :%2$s", pref + cl, key)); params.put(key, formatter.parse(value.toString())); } } else if (key.startsWith("to")) { String cl = key.replace("to", ""); if (!searchParamsCopy.containsKey("from" + cl)) { arrQuery.add(String.format("%1$s <= :%2$s", pref + cl, key)); params.put(key, formatter.parse(value.toString())); } else { if (arrQuery.size() > 0) { arrQuery.remove(arrQuery.size() - 1); } } } else { arrQuery.add(String.format("DATE(%1$s) = DATE(:%2$s)", pref + key, key)); params.put(key, value + "%"); } } catch (ParseException ex) { } } else if (value instanceof Number) { if (key.startsWith("and_")) { if (searchParamsCopy.containsKey(key.replace("and_", ""))) { if (!CollectionUtils.isEmpty(arrQuery)) { arrQuery.remove(arrQuery.size() - 1); } } } else if (searchParamsCopy.containsKey("and_" + key)) { arrQuery.add(String.format("(%1$s = :%2$s", pref + key, key)); if (value instanceof Integer) { params.put(key, Integer.parseInt(value.toString())); } else if (value instanceof Long) { params.put(key, Long.parseLong(value.toString())); } else if (value instanceof Float) { params.put(key, Float.parseFloat(value.toString())); } else if (value instanceof Double) { params.put(key, Double.parseDouble(value.toString())); } Object obj = searchParamsCopy.get("and_" + key); if (obj != null) { arrQuery.add(String.format(" OR %1$s = :%2$s)", pref + key, "and_" + key)); if (value instanceof Integer) { params.put("and_" + key, Integer.parseInt(obj.toString())); } else if (value instanceof Long) { params.put("and_" + key, Long.parseLong(obj.toString())); } else if (value instanceof Float) { params.put("and_" + key, Float.parseFloat(obj.toString())); } else if (value instanceof Double) { params.put("and_" + key, Double.parseDouble(obj.toString())); } } } else { arrQuery.add(String.format("%1$s = :%2$s", pref + key, key)); if (value instanceof Integer) { params.put(key, Integer.parseInt(value.toString())); } else if (value instanceof Long) { params.put(key, Long.parseLong(value.toString())); } else if (value instanceof Float) { params.put(key, Float.parseFloat(value.toString())); } else if (value instanceof Double) { params.put(key, Double.parseDouble(value.toString())); } } } else if (value instanceof String) { if (key.startsWith("and_")) { if (searchParamsCopy.containsKey(key.replace("and_", ""))) { if (arrQuery.size() > 0) { arrQuery.remove(arrQuery.size() - 1); } } } else if (searchParamsCopy.containsKey("and_" + key)) { arrQuery.add(String.format("(LOWER(%1$s) like LOWER(:%2$s)", pref + key, key)); params.put(key, "%" + value + "%"); Object obj = searchParamsCopy.get("and_" + key); if (obj != null) { arrQuery.add(String.format(" OR LOWER(%1$s) LIKE LOWER(:%2$s))", pref + key, "and_" + key)); params.put("and_" + key, "%" + obj + "%"); } } else if (key.startsWith("in_cond_")) { String cl = key.replace("in_cond_", ""); arrQuery.add(String.format("%1$s IN (%2$s)", pref + cl, value.toString())); params.remove(key); } else if (key.startsWith("not_in_cond_")) { String cl = key.replace("not_in_cond_", ""); arrQuery.add(String.format("%1$s NOT IN (%2$s)", pref + cl, value.toString())); params.remove(key); } else { arrQuery.add(String.format("LOWER(%1$s) LIKE LOWER(:%2$s)", pref + key, key)); params.put(key, "%" + value + "%"); } } } strQuery.append(String.join("", arrQuery)); }
From source file:com.termmed.reconciliation.RelationshipReconciliation.java
/** * Compare actives wo match.//www.ja v a 2 s. c o m * * @param step the step * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private String compareActivesWOMatch(int step) throws IOException { // STATISTICS COUNTERS int countSameISA = 0; int countA_Diff = 0; int countB_Diff = 0; int countB_DiffISA = 0; int countB_Total = 0; int sumNewNoRec = 0; int sumPrevActNowRet = 0; long startTime = System.currentTimeMillis(); StringBuilder s = new StringBuilder(); s.append( "\r\n::: [Reconciliation by previous actives vs current actives, without grouping comparation - step:" + step + "]"); boolean reconciled = false; for (Long conceptId : newNoRec.keySet()) { ArrayList<Relationship> relsPrev = prevActNowRet.get(conceptId); ArrayList<Relationship> relsCurr = newNoRec.get(conceptId); sumNewNoRec += relsCurr.size(); if (relsPrev != null) { sumPrevActNowRet += relsPrev.size(); for (Relationship relC : relsCurr) { reconciled = false; for (Relationship relP : relsPrev) { if (compareRelsStep(relC, relP, step)) { writeReconciled(bw, relC, relP); countB_Total++; if (relC.typeId == isa) { countSameISA++; } reconciled = true; relsPrev.remove(relP); break; } } if (!reconciled) { countB_Diff++; if (relC.typeId == isa) { countB_DiffISA++; } writeNewNoRec(relC); } } countA_Diff += relsPrev.size(); prevActNowRet.put(conceptId, relsPrev); } else { for (Relationship relC : relsCurr) { countB_Diff++; if (relC.typeId == isa) { countB_DiffISA++; } writeNewNoRec(relC); } } } s.append("\r\n::: Current active relationships to reconcile = \t" + sumNewNoRec); s.append("\r\n::: Candidate previous active relationships to match = \t" + sumPrevActNowRet); s.append("\r\n::: Partial process statistics:"); s.append("\r\n::: Reconciled relationships: \t").append(countB_Total); s.append("\r\n::: Reconciled Isa's relationships: \t").append(countSameISA); s.append("\r\n::: Previous relationships without match : \t").append(countA_Diff); s.append("\r\n::: Current relationships without match: \t").append(countB_Diff); s.append("\r\n::: Current Isa's relationships without match:\t").append(countB_DiffISA); s.append("\r\n::: "); long lapseTime = System.currentTimeMillis() - startTime; s.append("\r\n::: [Partial time] Sort/Compare Input & Output: \t").append(lapseTime); s.append("\t(mS)\t"); s.append("\r\n"); sumB_Total += countB_Total; sumSameISA += countSameISA; sumA_Diff = countA_Diff; sumB_Diff = countB_Diff; sumB_DiffISA = countB_DiffISA; return s.toString(); }
From source file:edu.cmu.sphinx.speakerid.SpeakerIdentification.java
/** * @param features The feature vectors to be used for clustering * @return A cluster for each speaker detected based on the feature vectors provided *///from w w w . ja v a 2 s .co m public ArrayList<SpeakerCluster> cluster(ArrayList<float[]> features) { ArrayList<SpeakerCluster> ret = new ArrayList<SpeakerCluster>(); Array2DRowRealMatrix featuresMatrix = ArrayToRealMatrix(features, features.size()); LinkedList<Integer> l = getAllChangingPoints(featuresMatrix); Iterator<Integer> it = l.iterator(); int curent, previous = it.next(); while (it.hasNext()) { curent = it.next(); Segment s = new Segment(previous * Segment.FRAME_LENGTH, (curent - previous) * (Segment.FRAME_LENGTH)); Array2DRowRealMatrix featuresSubset = (Array2DRowRealMatrix) featuresMatrix.getSubMatrix(previous, curent - 1, 0, 12); ret.add(new SpeakerCluster(s, featuresSubset, getBICValue(featuresSubset))); previous = curent; } int clusterCount = ret.size(); Array2DRowRealMatrix distance; distance = new Array2DRowRealMatrix(clusterCount, clusterCount); distance = updateDistances(ret); while (true) { double distmin = 0; int imin = -1, jmin = -1; for (int i = 0; i < clusterCount; i++) for (int j = 0; j < clusterCount; j++) if (i != j) distmin += distance.getEntry(i, j); distmin /= (clusterCount * (clusterCount - 1) * 4); for (int i = 0; i < clusterCount; i++) { for (int j = 0; j < clusterCount; j++) { if (distance.getEntry(i, j) < distmin && i != j) { distmin = distance.getEntry(i, j); imin = i; jmin = j; } } } if (imin == -1) { break; } ret.get(imin).mergeWith(ret.get(jmin)); updateDistances(ret, imin, jmin, distance); ret.remove(jmin); clusterCount--; } return ret; }
From source file:fitnesserefactor.FitnesseRefactor.java
private void DelTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelTableActionPerformed if (ParentFolder.isSelected()) { if (!"".equals(JtreePath)) { File dir = new File(JtreePath); try { if (dir.getParent() != null && dir.isFile()) { String Testcase = dir.getParent(); File dir1 = new File(Testcase); if (dir1.getParent() != null && dir1.isDirectory()) { String parent = dir1.getParent(); File dir2 = new File(Testcase); if (dir2.getParent() != null) { String GrandParent = dir2.getParent(); File dir3 = new File(GrandParent); File[] allFiles = dir3.listFiles(); ArrayList al = new ArrayList(); for (File file : allFiles) { String TestcaseNames = file.getName(); al.add(TestcaseNames); }/* w w w . j a va2 s . c o m*/ if (!fromTxt.getText().isEmpty() && !toTxt.getText().isEmpty()) { int FromTxtInt = Integer.parseInt(fromTxt.getText()); int ToTxtInt = Integer.parseInt(toTxt.getText()); int TotFiles = al.size(); if ((ToTxtInt > FromTxtInt) && (ToTxtInt > 0) && (FromTxtInt > 0) && ToTxtInt <= al.size() - 2) { for (int removeAfterToIndx = (ToTxtInt + 2); removeAfterToIndx < TotFiles; removeAfterToIndx++) { al.remove(ToTxtInt + 2); } if (FromTxtInt > 1) { for (int removeFromIndx = 1; removeFromIndx < FromTxtInt; removeFromIndx++) { al.remove(2); } } } else { JOptionPane.showMessageDialog(null, "FROM test case number cannot be greater/equal to TO test case number.\nFROM and TO test case numbers should be greater than zero. \nTO test case number should not be greater than the testcase count ", "Warning", JOptionPane.WARNING_MESSAGE); } } for (int i = 2; i <= al.size(); i++) { System.out.println(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); File EachFile = new File(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); for (int j = 0; j < FileUtils.readLines(EachFile).size(); j++) { String line = (String) FileUtils.readLines(EachFile).get(j); if (line.matches("(.*)" + FitnesseTablesList.getSelectedItem().toString() + "(.*)")) { p = j; ReadAllLines(EachFile); int selectTableSize = SizeOfTable(EachFile); for (int DeleteLines = 0; DeleteLines <= selectTableSize; DeleteLines++) { AllLines.remove(p); } WriteAllLines(EachFile); } } } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Need to select atleast one content.txt file", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (Exception E) { //JOptionPane.showMessageDialog(null, E, "Java Runtime Error", JOptionPane.ERROR ); } } } }
From source file:fitnesserefactor.FitnesseRefactor.java
private void deleteColBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteColBtnActionPerformed if (ParentFolder.isSelected()) { if (!"".equals(JtreePath)) { File dir = new File(JtreePath); try { if (dir.getParent() != null && dir.isFile()) { String Testcase = dir.getParent(); File dir1 = new File(Testcase); if (dir1.getParent() != null && dir1.isDirectory()) { String parent = dir1.getParent(); File dir2 = new File(Testcase); if (dir2.getParent() != null) { String GrandParent = dir2.getParent(); File dir3 = new File(GrandParent); File[] allFiles = dir3.listFiles(); ArrayList al = new ArrayList(); for (File file : allFiles) { String TestcaseNames = file.getName(); al.add(TestcaseNames); }/*from w w w . j a va 2 s . c om*/ if (!fromTxt.getText().isEmpty() && !toTxt.getText().isEmpty()) { int FromTxtInt = Integer.parseInt(fromTxt.getText()); int ToTxtInt = Integer.parseInt(toTxt.getText()); int TotFiles = al.size(); if ((ToTxtInt > FromTxtInt) && (ToTxtInt > 0) && (FromTxtInt > 0) && ToTxtInt <= al.size() - 2) { for (int removeAfterToIndx = (ToTxtInt + 2); removeAfterToIndx < TotFiles; removeAfterToIndx++) { al.remove(ToTxtInt + 2); } if (FromTxtInt > 1) { for (int removeFromIndx = 1; removeFromIndx < FromTxtInt; removeFromIndx++) { al.remove(2); } } } else { JOptionPane.showMessageDialog(null, "FROM test case number cannot be greater/equal to TO test case number.\nFROM and TO test case numbers should be greater than zero. \nTO test case number should not be greater than the testcase count ", "Warning", JOptionPane.WARNING_MESSAGE); } } for (int i = 2; i <= al.size(); i++) { System.out.println(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); File EachFile = new File(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); for (int j = 0; j < FileUtils.readLines(EachFile).size(); j++) { String line = (String) FileUtils.readLines(EachFile).get(j); if (line.matches("(.*)" + FitnesseTablesList.getSelectedItem().toString() + "(.*)")) { p = j; ReadAllLines(EachFile); int linNum = CountLines(EachFile); DeleteColumn(EachFile, Integer.parseInt(ColumnField.getText())); int DelColsLen = DeletedSubLines.size(); int tblIndex = 1; for (int SetNew = 0; SetNew < DelColsLen; SetNew++) { AllLines.set(p + tblIndex, DeletedSubLines.get(SetNew).toString()); tblIndex = tblIndex + 1; } WriteAllLines(EachFile); } } } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Need to select atleast one content.txt file", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (Exception E) { //JOptionPane.showMessageDialog(null, E, "Java Runtime Error", JOptionPane.ERROR ); } } } }
From source file:fitnesserefactor.FitnesseRefactor.java
private void ReplaceAllBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReplaceAllBtnActionPerformed if (ParentFolder1.isSelected()) { if (!"".equals(JtreePath)) { File dir = new File(JtreePath); try { if (dir.getParent() != null && dir.isFile()) { String Testcase = dir.getParent(); File dir1 = new File(Testcase); if (dir1.getParent() != null && dir1.isDirectory()) { String parent = dir1.getParent(); File dir2 = new File(Testcase); if (dir2.getParent() != null) { String GrandParent = dir2.getParent(); File dir3 = new File(GrandParent); File[] allFiles = dir3.listFiles(); ArrayList al = new ArrayList(); for (File file : allFiles) { String TestcaseNames = file.getName(); al.add(TestcaseNames); }//from w ww .j a v a 2 s . c o m if (!fromTxt.getText().isEmpty() && !toTxt.getText().isEmpty()) { int FromTxtInt = Integer.parseInt(fromTxt.getText()); int ToTxtInt = Integer.parseInt(toTxt.getText()); int TotFiles = al.size(); if ((ToTxtInt > FromTxtInt) && (ToTxtInt > 0) && (FromTxtInt > 0) && ToTxtInt <= al.size() - 2) { for (int removeAfterToIndx = (ToTxtInt + 2); removeAfterToIndx < TotFiles; removeAfterToIndx++) { al.remove(ToTxtInt + 2); } if (FromTxtInt > 1) { for (int removeFromIndx = 1; removeFromIndx < FromTxtInt; removeFromIndx++) { al.remove(2); } } } else { JOptionPane.showMessageDialog(null, "FROM test case number cannot be greater/equal to TO test case number.\nFROM and TO test case numbers should be greater than zero. \nTO test case number should not be greater than the testcase count ", "Warning", JOptionPane.WARNING_MESSAGE); } } for (int i = 2; i <= al.size(); i++) { System.out.println(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); File EachFile = new File(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); for (int j = 0; j < FileUtils.readLines(EachFile).size(); j++) { String line = (String) FileUtils.readLines(EachFile).get(j); if (line.matches("(.*)" + FitnesseTablesList.getSelectedItem().toString() + "(.*)")) { p = j; ReplacedLines = new ArrayList(); ReadAllLines(EachFile); getTable(EachFile); int SelectedTable = getTable(EachFile).size(); for (int RepLines = 0; RepLines < SelectedTable; RepLines++) { ReplaceValue(EachFile, getTable(EachFile).get(RepLines).toString()); } int c = 0; for (int Replace = p; Replace < SelectedTable + p; Replace++) { AllLines.set(Replace, ReplacedLines.get(c)); c++; } WriteAllLines(EachFile); } } } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Need to select atleast one content.txt file", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (Exception E) { //JOptionPane.showMessageDialog(null, E, "Java Runtime Error", JOptionPane.ERROR ); } } } }
From source file:com.piketec.jenkins.plugins.tpt.TptPluginMasterJobExecutor.java
private boolean executeOneConfig(JenkinsConfiguration ec, TptApi api) throws InterruptedException { if (!ec.isEnableTest()) { return true; }/* w w w . j ava 2s .c om*/ Collection<String> testCases = null; ExecutionConfiguration executionConfig; String testdataDir = Utils.getGeneratedTestDataDir(ec); FilePath testDataPath = new FilePath(build.getWorkspace(), testdataDir); String reportDir = Utils.getGeneratedReportDir(ec); FilePath reportPath = new FilePath(build.getWorkspace(), reportDir); try { logger.info("Create and/or clean test data directory \"" + testDataPath.getRemote() + "\""); testDataPath.mkdirs(); Utils.deleteFiles(testDataPath); logger.info("Create and/or clean report directory \"" + reportPath.getRemote() + "\""); reportPath.mkdirs(); reportPath.deleteContents(); if (!StringUtils.isBlank(jUnitXmlPath)) { FilePath path = new FilePath(build.getWorkspace(), jUnitXmlPath); logger.info("Create and/or clear JUnit XML directory " + path.getRemote()); path.mkdirs(); path.deleteContents(); } } catch (IOException e) { logger.error("Could not create or clear directories on master: " + e.getMessage()); return false; } OpenResult openProject; try { openProject = api.openProject(new File(ec.getTptFile())); if (openProject.getProject() == null) { logger.error("Could not open project:\n" + Utils.toString(openProject.getLogs(), "\n")); return false; } new CleanUpTask(openProject.getProject(), build); executionConfig = getExecutionConfigByName(openProject.getProject(), ec.getConfiguration()); if (executionConfig == null) { logger.error("Could not find config"); return false; } if (StringUtils.isNotEmpty(ec.getTestSet())) { boolean testSetFound = false; for (TestSet definedTestset : openProject.getProject().getTestSets().getItems()) { if (definedTestset.getName().equals(ec.getTestSet())) { testSetFound = true; testCases = new ArrayList<>(); for (Scenario testcase : definedTestset.getTestCases().getItems()) { testCases.add(testcase.getName()); } break; } } if (!testSetFound) { logger.error("Could not find test set \"" + ec.getTestSet() + "\""); return false; } } else { testCases = getTestCaseNames(executionConfig); } } catch (RemoteException e) { logger.error(e.getMessage()); return false; } catch (ApiException e) { logger.error(e.getMessage()); return false; } // check if found test cases to execute if (testCases == null || testCases.isEmpty()) { logger.error( "No test cases are found to execute. It is possible that \"selected Test Cases \" is configured as test set. If so please change it to another existing test set"); return false; } ArrayList<RetryableJob> retryableJobs = new ArrayList<>(); // create test sets for slave jobs int slaveJobSize; int remainer; if (slaveJobCount > 1) { slaveJobSize = testCases.size() / slaveJobCount; remainer = testCases.size() % slaveJobCount; } else { slaveJobSize = testCases.size(); remainer = 0; } ArrayList<List<String>> subTestSets = getSubTestSets(testCases, slaveJobSize, remainer); // start one job for every test set Job slaveJob = null; Jenkins jenkinsInstance = Jenkins.getInstance(); if (jenkinsInstance == null) { logger.error("No jenkins instance found"); return false; } for (Job j : jenkinsInstance.getAllItems(Job.class)) { if (j.getName().equals(slaveJobName)) { slaveJob = j; } } if (slaveJob == null) { logger.error("Slave Job \"" + slaveJobName + "\" not found"); return false; } for (List<String> subTestSet : subTestSets) { logger.info("Create job for \"" + subTestSet + "\""); // creates the workloads for the slaves, with the smaller chunks of testsets WorkLoad workloadToAdd = new WorkLoad(ec.getTptFile(), ec.getConfiguration(), testdataDir, reportDir, ec.getTestSet(), subTestSet, build.getWorkspace(), build); // it adds the workloads to an static HashMap. WorkLoad.putWorkLoad(slaveJobName, workloadToAdd); // Creates a retryable job , there are the builds scheduled. So the logic is : We put a // workload in a static HashMap and then we trigger a build for a slave. In that way we are // distributing the builds on the slaves. RetryableJob retryableJob = new RetryableJob(slaveJobTries, logger, slaveJob); retryableJob.perform(build, listener); retryableJobs.add(retryableJob); } logger.info("Waiting for completion of child jobs."); for (RetryableJob retryableJob : retryableJobs) { try { retryableJob.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.interrupt(e.getMessage()); logger.info("Stopping slave jobs."); for (RetryableJob retryableJobToCancle : retryableJobs) { retryableJobToCancle.cancel(); } return false; } } // now combine the reports of the different test executions try { File oldTestDataFile = executionConfig.getDataDir(); File oldReportDir = executionConfig.getReportDir(); executionConfig.setDataDir(new File(testDataPath.getRemote())); executionConfig.setReportDir(new File(reportPath.getRemote())); // set explicit defined test set for all items ArrayList<TestSet> oldTestSets = new ArrayList<>(); if (StringUtils.isNotEmpty(ec.getTestSet())) { RemoteCollection<TestSet> allTestSets = openProject.getProject().getTestSets(); TestSet newTestSet = null; for (TestSet t : allTestSets.getItems()) { if (t.getName().equals(ec.getTestSet())) { newTestSet = t; } } if (newTestSet == null) { logger.error("Test set \"" + ec.getTestSet() + "\" not found."); return false; } for (ExecutionConfigurationItem item : executionConfig.getItems()) { oldTestSets.add(item.getTestSet()); item.setTestSet(newTestSet); } } ExecutionStatus execStatus = api.reGenerateOverviewReport(executionConfig); while (execStatus.isRunning() || execStatus.isPending()) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); execStatus.cancel(); return false; } } executionConfig.setDataDir(oldTestDataFile); executionConfig.setReportDir(oldReportDir); // reset test sets to old values if (StringUtils.isNotEmpty(ec.getTestSet())) { for (ExecutionConfigurationItem item : executionConfig.getItems()) { item.setTestSet(oldTestSets.remove(0)); } } int foundTestData = 0; if (enableJunit) { foundTestData = Utils.publishAsJUnitResults(build.getWorkspace(), ec, testDataPath, jUnitXmlPath, jUnitLogLevel, logger); } else { try { foundTestData = Publish.getTestcases(testDataPath, logger).size(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.interrupt("Interrupted while parsing the \"test_summary.xml\" of the testcases."); return false; } } if (foundTestData != testCases.size()) { logger.error("Found only " + foundTestData + " of " + testCases.size() + " test results."); return false; } } catch (RemoteException e) { logger.error(e.getMessage()); return false; } catch (ApiException e) { logger.error(e.getMessage()); return false; } catch (IOException e) { logger.error("Could not publish result: " + e.getMessage()); return false; } TPTBuildStepEntries.addEntry(ec, build); return true; }
From source file:fitnesserefactor.FitnesseRefactor.java
private void AddTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddTableActionPerformed ProgressBar.setValue(0);//from w w w . j a va 2s . c o m ProgressBar.setMinimum(0); if (ParentFolder.isSelected()) { if (!"".equals(JtreePath)) { File dir = new File(JtreePath); try { if (dir.getParent() != null && dir.isFile()) { String Testcase = dir.getParent(); File dir1 = new File(Testcase); if (dir1.getParent() != null && dir1.isDirectory()) { String parent = dir1.getParent(); File dir2 = new File(Testcase); if (dir2.getParent() != null) { String GrandParent = dir2.getParent(); File dir3 = new File(GrandParent); File[] allFiles = dir3.listFiles(); ArrayList al = new ArrayList(); for (File file : allFiles) { String TestcaseNames = file.getName(); al.add(TestcaseNames); } if (!fromTxt.getText().isEmpty() && !toTxt.getText().isEmpty()) { int FromTxtInt = Integer.parseInt(fromTxt.getText()); int ToTxtInt = Integer.parseInt(toTxt.getText()); int TotFiles = al.size(); if ((ToTxtInt > FromTxtInt) && (ToTxtInt > 0) && (FromTxtInt > 0) && ToTxtInt <= al.size() - 2) { for (int removeAfterToIndx = (ToTxtInt + 2); removeAfterToIndx < TotFiles; removeAfterToIndx++) { al.remove(ToTxtInt + 2); } if (FromTxtInt > 1) { for (int removeFromIndx = 1; removeFromIndx < FromTxtInt; removeFromIndx++) { al.remove(2); } } } else { JOptionPane.showMessageDialog(null, "FROM test case number cannot be greater/equal to TO test case number.\nFROM and TO test case numbers should be greater than zero. \nTO test case number should not be greater than the testcase count ", "Warning", JOptionPane.WARNING_MESSAGE); } } ProgressBar.setMaximum(al.size() - 2); //ProgressBar.setValue(5); int progressCount = 0; for (int i = 2; i <= al.size(); i++) { System.out.println(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); File EachFile = new File(dir2.getParent() + "\\" + al.get(i) + "\\content.txt"); for (int j = 0; j < FileUtils.readLines(EachFile).size(); j++) { String line = (String) FileUtils.readLines(EachFile).get(j); if (line.matches("(.*)" + FitnesseTablesList.getSelectedItem().toString() + "(.*)")) { p = j; ReadAllLines(EachFile); int linNum = CountLines(EachFile); int selectTableSize = SizeOfTable(EachFile); AddTable(); int AddedLinesLen = AddedLines.size(); int tblIndex = 1; for (int SetNewLines = 0; SetNewLines < AddedLinesLen; SetNewLines++) { AllLines.add(p + selectTableSize + tblIndex, AddedLines.get(SetNewLines).toString()); tblIndex = tblIndex + 1; } AllLines.add(p + selectTableSize + tblIndex, ""); WriteAllLines(EachFile); break; } else if (line.matches("(.*)" + FitnesseTablesList.getItemAt(1) + "(.*)") && FitnesseTablesList.getSelectedItem().toString() .contains("Select an item")) { p = j; int r = p; ReadAllLines(EachFile); AddTable(); int AddedLinesLen = AddedLines.size(); for (int SetNewLines = 0; SetNewLines < AddedLinesLen; SetNewLines++) { AllLines.add(r, AddedLines.get(SetNewLines).toString()); r = r + 1; } AllLines.add(r, ""); WriteAllLines(EachFile); break; } } progressCount = progressCount + 1; ProgressBar.setValue(progressCount); } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "There are no testcases under the parent folder", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Need to select atleast one content.txt file", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (Exception E) { //JOptionPane.showMessageDialog(null, E, "Java Runtime Error", JOptionPane.ERROR ); } } } }