List of usage examples for java.util Collections reverse
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void reverse(List<?> list)
This method runs in linear time.
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages/*from www .j a v a 2 s .c om*/ * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:it.av.eatt.service.impl.JcrApplicationServiceJackrabbit.java
@Transactional(readOnly = true) public List<T> getAllRevisions(String path) throws JackWicketException { ArrayList<T> revisions = new ArrayList<T>(); if (StringUtils.isNotEmpty(path)) { VersionIterator versionIterator = jcrMappingtemplate.getAllRevisions(path); while (versionIterator.hasNext()) { Version version = (Version) versionIterator.next(); if (version.getName().equals("jcr:rootVersion")) { continue; }/*from w ww . j a v a2 s . co m*/ T versionObject = jcrMappingtemplate.getObjectByVersion(path, version.getName()); versionObject.setVersion(version.getName()); revisions.add(versionObject); } } //Sort to have latest release in first position Collections.reverse(revisions); return revisions; }
From source file:com.github.maoo.indexer.webscripts.NodeDetailsWebScript.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { final String serviceContextPath = req.getServerPath() + req.getServiceContextPath(); final List<String> readableAuthorities = new ArrayList<String>(); // Parsing parameters passed from the WebScript invocation Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars(); String storeId = templateArgs.get("storeId"); String storeProtocol = templateArgs.get("storeProtocol"); String uuid = templateArgs.get("uuid"); NodeRef nodeRef = new NodeRef(storeProtocol, storeId, uuid); logger.debug(/* ww w. ja v a 2 s. c om*/ String.format("Invoking ACLs Webscript, using the following params\n" + "nodeRef: %s\n", nodeRef)); // Processing properties Map<QName, Serializable> propertyMap = nodeService.getProperties(nodeRef); Map<String, Pair<String, String>> properties = toStringMap(propertyMap); // Processing aspects Set<QName> aspectsSet = nodeService.getAspects(nodeRef); Set<String> aspects = toStringSet(aspectsSet); // Processing content data ContentData contentData = (ContentData) propertyMap.get(ContentModel.PROP_CONTENT); // Get the node ACL Id Long dbId = (Long) propertyMap.get(ContentModel.PROP_NODE_DBID); Long nodeAclId = nodeDao.getNodeAclId(dbId); // Get also the inherited ones List<Acl> acls = getAllAcls(nodeAclId); // @TODO - avoid reverse by implementing direct recursion Collections.reverse(acls); // Getting path and siteName Path pathObj = nodeService.getPath(nodeRef); String path = pathObj.toPrefixString(namespaceService); String siteName = Utils.getSiteName(pathObj); // Walk through ACLs and related ACEs, rendering out authority names // having a granted permission on the node for (Acl acl : acls) { List<AccessControlEntry> aces = aclDao.getAccessControlList(acl.getId()).getEntries(); for (AccessControlEntry ace : aces) { if ((!ace.getPermission().getName().equals(BASE_READ_PERMISSIONS)) && ace.getAccessStatus().equals(AccessStatus.ALLOWED)) { if (!readableAuthorities.contains(ace.getAuthority())) { readableAuthorities.add(ace.getAuthority()); } } } } Map<String, Object> model = new HashMap<String, Object>(1, 1.0f); if (contentData != null) { model.put("mimetype", contentData.getMimetype()); model.put("size", contentData.getSize()); } model.put("nsResolver", namespaceService); model.put("readableAuthorities", readableAuthorities); model.put("properties", properties); model.put("aspects", aspects); model.put("path", path); model.put("serviceContextPath", serviceContextPath); model.put("documentUrlPrefix", documentUrlPrefix); model.put("shareUrl", shareUrl); model.put("shareUrlPrefix", shareUrlPrefix); model.put("thumbnailUrlPrefix", thumbnailUrlPrefix); model.put("previewUrlPrefix", previewUrlPrefix); String documentUrlPath = String.format("/%s/%s/%s", storeProtocol, storeId, uuid); model.put("documentUrlPath", documentUrlPath); // Calculating the contentUrlPath and adding it only if the contentType // is child of cm:content boolean isContentAware = isContentAware(nodeRef); if (isContentAware) { String contentUrlPath = String.format("/api/node/%s/%s/%s/content", storeProtocol, storeId, uuid); model.put("contentUrlPath", contentUrlPath); // Rendering out the (relative) URL path to Alfresco Share String shareUrlPath = null; if (!StringUtil.isEmpty(siteName)) { shareUrlPath = String.format("/page/site/%s/document-details?nodeRef=%s", siteName, nodeRef.toString()); } else { shareUrlPath = String.format("/page/document-details?nodeRef=%s", nodeRef.toString()); } if (shareUrlPath != null) { model.put("shareUrlPath", shareUrlPath); } } String previewUrlPath = String.format("/api/node/%s/%s/%s/content/thumbnails/webpreview", storeProtocol, storeId, uuid); model.put("previewUrlPath", previewUrlPath); String thumbnailUrlPath = String.format( "/api/node/%s/%s/%s/content/thumbnails/doclib?c=queue&ph=true&lastModified=1", storeProtocol, storeId, uuid); model.put("thumbnailUrlPath", thumbnailUrlPath); ThumbnailRegistry registry = thumbnailService.getThumbnailRegistry(); ThumbnailDefinition details = registry.getThumbnailDefinition("doclib"); try { NodeRef thumbRef = thumbnailService.getThumbnailByName(nodeRef, ContentModel.PROP_CONTENT, "doclib"); if (thumbRef == null) { thumbRef = thumbnailService.createThumbnail(nodeRef, ContentModel.PROP_CONTENT, details.getMimetype(), details.getTransformationOptions(), details.getName()); } ContentReader thumbReader = contentService.getReader(thumbRef, ContentModel.PROP_CONTENT); InputStream thumbsIs = thumbReader.getContentInputStream(); String thumbBase64 = Base64.encodeBase64String(IOUtils.toByteArray(thumbsIs)); model.put("thumbnailBase64", thumbBase64); IOUtils.closeQuietly(thumbsIs); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("It was not possible to get/build thumbnail doclib for nodeRef: " + nodeRef + ". Message: " + e.getMessage()); } // thumbnail placeholder String phPath = scriptThumbnailService.getMimeAwarePlaceHolderResourcePath("doclib", details.getMimetype()); StringBuilder sb = new StringBuilder("classpath:").append(phPath); final String classpathResource = sb.toString(); InputStream is = null; try { is = resourceLoader.getResource(classpathResource).getInputStream(); String thumbBase64 = Base64.encodeBase64String(IOUtils.toByteArray(is)); model.put("thumbnailBase64", thumbBase64); } catch (Exception e2) { if (logger.isWarnEnabled()) { logger.warn("It was not possible to get/build placeholder thumbnail doclib for nodeRef: " + nodeRef + ". Message: " + e2.getMessage()); } } finally { IOUtils.closeQuietly(is); } } model.put("contentUrlPrefix", contentUrlPrefix); return model; }
From source file:userInterface.StateAdminRole.DecisionChartJPanel.java
private PieDataset createDataset() { ArrayList<VaccineQty> temp = new ArrayList<>(); //temp = supplier.getProductCatalog().getProductCatalog(); //temp = supplier.getProductCatalog().getProductCatalog(); VaccineQty vq = null;//from w w w. java2 s .c o m Boolean flag = true; for (ClinicOrderRequest cor : e.getMasterCatalog()) { System.out.println("ORder"); for (OrderItem oi : cor.getOrder().getOrder()) { System.out.println("1st-" + oi.getProduct()); if (temp.size() == 0) { System.out.println("here 1st"); vq = new VaccineQty(); vq.setV(oi.getProduct()); vq.setQ(oi.getQuantity()); temp.add(vq); } else { for (VaccineQty vqc : temp) { System.out.println("oi-" + oi.getProduct() + " ," + "vg-" + vq.getV()); if (vqc.getV().equals(oi.getProduct())) { System.out.println("in same"); vqc.setQ(vqc.getQ() + oi.getQuantity()); flag = false; break; } } if (flag) { System.out.println("hello"); vq = new VaccineQty(); vq.setV(oi.getProduct()); vq.setQ(oi.getQuantity()); temp.add(vq); } } } } Collections.sort(temp, new Comparator<VaccineQty>() { public int compare(VaccineQty one, VaccineQty other) { if (one.getQ() < other.getQ()) { return -1; } if (one.getQ() > other.getQ()) { return 1; } return 0; } }); Collections.reverse(temp); DefaultPieDataset defaultpiedataset = new DefaultPieDataset(); //defaultpiedataset.setValue("Java", 10); int i = 1; for (VaccineQty p : temp) { if (i == 6) { break; } else { defaultpiedataset.setValue(p.getV().getName() + "(" + p.getQ() + ")", p.getQ()); i++; } } return defaultpiedataset; }
From source file:com.ansorgit.plugins.bash.lang.valueExpansion.ValueExpansionUtil.java
private static StringBuilder expand(List<Expansion> expansions) { List<Expansion> reversed = new ArrayList<Expansion>(expansions); Collections.reverse(reversed); StringBuilder result = new StringBuilder(); do {/*from www .j av a 2 s.c o m*/ result.append(makeLine(reversed)); if (stillMore(reversed)) { result.append(" "); } } while (stillMore(reversed)); return result; }
From source file:fitnesse.slim.StatementExecutor.java
private Class<?> searchPathsForClass(String className) { Class<?> k = getClass(className); if (k != null) return k; List<String> reversedPaths = new ArrayList<String>(paths); Collections.reverse(reversedPaths); for (String path : reversedPaths) { k = getClass(path + "." + className); if (k != null) return k; }/*from w w w.ja v a 2s.co m*/ throw new SlimError(String.format("message:<<NO_CLASS %s>>", className)); }
From source file:de.unisb.cs.st.javalanche.rhino.coverage.CoberturaParser.java
private static void summarizePriorization(FailureMatrix fm, List<PriorizationResult> prioritizedAdditional, String prioritizationType) { Collections.reverse(prioritizedAdditional); List<String> testList = new ArrayList<String>(); int totalFailures = fm.getNumberOfFailures(); int count = 0; logger.info("Result for: " + prioritizationType); StringBuilder sb = new StringBuilder(); for (PriorizationResult prioritizationResult : prioritizedAdditional) { count++;// w w w . ja v a 2s .co m testList.add(prioritizationResult.getTestName()); int detectedFailures = fm.getDetectedFailures(testList); System.out.println( count + " " + prioritizationResult.getTestName() + " (" + prioritizationResult.getInfo() + ") - " + detectedFailures + " out of " + totalFailures + " failures"); String join = Join.join(",", new Object[] { count, prioritizationResult.getTestName(), detectedFailures, totalFailures, "\"" + prioritizationResult.getInfo() + "\"" }); sb.append(join).append('\n'); } Io.writeFile(sb.toString(), new File(prioritizationType + ".csv")); }
From source file:com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.UnSafeIsSetOverArrayInspector.java
@Override @NotNull//from w w w.j a v a 2s . c o m public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new BasePhpElementVisitor() { @Override public void visitPhpIsset(@NotNull PhpIsset issetExpression) { /* * if no parameters, we don't check; * if multiple parameters, perhaps if-inspection fulfilled and isset's were merged * * TODO: still needs analysis regarding concatenations in indexes */ final PhpExpression[] arguments = issetExpression.getVariables(); if (arguments.length != 1) { return; } /* gather context information */ PsiElement issetParent = issetExpression.getParent(); boolean issetInverted = false; if (issetParent instanceof UnaryExpression) { final PsiElement operator = ((UnaryExpression) issetParent).getOperation(); if (OpenapiTypesUtil.is(operator, PhpTokenTypes.opNOT)) { issetInverted = true; issetParent = issetParent.getParent(); } } boolean isResultStored = (issetParent instanceof AssignmentExpression || issetParent instanceof PhpReturn); /* false-positives: ternaries using isset-or-null semantics, there array_key_exist can introduce bugs */ final PsiElement conditionCandidate = issetInverted ? issetExpression.getParent() : issetExpression; boolean isTernaryCondition = issetParent instanceof TernaryExpression && conditionCandidate == ((TernaryExpression) issetParent).getCondition(); if (isTernaryCondition) { final TernaryExpression ternary = (TernaryExpression) issetParent; final PsiElement nullCandidate = issetInverted ? ternary.getTrueVariant() : ternary.getFalseVariant(); if (PhpLanguageUtil.isNull(nullCandidate)) { return; } } /* do analyze */ final PsiElement argument = ExpressionSemanticUtil.getExpressionTroughParenthesis(arguments[0]); if (argument == null) { return; } /* false positives: variables in template/global context - too unreliable */ if (argument instanceof Variable && ExpressionSemanticUtil.getBlockScope(argument) == null) { return; } if (!(argument instanceof ArrayAccessExpression)) { if (argument instanceof FieldReference) { /* if field is not resolved, it's probably dynamic and isset has a purpose */ final PsiReference referencedField = argument.getReference(); final PsiElement resolvedField = referencedField == null ? null : OpenapiResolveUtil.resolveReference(referencedField); if (resolvedField == null || !(ExpressionSemanticUtil.getBlockScope(resolvedField) instanceof PhpClass)) { return; } } if (SUGGEST_TO_USE_NULL_COMPARISON) { /* false-positives: finally, perhaps fallback to initialization in try */ if (PsiTreeUtil.getParentOfType(issetExpression, Finally.class) == null) { final List<String> fragments = Arrays.asList(argument.getText(), issetInverted ? "===" : "!==", "null"); if (!ComparisonStyle.isRegular()) { Collections.reverse(fragments); } final String replacement = String.join(" ", fragments); holder.registerProblem(issetInverted ? issetExpression.getParent() : issetExpression, String.format(patternUseNullComparison, replacement), ProblemHighlightType.WEAK_WARNING, new CompareToNullFix(replacement)); } } return; } /* TODO: has method/function reference as index */ if (REPORT_CONCATENATION_IN_INDEXES && !isResultStored && this.hasConcatenationAsIndex((ArrayAccessExpression) argument)) { holder.registerProblem(argument, messageConcatenationInIndex); return; } if (SUGGEST_TO_USE_ARRAY_KEY_EXISTS && !isArrayAccess((ArrayAccessExpression) argument)) { holder.registerProblem(argument, messageUseArrayKeyExists, ProblemHighlightType.WEAK_WARNING); } } /* checks if any of indexes is concatenation expression */ /* TODO: iterator for array access expression */ private boolean hasConcatenationAsIndex(@NotNull ArrayAccessExpression expression) { PsiElement expressionToInspect = expression; while (expressionToInspect instanceof ArrayAccessExpression) { final ArrayIndex index = ((ArrayAccessExpression) expressionToInspect).getIndex(); if (index != null && index.getValue() instanceof BinaryExpression) { final PsiElement operation = ((BinaryExpression) index.getValue()).getOperation(); if (operation != null && operation.getNode().getElementType() == PhpTokenTypes.opCONCAT) { return true; } } expressionToInspect = expressionToInspect.getParent(); } return false; } // TODO: partially duplicates semanticalAnalysis.OffsetOperationsInspector.isContainerSupportsArrayAccess() private boolean isArrayAccess(@NotNull ArrayAccessExpression expression) { /* ok JB parses `$var[]= ...` always as array, lets make it working properly and report them later */ final PsiElement container = expression.getValue(); if (!(container instanceof PhpTypedElement)) { return false; } final Set<String> containerTypes = new HashSet<>(); final PhpType resolved = OpenapiResolveUtil.resolveType((PhpTypedElement) container, container.getProject()); if (resolved != null) { resolved.filterUnknown().getTypes().forEach(t -> containerTypes.add(Types.getType(t))); } /* failed to resolve, don't try to guess anything */ if (containerTypes.isEmpty()) { return false; } boolean supportsOffsets = false; for (final String typeToCheck : containerTypes) { /* assume is just null-ble declaration or we shall just rust to mixed */ if (typeToCheck.equals(Types.strNull)) { continue; } if (typeToCheck.equals(Types.strMixed)) { supportsOffsets = true; continue; } /* some of possible types are scalars, what's wrong */ if (!StringUtils.isEmpty(typeToCheck) && typeToCheck.charAt(0) != '\\') { supportsOffsets = false; break; } /* assume class has what is needed, OffsetOperationsInspector should report if not */ supportsOffsets = true; } containerTypes.clear(); return supportsOffsets; } }; }
From source file:eo.radio.datumoj.Cxefdatumoj.java
public void leguElsendojn(String radioTxt) { String kapo = null;//from w w w . j av a 2 s . co m for (String unuo : radioTxt.split("\n\r?\n")) { unuo = unuo.trim(); //Log.d("Unuo: "+unuo); if (unuo.length() == 0) { continue; } if (kapo == null) { kapo = unuo; } else { try { Elsendo e = new Elsendo(); String[] x = unuo.split("\n"); /* 3ZZZ en Esperanto 2011-09-29 http://www.melburno.org.au/3ZZZradio/mp3/2011-09-26.3ZZZ.radio.mp3 Anonco : el retmesa?o de Floral Martorell Katastrofo e Vinilkosmo/ Eurokka Kanto : informo pri la kompaktdisko Hiphopa Kompilo 2 Miela obsedo Legado: el la verko de Ken Linton Kanako el Kananam apitro 12 Stranga ?ardeno Lez el Monato de agusto /septembro Tantamas ?topi?oj de Ivo durwael Karlo el Monato Eksplofas la popola kolero [...] */ e.kanalNomo = x[0]; e.datoStr = x[1]; e.dato = datoformato.parse(x[1]); e.sonoUrl = x[2]; e.priskribo = x[3]; elsendoj.add(e); Kanalo k = kanalnomoAlKanalo.get(e.kanalNomo); // Jen problemo. "Esperanta Retradio" nomi?as "Peranto" en // http://esperanto-radio.com/radio.txt . Ni solvas tion serante anka por la kodo // "kodo": "peranto", // "nomo": "Esperanta Retradio", if (k == null) { k = kanalkodoAlKanalo.get(e.kanalNomo.toLowerCase()); if (k != null) e.kanalNomo = k.nomo; } if (k == null) { Log.d("Nekonata kanalnomo - ALDONAS GXIN: " + e.kanalNomo); k = new Kanalo(); k.json = new JSONObject(); k.kodo = k.nomo = e.kanalNomo; k.datumFonto = "aldonita de radio.txt"; kanalkodoAlKanalo.put(k.kodo, k); kanalnomoAlKanalo.put(k.nomo, k); kanaloj.add(k); } else if (k.datumFonto == null) { k.datumFonto = "radio.txt"; } //Log.d("Aldonas elsendon "+e.toString()); k.elsendoj.add(e); } catch (Exception e) { Log.e("Ne povis legi unuon: " + unuo, e); } } } for (Kanalo k : kanaloj) Collections.reverse(k.elsendoj); }
From source file:com.rastating.droidbeard.net.FetchShowTask.java
@Override protected TVShow doInBackground(Long... longs) { long tvdbid = longs[0]; TVShow show = getTVShow(tvdbid);/*from w w w. j a v a 2 s . c o m*/ if (show != null) { Bitmap banner = getBanner(tvdbid); show.setBanner(banner); List<Season> seasons = getSeasons(tvdbid); // Sort the seasons in reverse order. if (seasons != null) { Collections.sort(seasons, new SeasonComparator()); Collections.reverse(seasons); show.setSeasons(seasons); } } return show; }