List of usage examples for java.util LinkedList indexOf
public int indexOf(Object o)
From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkProfile.java
private boolean addItem(LinkedList<ItemInfo> items, ItemInfo itemInfo) { boolean added = false; int idx = items.indexOf(itemInfo); if (idx != -1) { // HACK: Always swap existing ItemInfos with our new one, since it will // more up-to-date information ItemInfo existing = items.set(idx, itemInfo); assert (existing != null); return (true); }// w w w .ja v a 2s .co m if (itemInfo.hasCurrentPrice()) assert (itemInfo.getCurrentPrice() > 0) : "Negative current price for " + itemInfo; // If we have room, shove it right in // We'll throw it in the back because we know it hasn't been used yet if (items.size() < AuctionMarkConstants.ITEM_ID_CACHE_SIZE) { items.addLast(itemInfo); added = true; // Otherwise, we can will randomly decide whether to pop one out } else if (this.rng.nextBoolean()) { items.pop(); items.addLast(itemInfo); added = true; } return (added); }
From source file:org.micromanager.plugins.magellan.surfacesandregions.SurfaceInterpolatorSimple.java
@Override public float getExtrapolatedValue(double x, double y) { //duplicate points for thread safety final LinkedList<Point3d> points = new LinkedList<Point3d>(points_); //find 3 closest points and calculate value //find closest convex hull vertex final LinkedList<Integer> closestIndices = new LinkedList<Integer>(); final LinkedList<Double> closestDistances = new LinkedList<Double>(); for (int i = 0; i < points.size(); i++) { //get current distance Vector2D vertex = new Vector2D(points.get(i).x, points.get(i).y); double distance = vertex.distance(new Vector2D(x, y)); if (closestDistances.size() < 3) { closestIndices.add(i);/*from w w w .jav a 2 s . co m*/ closestDistances.add(distance); } else if (distance < closestDistances.get(2)) { closestIndices.removeLast(); closestDistances.removeLast(); closestIndices.add(i); closestDistances.add(distance); } //sort Collections.sort(closestIndices, new Comparator<Integer>() { public int compare(Integer left, Integer right) { return (new Double(closestDistances.get(closestIndices.indexOf(left)))) .compareTo(closestDistances.get(closestIndices.indexOf(right))); } }); Collections.sort(closestDistances); } Point3d point1 = points.get(closestIndices.get(0)); Point3d point2 = points.get(closestIndices.get(1)); Point3d point3 = points.get(closestIndices.get(2)); Vector3D v1 = new Vector3D(point1.x, point1.y, point1.z); Vector3D v2 = new Vector3D(point2.x, point2.y, point2.z); Vector3D v3 = new Vector3D(point3.x, point3.y, point3.z); Plane plane = new Plane(v1, v2, v3, TOLERANCE); //intersetion of vertical line at these x+y values with plane gives point in plane Vector3D pointInPlane = plane .intersection(new Line(new Vector3D(x, y, 0), new Vector3D(x, y, 1), TOLERANCE)); float zVal = (float) pointInPlane.getZ(); return zVal; }
From source file:com.commander4j.util.JUtility.java
public static String getTimeStampStringFormat(Timestamp ts, String fmt) { String result = ""; LinkedList<String> fmtList = new LinkedList<String>(); LinkedList<String> valList = new LinkedList<String>(); fmtList.clear();/*from ww w .ja v a 2 s.c o m*/ valList.clear(); result = ts.toString(); fmtList.add("yyyy"); valList.add(result.substring(0, 4)); fmtList.add("yy"); valList.add(result.substring(2, 4)); fmtList.add("mm"); valList.add(result.substring(5, 7)); fmtList.add("dd"); valList.add(result.substring(8, 10)); fmtList.add("hh"); valList.add(result.substring(11, 13)); fmtList.add("mi"); valList.add(result.substring(14, 16)); fmtList.add("ss"); valList.add(result.substring(17, 19)); fmtList.add("yymmdd"); valList.add(result.substring(2, 4) + result.substring(5, 7) + result.substring(8, 10)); int pos = fmtList.indexOf(fmt); if (pos >= 0) { result = valList.get(pos); } else { result = ""; } return result; }
From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java
private void testingForLogFilesFromEachLogFolderAndFillInfo(LinkedList<LogFolderInfo> tmpLogFolderList) { long timeF1 = System.currentTimeMillis(); Object[] objArray = new Object[gui.logFolderList.myModel.size()]; gui.logFolderList.myModel.copyInto(objArray); for (Object comp : objArray) { if (stopLogListProcessing) break; try {// www . jav a2 s.co m LogFolderInfo logFolder = (LogFolderInfo) comp; int indexLFolder = tmpLogFolderList.indexOf(logFolder); LinkedHashSet<LogFileInfo> logFilesTmp = (indexLFolder != -1) ? tmpLogFolderList.get(indexLFolder).getLogFiles() : new LinkedHashSet<LogFileInfo>(); for (LogFileInfo logFx : logFilesTmp) { if (stopLogListProcessing) break; if (!logFolder.getLogFiles().contains(logFx)) { // The file or directory is new logFolder.addFile(logFx); } else { // The file or directory is already known so let us update LogFileInfo lfx = logFolder.getLogFile(logFx.getName()/* fxStr */); if (lfx.getSize() == -1) { lfx.setSize(logFx.getSize()); } else if (lfx.getSize() != logFx.getSize()) { // System.out.println("//////////// " + lfx.getSize() + " " + logFx.getSize()); if (lfx.getState() == LogFolderInfo.State.SYNC) lfx.setState(LogFolderInfo.State.INCOMPLETE); else if (lfx.getState() == LogFolderInfo.State.LOCAL) lfx.setState(LogFolderInfo.State.INCOMPLETE); lfx.setSize(logFx.getSize()); lfx.setFile(logFx.getFile()); } else if (lfx.getSize() == logFx.getSize()) { if (lfx.getState() == LogFolderInfo.State.LOCAL) lfx.setState(LogFolderInfo.State.SYNC); } lfx.setHost(logFx.getHost()); if (logFx.isDirectory()) { ArrayList<LogFileInfo> notMatchElements = new ArrayList<>(); notMatchElements.addAll(lfx.getDirectoryContents()); for (LogFileInfo lfi : logFx.getDirectoryContents()) { boolean alreadyExists = false; for (LogFileInfo lfiLocal : lfx.getDirectoryContents()) { if (lfi.equals(lfiLocal)) { alreadyExists = true; notMatchElements.remove(lfiLocal); lfi.setSize(lfiLocal.getSize()); lfi.setFile(lfiLocal.getFile()); lfi.setHost(lfiLocal.getHost()); } } if (!alreadyExists) { lfx.getDirectoryContents().add(lfi); lfx.setState(LogFolderInfo.State.INCOMPLETE); } } for (LogFileInfo lfi : notMatchElements) { lfx.getDirectoryContents().remove(lfi); } } if (lfx.isDirectory()) { if (!LogsDownloaderWorkerUtil.getFileTarget(lfx.getName(), worker.getDirBaseToStoreFiles(), worker.getLogLabel()).exists()) { for (LogFileInfo lfi : lfx.getDirectoryContents()) { if (!LogsDownloaderWorkerUtil.getFileTarget(lfi.getName(), worker.getDirBaseToStoreFiles(), worker.getLogLabel()).exists()) { if (lfx.getState() != LogFolderInfo.State.NEW && lfx.getState() != LogFolderInfo.State.DOWNLOADING) lfx.setState(LogFolderInfo.State.INCOMPLETE); break; } } } else { long sizeD = LogsDownloaderWorkerUtil.getDiskSizeFromLocal(lfx, worker); if (lfx.getSize() != sizeD && lfx.getState() == LogFolderInfo.State.SYNC) lfx.setState(LogFolderInfo.State.INCOMPLETE); } } else { if (!LogsDownloaderWorkerUtil.getFileTarget(lfx.getName(), worker.getDirBaseToStoreFiles(), worker.getLogLabel()).exists()) { if (lfx.getState() != LogFolderInfo.State.NEW && lfx.getState() != LogFolderInfo.State.DOWNLOADING) { lfx.setState(LogFolderInfo.State.INCOMPLETE); // System.out.println("//////////// " + lfx.getName() + " " + LogsDownloaderUtil.getFileTarget(lfx.getName()).exists()); } } else { long sizeD = LogsDownloaderWorkerUtil.getDiskSizeFromLocal(lfx, worker); if (lfx.getSize() != sizeD && lfx.getState() == LogFolderInfo.State.SYNC) lfx.setState(LogFolderInfo.State.INCOMPLETE); } } } } // Put LOCAL state on files not in server LinkedHashSet<LogFileInfo> toDelFL = new LinkedHashSet<LogFileInfo>(); for (LogFileInfo lfx : logFolder.getLogFiles()) { if (!logFilesTmp.contains(lfx) /* !res.keySet().contains(lfx.getName()) */) { lfx.setState(LogFolderInfo.State.LOCAL); if (!LogsDownloaderWorkerUtil .getFileTarget(lfx.getName(), worker.getDirBaseToStoreFiles(), worker.getLogLabel()) .exists()) { toDelFL.add(lfx); // logFolder.getLogFiles().remove(lfx); //This cannot be done here } } } for (LogFileInfo lfx : toDelFL) logFolder.getLogFiles().remove(lfx); } catch (Exception e) { NeptusLog.pub().debug(e.getMessage()); } } NeptusLog.pub().warn(".......Testing for log files from each log folder " + (System.currentTimeMillis() - timeF1) + "ms"); }
From source file:org.bibsonomy.webapp.controller.MySearchController.java
private void buildRelationTables(ListCommand<Post<BibTex>> bibtex, MySearchCommand command) { /**/*www. j a v a 2s.co m*/ * containers for relation tables */ final LinkedList<String> titleList = command.getTitles(); final LinkedList<String> tagList = command.getTags(); final LinkedList<String> authorList = command.getAuthors(); /** * sorted lists for several relations */ SortedSet<Integer>[] tagTitle = new TreeSet[tagList.size()]; SortedSet<Integer>[] authorTitle = new TreeSet[authorList.size()]; SortedSet<Integer>[] tagAuthor = new TreeSet[tagList.size()]; SortedSet<Integer>[] titleAuthor = new TreeSet[titleList.size()]; /** * string arrays for hash and url informations for the several bibtex */ String[] bibtexHashs = new String[titleList.size()]; String[] bibtexUrls = new String[titleList.size()]; /** * build the relations from the bibtex informations */ for (Post<BibTex> bibtexEntry : bibtex.getList()) { // read values from resultset String title = bibtexEntry.getResource().getTitle().replaceAll("\\n|\\r", ""); Set<Tag> tags = bibtexEntry.getTags(); String hash = bibtexEntry.getResource().getSimHash2(); String url = bibtexEntry.getResource().getUrl(); String author = buildAuthorsAndEditors(bibtexEntry.getResource().getAuthor(), bibtexEntry.getResource().getEditor()); // tag --> title relation for (Tag tag : tags) { if (tagTitle[tagList.indexOf(tag.getName())] == null) { SortedSet<Integer> v = new TreeSet<Integer>(); v.add(titleList.indexOf(title)); tagTitle[tagList.indexOf(tag.getName())] = v; } else { tagTitle[tagList.indexOf(tag.getName())].add(titleList.indexOf(title)); } } // author --> title relation List<String> authorsLastNames = extractAuthorsLastNames(author); for (String name : authorsLastNames) { if (authorTitle[authorList.indexOf(name)] == null) { SortedSet<Integer> v = new TreeSet<Integer>(); v.add(titleList.indexOf(title)); authorTitle[authorList.indexOf(name)] = v; } else { authorTitle[authorList.indexOf(name)].add(titleList.indexOf(title)); } } // tag --> author relation for (Tag tag : tags) { if (tagAuthor[tagList.indexOf(tag.getName())] == null) { SortedSet<Integer> v = new TreeSet<Integer>(); for (String name : authorsLastNames) { v.add(authorList.indexOf(name)); } tagAuthor[tagList.indexOf(tag.getName())] = v; } else { for (String name : authorsLastNames) { tagAuthor[tagList.indexOf(tag.getName())].add(authorList.indexOf(name)); } } } // title --> author relation if (titleAuthor[titleList.indexOf(title)] == null) { SortedSet<Integer> v = new TreeSet<Integer>(); for (String name : authorsLastNames) { v.add(authorList.indexOf(name)); } titleAuthor[titleList.indexOf(title)] = v; } else { for (String name : authorsLastNames) { titleAuthor[titleList.indexOf(title)].add(authorList.indexOf(name)); } } // BibTeX-Hashtable bibtexHashs[titleList.indexOf(title)] = hash; // Urls bibtexUrls[titleList.indexOf(title)] = url; } /** * store relation tables in the command object */ command.setTagTitle(tagTitle); command.setAuthorTitle(authorTitle); command.setTagAuthor(tagAuthor); command.setTitleAuthor(titleAuthor); command.setBibtexHash(bibtexHashs); command.setBibtexUrls(bibtexUrls); /** * simhash is needed by the javascript code in the mySearch.jspx side to * complete the bibtex hash string */ command.setSimHash(HashID.getSimHash(2).getId()); }
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 */// ww w. j a v a2 s. c o 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:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java
public LinkedList<AZoFTPFile> download(LinkedList<AZoFTPFile> afs, LocalStorage localStorage) { if (afs.size() <= 0) { return afs; }/* ww w .j a va 2 s .com*/ LinkedList<AZoFTPFile> retval = new LinkedList<>(); /* for (AZoFTPFile a : afs) { retval.add(a); }*/ Collections.sort(afs, new Comparator<AZoFTPFile>() { @Override public int compare(AZoFTPFile o1, AZoFTPFile o2) { return o1.ftpFile.getTimestamp().compareTo(o2.ftpFile.getTimestamp()); } }); simplyConnect(FTP.BINARY_FILE_TYPE); notify(FTPConnectionStatus.CONNECTED, getLastWorkingConnection(), -1); if (afs.size() > 0) { AZoFTPFile af = afs.getFirst();//) { File localFile = null; try { localFile = localStorage.getLocalFile(af); } catch (IOException ex) { notify(FTPConnectionStatus.LOCALSTORAGEERROR, af.dir + af.ftpFile.getName(), -1); close(); return retval; } if (!localStorage.prepareLocalFile(localFile)) { notify(FTPConnectionStatus.LOCALSTORAGEERROR, af.dir + af.ftpFile.getName(), -1); close(); return retval; } FileOutputStream fos = null; InputStream is = null; try { fos = new FileOutputStream(localFile); ftpclient.setSoTimeout(LONG_TIMEOUT); is = ftpclient.retrieveFileStream(af.dir + af.ftpFile.getName()); cis = new CountingInputStream(is); downloadsize = af.ftpFile.getSize(); notify(FTPConnectionStatus.DOWNLOADING, af.dir + af.ftpFile.getName(), ((int) (100.0 * ((afs.indexOf(af) + 1.0) / (double) afs.size())))); // ftpclient.setDataTimeout(TIMEOUT); // ftpclient.setSoTimeout(TIMEOUT); // Files.copy(cis, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING); try { IOUtils.copyLarge(cis, fos); } catch (Exception ie) { fos.close(); is.close(); } while (!ftpclient.completePendingCommand()) { try { Thread.currentThread().wait(500); } catch (InterruptedException ex) { Logger.getLogger(FTPConnection.class.getName()).log(Level.SEVERE, null, ex); } } ; is.close(); fos.close(); localStorage.setLatestIncoming(localFile); localStorage.addSyncedFile(af); notify(FTPConnectionStatus.NEW_LOCAL_FILE, localFile.getAbsolutePath(), -1); retval.add(af); notify(FTPConnectionStatus.SUCCESS, af.dir + af.ftpFile.getName(), ((int) (100.0 * ((afs.indexOf(af) + 2.0) / (double) afs.size())))); } catch (Exception ex) { try { is.close(); fos.close(); close(); localFile.delete(); simplyConnect(FTP.BINARY_FILE_TYPE); } catch (Exception ex2) { close(); } } } close(); return retval; }
From source file:au.edu.ausstage.networks.LookupManager.java
/** * A method to lookup the key collaborators for a contributor * * @param id the unique id of the contributor * @param formatType the required format of the data * @param sortType the required way in which the data is to be sorted * * @return the results of the lookup */// ww w.ja va2 s .c o m public String getKeyCollaborators(String id, String formatType, String sortType) { // check on the parameters if (InputUtils.isValidInt(id) == false || InputUtils.isValid(formatType) == false || InputUtils.isValid(sortType) == false) { throw new IllegalArgumentException("All parameters to 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; // define the base sparql query String sparqlQuery = "PREFIX foaf: <" + FOAF.NS + ">" + "PREFIX ausestage: <" + AuseStage.NS + "> " + "SELECT ?collaborator ?collabGivenName ?collabFamilyName ?function ?firstDate ?lastDate ?collabCount " + "WHERE { " + " @ a foaf:Person ; " + " ausestage:hasCollaboration ?collaboration. " + " ?collaboration ausestage:collaborator ?collaborator; " + " ausestage:collaborationFirstDate ?firstDate; " + " ausestage:collaborationLastDate ?lastDate; " + " ausestage:collaborationCount ?collabCount. " + " ?collaborator foaf:givenName ?collabGivenName; " + " foaf:familyName ?collabFamilyName; " + " ausestage:function ?function. " + " FILTER (?collaborator != @) " + "}"; // do we need to sort by name? if (sortType.equals("count") == true) { sparqlQuery += " ORDER BY DESC(?collabCount)"; } else if (sortType.equals("name") == true) { sparqlQuery += " ORDER BY ?collabFamilyName ?collabGivenName"; } // build a URI from the id id = AusStageURI.getContributorURI(id); // add the contributor URI to the query sparqlQuery = sparqlQuery.replaceAll("@", "<" + id + ">"); // execute the query ResultSet results = rdf.executeSparqlQuery(sparqlQuery); // build the dataset // use a numeric sort order while (results.hasNext()) { // 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 // get the name collaborator.setGivenName(row.get("collabGivenName").toString()); collaborator.setFamilyName(row.get("collabFamilyName").toString(), true); // get the dates collaborator.setFirstDate(row.get("firstDate").toString()); collaborator.setLastDate(row.get("lastDate").toString()); // get the collaboration count collaborator.setCollaborations(Integer.toString(row.get("collabCount").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); } } // play nice and tidy up rdf.tidyUp(); // sort by the id if (sortType.equals("id") == true) { TreeMap<Integer, Collaborator> collaboratorsToSort = new TreeMap<Integer, Collaborator>(); for (int i = 0; i < collaborators.size(); i++) { collaborator = collaborator = collaborators.get(i); collaboratorsToSort.put(Integer.parseInt(collaborator.getId()), collaborator); } // empty the list collaborators.clear(); // add the collaborators back to the list Collection values = collaboratorsToSort.values(); Iterator iterator = values.iterator(); while (iterator.hasNext()) { // get the collaborator collaborator = (Collaborator) iterator.next(); collaborators.add(collaborator); } collaboratorsToSort = null; } // 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:org.eclipse.birt.report.model.writer.ModuleWriterImpl.java
/** * Writes the contents of a slot. The order is not the order in the slot * while we first write the ancestor and then the derived ones. The contents * are enclosed in an optional list tag. * /*from w w w .j av a2 s.c om*/ * @param obj * the container element * @param slot * the slot to write * @param tag * the optional list tag that encloses the list of contents */ protected void writeArrangedContents(DesignElement obj, int slot, String tag) { List<DesignElement> list = obj.getSlot(slot).getContents(); if (list.isEmpty()) return; LinkedList<DesignElement> newList = new LinkedList<DesignElement>(); Iterator<DesignElement> iter = list.iterator(); while (iter.hasNext()) { DesignElement element = iter.next(); DesignElement parent = element.getExtendsElement(); if (!newList.contains(element)) { newList.add(element); } if (parent != null && list.contains(parent)) { if (!newList.contains(parent)) { int index = newList.indexOf(element); newList.add(index, parent); } else if (newList.indexOf(element) < newList.indexOf(parent)) { newList.remove(parent); int index = newList.indexOf(element); newList.add(index, parent); } } } if (tag != null) writer.conditionalStartElement(tag); // Iterate over the contents using this visitor to write each one. // Note that this may result in a recursive call back into this // method as we do a depth-first traversal of the design tree. iter = newList.iterator(); while (iter.hasNext()) { (iter.next()).apply(this); } if (tag != null) writer.endElement(); }
From source file:com.nest5.businessClient.Initialactivity.java
@Override public void OnOrderClicked(int isDelivery, int isTogo, String note) { // al guardar lo que hace es que guarda un objeto Sale con fecha, metodo // de pago y valor recibido. // despues toma currentOrder y dic saveItem(Context mContext,int type, // long item_id, double qty) para cada uno // al recuperar un sale se hace // price = 0.0; Date date = new Date(); String fecha = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(date); //String fecha = DateFormat.getDateFormat(Initialactivity.this).format( //date);//from w ww . j ava 2s . co m // imprimir, conectar por wifi y enviar el texto arregladito a la app de // puente String mesa = "-DOMICILIO / PARA LLEVAR- O -MESA NO REGISTRADA-"; if (currentTable != null) { mesa = currentTable.getTable().getName().toUpperCase(Locale.getDefault()); } int lines = 0; StringBuilder factura = new StringBuilder(); String newline = "\r\n"; String title = "-----COMANDA----COMANDA-----" + "\r\n"; String tableheader = " Item Cantidad\r\n"; String notas = "NOTAS\r\n"; factura.append(title); factura.append(mesa + "\r\n"); lines++; factura.append(fecha); lines++; lines++; lines++; factura.append(newline); factura.append(tableheader); lines++; int j = 0; LinkedList<String> productos = new LinkedList<String>(); LinkedList<Integer> quantities = new LinkedList<Integer>(); LinkedList<Double> precios = new LinkedList<Double>(); Iterator<Entry<Registrable, Integer>> it = currentOrder.entrySet().iterator(); // Log.d(TAG,String.valueOf(currentOrder.size())); LinkedHashMap<Registrable, Integer> currentObjects = new LinkedHashMap<Registrable, Integer>(); while (it.hasNext()) { LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) it.next(); currentObjects.put(pairs.getKey(), pairs.getValue()); String name = pairs.getKey().name; productos.add(name); int longName = name.length(); int subLength = 14 - longName; if (subLength < 0) name = name.substring(0, 14); int espacios1 = 4; int espacios2 = 12; if (name.length() < 14) { espacios1 += 14 - name.length(); } factura.append(name); int qtyL = String.valueOf(pairs.getValue()).length(); espacios1 = espacios1 - qtyL < 1 ? espacios1 = 1 : espacios1 - qtyL; //espacios2 = espacios2 - priceL < 1 ? espacios2 = 1 : espacios2 - priceL; espacios2 = espacios2 - qtyL < 1 ? espacios2 = 1 : espacios2 - qtyL; for (int k = 0; k < espacios1; k++) { factura.append(" "); } factura.append(pairs.getValue()); quantities.add(pairs.getValue()); for (int k = 0; k < espacios2; k++) { factura.append(" "); } factura.append(newline); lines++; } factura.append(notas); factura.append(note); long startTime = System.currentTimeMillis(); if (currentSelectedAddTable > -1) {//esto significa que esta agregando la orden actual a otra existente, para la mesa que este seleccionada LinkedHashMap<Registrable, Integer> existingOrder = null; for (Map.Entry<LinkedHashMap<Registrable, Integer>, CurrentTable<Table, Integer>> tab : cookingOrdersTable .entrySet()) { if (tab.getValue().getTable().getName().equalsIgnoreCase(currentTable.getTable().getName())) { existingOrder = tab.getKey(); break; } } if (existingOrder != null) { int prevDelivery = cookingOrdersDelivery.get(existingOrder); int prevTogo = cookingOrdersTogo.get(existingOrder); Long prevTime = cookingOrdersTimes.get(existingOrder); cookingOrders.remove(existingOrder); cookingOrdersDelivery.remove(existingOrder); cookingOrdersTable.remove(existingOrder); cookingOrdersTimes.remove(existingOrder); cookingOrdersTogo.remove(existingOrder); Iterator<Entry<Registrable, Integer>> itnuevo = existingOrder.entrySet().iterator(); while (itnuevo.hasNext()) { LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) itnuevo .next(); currentObjects.put(pairs.getKey(), pairs.getValue()); } cookingOrders.add(currentObjects); cookingOrdersDelivery.put(currentObjects, prevDelivery); cookingOrdersTogo.put(currentObjects, prevTogo); cookingOrdersTimes.put(currentObjects, prevTime); cookingOrdersTable.put(currentObjects, currentTable); } } else { cookingOrders.add(currentObjects); cookingOrdersDelivery.put(currentObjects, isDelivery); cookingOrdersTogo.put(currentObjects, isTogo); cookingOrdersTimes.put(currentObjects, startTime); if (currentTable != null) { cookingOrdersTable.put(currentObjects, currentTable); openTables.push(currentTable); } else { int[] coordinates = new int[2]; coordinates[0] = 0; coordinates[1] = 0; CurrentTable<Table, Integer> tabletemp = new CurrentTable<Table, Integer>( new Table("Domicilio / Para Llevar", 1, coordinates), 1); cookingOrdersTable.put(currentObjects, tabletemp); openTables.push(tabletemp); } } List<Long> items = new ArrayList<Long>(); List<String> nameTables = new ArrayList<String>(); for (LinkedHashMap<Registrable, Integer> current : cookingOrders) { items.add(cookingOrdersTimes.get(current)); nameTables.add(cookingOrdersTable.get(current).getTable().getName()); } cookingAdapter = new SaleAdapter(mContext, items, nameTables, inflater); ordersList.setAdapter(cookingAdapter); ordersList.setOnItemClickListener(orderListListener); /*if (!isTimerRunning) { startTimer(); }*/ currentOrder.clear(); currentTable = null; statusText.setText("En Espera de Abrir mesa."); makeTable("NA"); lines++; lines++; Boolean printed = true; try { if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) { try { mChatService.write(factura.toString().getBytes("x-UnicodeBig")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { printed = false; Toast.makeText(mContext, "No hay impresora conectada.", Toast.LENGTH_LONG).show(); } } catch (NullPointerException e) { printed = false; e.printStackTrace(); } if (!printed) {//buscar impresora TCP/IP StringBuilder formateado = new StringBuilder(); formateado.append(CLEAR_PRINTER); formateado.append(INITIALIZE_PRINTER); formateado.append(JUSTIFICATION_CENTER); formateado.append(DOUBLE_WIDE_CHARACTERS); formateado.append("----COMANDA----"); formateado.append(PRINT_FEED_ONE_LINE); formateado.append(fecha); formateado.append(PRINT_FEED_ONE_LINE); formateado.append(mesa); formateado.append(PRINT_FEED_N_LINES); formateado.append((char) 0x03); formateado.append(JUSTIFICATION_LEFT); formateado.append("ITEM"); formateado.append(HORIZONTAL_TAB); formateado.append(HORIZONTAL_TAB); formateado.append(HORIZONTAL_TAB); formateado.append("CANTIDAD"); formateado.append(HORIZONTAL_TAB); formateado.append(SINGLE_WIDE_CHARACTERS); formateado.append(PRINT_FEED_ONE_LINE); for (String actual : productos) { int pos = productos.indexOf(actual); int cantidad = quantities.get(pos); formateado.append(actual); formateado.append(HORIZONTAL_TAB); formateado.append(HORIZONTAL_TAB); formateado.append(HORIZONTAL_TAB); formateado.append(cantidad); formateado.append(PRINT_FEED_ONE_LINE); } formateado.append(PRINT_FEED_N_LINES); formateado.append((char) 0x02); formateado.append(ITALIC_STYLE); formateado.append(notas); formateado.append(PRINT_FEED_ONE_LINE); formateado.append(note); formateado.append(ITALIC_CANCEL); formateado.append(FINALIZE_TICKET); formateado.append(PARTIAL_CUT); if (mTCPPrint != null) { if (mTCPPrint.getStatus() == TCPPrint.CONNECTED) { mTCPPrint.sendMessage(formateado.toString()); mTCPPrint.sendMessage(formateado.toString()); } else { mTCPPrint.stopClient(); new connectTask().execute(formateado.toString()); alertbox("Oops!", "Al Parecer no hay impresora disponible. Estamos tratando de reconectarnos e imprimir. Si no funciona, reinicia la Red o la impresora y ve a rdenes para imprimir el pedido."); } } else { alertbox("Oops!", "Al Parecer no hay impresora disponible. Trataremos en este momento de nuevo de imprimir el pedido. Si no funciona, reinicia la red o la impreso y ve a rdenes para imprimir de nuevo la orden."); new connectTask().execute(formateado.toString()); } } }