List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:org.apache.fop.fonts.type1.AFMParser.java
/** * Parses an AFM file from a BufferedReader. * @param reader the BufferedReader instance to read from * @param afmFileName the name of the AFM file * @return the parsed AFM file//from ww w . ja va 2s. c o m * @throws IOException if an I/O error occurs */ public AFMFile parse(BufferedReader reader, String afmFileName) throws IOException { Stack<Object> stack = new Stack<Object>(); int parseMode = PARSE_NORMAL; while (true) { String line = reader.readLine(); if (line == null) { break; } String key = null; switch (parseMode) { case PARSE_NORMAL: key = parseLine(line, stack); break; case PARSE_CHAR_METRICS: key = parseCharMetrics(line, stack, afmFileName); break; default: throw new IllegalStateException("Invalid parse mode"); } Integer newParseMode = PARSE_MODE_CHANGES.get(key); if (newParseMode != null) { parseMode = newParseMode.intValue(); } } return (AFMFile) stack.pop(); }
From source file:org.apache.axis2.deployment.util.Utils.java
public static String getPath(String parent, String childPath) { Stack parentStack = new Stack(); Stack childStack = new Stack(); if (parent != null) { String[] values = parent.split("/"); if (values.length > 0) { for (String value : values) { parentStack.push(value); }/*from www .ja v a 2 s . c o m*/ } } String[] values = childPath.split("/"); if (values.length > 0) { for (String value : values) { childStack.push(value); } } String filepath = ""; while (!childStack.isEmpty()) { String value = (String) childStack.pop(); if ("..".equals(value)) { parentStack.pop(); } else if (!"".equals(value)) { if ("".equals(filepath)) { filepath = value; } else { filepath = value + "/" + filepath; } } } while (!parentStack.isEmpty()) { String value = (String) parentStack.pop(); if (!"".equals(value)) { filepath = value + "/" + filepath; } } return filepath; }
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java
/** * Fill x forms association type.// w w w . j a v a2 s . c om * * @param transaction * the login * @param xformsDocument * the xforms document * @param classElement * the class element * @param association * the association * @param alfrescoClass * the alfresco class * @param initParams * the init params * @param stack * the stack * @param isServletRequest * * @throws ServletException * */ @SuppressWarnings("unused") @Deprecated private void fillXFormsAssociationType(AlfrescoTransaction transaction, Document xformsDocument, Element classElement, AssociationType association, GenericClass alfrescoClass, Map<String, String> initParams, Stack<AssociationType> stack, boolean formIsReadOnly, boolean isServletRequest) throws ServletException { if (!stackContains(stack, association)) { stack.push(association); List<GenericAssociation> alfrescoAssociations = findAssociations(alfrescoClass, association); String targetClassType = classTypeToString(association.getType()); fillXFormsAssociationRoot(transaction, xformsDocument, classElement, association, stack, alfrescoAssociations, targetClassType, initParams, formIsReadOnly, isServletRequest); stack.pop(); } }
From source file:com.glaf.batch.job.BatchJob.java
public void execute(JobExecution execution) { IJobService jobService = ContextFactory.getBean("jobService"); if (execution.getSteps() != null && !execution.getSteps().isEmpty()) { List<StepExecution> steps = execution.getSteps(); Collections.sort(steps);/* ww w.ja v a 2s . com*/ /** * ?? */ Stack<StepExecution> stack = new Stack<StepExecution>(); for (int i = steps.size() - 1; i >= 0; i--) { stack.push(steps.get(i)); } while (!stack.empty()) { StepExecution step = stack.peek(); if (!jobService.stepExecutionCompleted(step.getJobStepKey())) { boolean success = false; int retry = 0; while (retry < 3 && !success) { retry++; try { jobService.startStepExecution(step.getJobStepKey()); if (StringUtils.isNotEmpty(step.getJobClass())) { Object object = ClassUtils.instantiateObject(step.getJobClass()); if (object instanceof IStep) { IStep ix = (IStep) object; ix.execute(step); if (jobService.stepExecutionCompleted(step.getJobStepKey())) { /** * ???? */ stack.pop(); success = true; retry = Integer.MAX_VALUE; break; } } } } catch (Exception ex) { ex.printStackTrace(); } } if (!success) { throw new RuntimeException( step.getStepKey() + " " + step.getStepName() + " execute failed."); } } } } }
From source file:org.apache.flink.cep.nfa.SharedBuffer.java
/** * Returns all elements from the previous relation starting at the given value with the * given key and timestamp./*from ww w . j a v a 2 s.c o m*/ * * @param key Key of the starting value * @param value Value of the starting element * @param timestamp Timestamp of the starting value * @param version Version of the previous relation which shall be extracted * @return Collection of previous relations starting with the given value */ public Collection<LinkedHashMultimap<K, V>> extractPatterns(final K key, final V value, final long timestamp, final DeweyNumber version) { Collection<LinkedHashMultimap<K, V>> result = new ArrayList<>(); // stack to remember the current extraction states Stack<ExtractionState<K, V>> extractionStates = new Stack<>(); // get the starting shared buffer entry for the previous relation SharedBufferEntry<K, V> entry = get(key, value, timestamp); if (entry != null) { extractionStates.add(new ExtractionState<K, V>(entry, version, new Stack<SharedBufferEntry<K, V>>())); // use a depth first search to reconstruct the previous relations while (!extractionStates.isEmpty()) { ExtractionState<K, V> extractionState = extractionStates.pop(); DeweyNumber currentVersion = extractionState.getVersion(); // current path of the depth first search Stack<SharedBufferEntry<K, V>> currentPath = extractionState.getPath(); // termination criterion if (currentVersion.length() == 1) { LinkedHashMultimap<K, V> completePath = LinkedHashMultimap.create(); while (!currentPath.isEmpty()) { SharedBufferEntry<K, V> currentEntry = currentPath.pop(); completePath.put(currentEntry.getKey(), currentEntry.getValueTime().getValue()); } result.add(completePath); } else { SharedBufferEntry<K, V> currentEntry = extractionState.getEntry(); // append state to the path currentPath.push(currentEntry); boolean firstMatch = true; for (SharedBufferEdge<K, V> edge : currentEntry.getEdges()) { // we can only proceed if the current version is compatible to the version // of this previous relation if (currentVersion.isCompatibleWith(edge.getVersion())) { if (firstMatch) { // for the first match we don't have to copy the current path extractionStates.push(new ExtractionState<K, V>(edge.getTarget(), edge.getVersion(), currentPath)); firstMatch = false; } else { Stack<SharedBufferEntry<K, V>> copy = new Stack<>(); copy.addAll(currentPath); extractionStates .push(new ExtractionState<K, V>(edge.getTarget(), edge.getVersion(), copy)); } } } } } } return result; }
From source file:com.sina.scs.transfer.TransferManager.java
/** * Downloads all objects in the virtual directory designated by the * keyPrefix given to the destination directory given. All virtual * subdirectories will be downloaded recursively. * * @param bucketName//from www . jav a2 s . c o m * The bucket containing the virtual directory * @param keyPrefix * The key prefix for the virtual directory, or null for the * entire bucket. All subdirectories will be downloaded * recursively. * @param destinationDirectory * The directory to place downloaded files. Subdirectories will * be created as necessary. */ public MultipleFileDownload downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) { if (keyPrefix == null) keyPrefix = ""; List<S3ObjectSummary> objectSummaries = new LinkedList<S3ObjectSummary>(); Stack<String> commonPrefixes = new Stack<String>(); commonPrefixes.add(keyPrefix); long totalSize = 0; // Recurse all virtual subdirectories to get a list of object summaries. // This is a depth-first search. do { String prefix = commonPrefixes.pop(); ObjectListing listObjectsResponse = null; do { if (listObjectsResponse == null) { ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName) .withDelimiter(DEFAULT_DELIMITER).withPrefix(prefix); listObjectsResponse = s3.listObjects(listObjectsRequest); } else { listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse); } for (S3ObjectSummary s : listObjectsResponse.getObjectSummaries()) { // Skip any files that are also virtual directories, since // we can't save both a directory and a file of the same // name. if (!s.getKey().equals(prefix) && !listObjectsResponse.getCommonPrefixes().contains(s.getKey() + DEFAULT_DELIMITER)) { objectSummaries.add(s); totalSize += s.getSize(); } else { log.debug("Skipping download for object " + s.getKey() + " since it is also a virtual directory"); } } commonPrefixes.addAll(listObjectsResponse.getCommonPrefixes()); } while (listObjectsResponse.isTruncated()); } while (!commonPrefixes.isEmpty()); /* This is the hook for adding additional progress listeners */ ProgressListenerChain additionalProgressListenerChain = new ProgressListenerChain(); TransferProgressImpl transferProgress = new TransferProgressImpl(); transferProgress.setTotalBytesToTransfer(totalSize); /* * Bind additional progress listeners to this * MultipleFileTransferProgressUpdatingListener to receive * ByteTransferred events from each single-file download implementation. */ ProgressListener multipleFileTransferProgressListener = new MultipleFileTransferProgressUpdatingListener( transferProgress, additionalProgressListenerChain); List<DownloadImpl> downloads = new ArrayList<DownloadImpl>(); String description = "Downloading from " + bucketName + "/" + keyPrefix; final MultipleFileDownloadImpl multipleFileDownload = new MultipleFileDownloadImpl(description, transferProgress, additionalProgressListenerChain, keyPrefix, bucketName, downloads); multipleFileDownload.setMonitor(new MultipleFileTransferMonitor(multipleFileDownload, downloads)); final AllDownloadsQueuedLock allTransfersQueuedLock = new AllDownloadsQueuedLock(); MultipleFileTransferStateChangeListener multipleFileTransferStateChangeListener = new MultipleFileTransferStateChangeListener( allTransfersQueuedLock, multipleFileDownload); for (S3ObjectSummary summary : objectSummaries) { // TODO: non-standard delimiters File f = new File(destinationDirectory, summary.getKey()); File parentFile = f.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { throw new RuntimeException("Couldn't create parent directories for " + f.getAbsolutePath()); } // All the single-file downloads share the same // MultipleFileTransferProgressUpdatingListener and // MultipleFileTransferStateChangeListener downloads .add((DownloadImpl) download( new GetObjectRequest(summary.getBucketName(), summary.getKey()) .withGeneralProgressListener(multipleFileTransferProgressListener), f, multipleFileTransferStateChangeListener)); } if (downloads.isEmpty()) { multipleFileDownload.setState(TransferState.Completed); return multipleFileDownload; } // Notify all state changes waiting for the downloads to all be queued // to wake up and continue. synchronized (allTransfersQueuedLock) { allTransfersQueuedLock.allQueued = true; allTransfersQueuedLock.notifyAll(); } return multipleFileDownload; }
From source file:gr.abiss.calipso.wicket.customattrs.CustomAttributeUtils.java
/** * Parses the given user intput to create the custom attribute lookup values (options) and their translations, * then add them to the given CustomAttribute. * @param optionsTextIput/*w ww. jav a2s. com*/ * @param attribute * @param languages */ public static void parseOptionsIntoAttribute(Map<String, String> optionsTextIput, CustomAttribute attribute, List<Language> languages) { //logger.info("parseOptionsIntoAttribute, attribute: "+attribute); // add options attribute.setPersistedVersion(attribute.getVersion()); attribute.setVersion(attribute.getVersion() + 1); attribute.removeAllLookupValues(); List<CustomAttributeLookupValue> optionsList = new LinkedList<CustomAttributeLookupValue>(); String languageId = null; for (Language language : languages) { if (languageId == null) { languageId = language.getId(); } String input = optionsTextIput.get(language.getId()); //logger.info("textAreaOptions.get(language.getId(): "+input); if (StringUtils.isNotBlank(input)) { Stack<CustomAttributeLookupValue> parents = new Stack<CustomAttributeLookupValue>(); String[] lines = input.split("\\r?\\n"); int listIndex = -1; for (int j = 0; j < lines.length; j++) { listIndex++; // count whitespace characters to determine level String line = lines[j]; //logger.info("Reading option line: "+line); int countLevel = 1; int limit = line.length(); for (int i = 0; i < limit; ++i) { if (Character.isWhitespace(line.charAt(i))) { ++countLevel; } else { break; } } String translatedName = line.substring(countLevel - 1).trim(); //logger.info("translatedName: "+translatedName); // build CustomAttributeLookupValue if it doesn't already exist CustomAttributeLookupValue lookupValue; if (language.getId().equalsIgnoreCase(languageId)) { //logger.info("creating new lookupValue and adding to list index " + listIndex + " for " + translatedName); lookupValue = new CustomAttributeLookupValue(); optionsList.add(lookupValue); } else { //logger.info("trying to get lookupValue from list index " + listIndex + "for "+translatedName); lookupValue = optionsList.get(listIndex); } lookupValue.setShowOrder(listIndex); if (language.getId().equalsIgnoreCase("en")) { lookupValue.setName(translatedName); lookupValue.setValue(translatedName); } lookupValue.setLevel(countLevel); // fix parent/child while ((!parents.isEmpty()) && parents.peek().getLevel() >= lookupValue.getLevel()) { parents.pop(); } // pile it if (lookupValue.getLevel() > 1) { //logger.info("Adding child "+lookupValue.getName() + "to parent " +parents.peek()); parents.peek().addChild(lookupValue); } parents.push(lookupValue); // add the translation //logger.info("Adding lookup value "+language.getId()+" translation: "+translatedName); lookupValue.addNameTranslation(language.getId(), translatedName); //logger.info("translations afre now: "+lookupValue.getNameTranslations()); } } //Set<CustomAttributeLookupValue> lookupValueSet = new HashSet<CustomAttributeLookupValue>(); //lookupValueSet.addAll(optionsList); } // update attribute lookup values attribute.removeAllLookupValues(); /* List<CustomAttributeLookupValue> toRemove = new LinkedList<CustomAttributeLookupValue>(); for(CustomAttributeLookupValue value : attribute.getAllowedLookupValues()){ toRemove.add(value); } attribute.removeAll(toRemove);*/ for (CustomAttributeLookupValue value : optionsList) { //logger.info("Adding lookupValue with translations: "+value.getNameTranslations()); attribute.addAllowedLookupValue(value); } //logger.info("Added lookup values: "+attribute.getAllowedLookupValues()); }
From source file:com.sina.cloudstorage.services.scs.transfer.TransferManager.java
/** * Downloads all objects in the virtual directory designated by the * keyPrefix given to the destination directory given. All virtual * subdirectories will be downloaded recursively. * * @param bucketName//from w w w . ja v a 2 s .co m * The bucket containing the virtual directory * @param keyPrefix * The key prefix for the virtual directory, or null for the * entire bucket. All subdirectories will be downloaded * recursively. * @param destinationDirectory * The directory to place downloaded files. Subdirectories will * be created as necessary. */ public MultipleFileDownload downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) { if (keyPrefix == null) keyPrefix = ""; List<S3ObjectSummary> objectSummaries = new LinkedList<S3ObjectSummary>(); Stack<String> commonPrefixes = new Stack<String>(); commonPrefixes.add(keyPrefix); long totalSize = 0; // Recurse all virtual subdirectories to get a list of object summaries. // This is a depth-first search. do { String prefix = commonPrefixes.pop(); ObjectListing listObjectsResponse = null; do { if (listObjectsResponse == null) { ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName) .withDelimiter(DEFAULT_DELIMITER).withPrefix(prefix); listObjectsResponse = s3.listObjects(listObjectsRequest); } else { listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse); } for (S3ObjectSummary s : listObjectsResponse.getObjectSummaries()) { // Skip any files that are also virtual directories, since // we can't save both a directory and a file of the same // name. if (!s.getKey().equals(prefix) && !listObjectsResponse.getCommonPrefixes().contains(s.getKey() + DEFAULT_DELIMITER)) { objectSummaries.add(s); totalSize += s.getSize(); } else { log.debug("Skipping download for object " + s.getKey() + " since it is also a virtual directory"); } } for (Map<String, String> cp : listObjectsResponse.getCommonPrefixes()) commonPrefixes.add(cp.get("Prefix")); } while (listObjectsResponse.isTruncated()); } while (!commonPrefixes.isEmpty()); /* This is the hook for adding additional progress listeners */ ProgressListenerChain additionalProgressListenerChain = new ProgressListenerChain(); TransferProgressImpl transferProgress = new TransferProgressImpl(); transferProgress.setTotalBytesToTransfer(totalSize); /* * Bind additional progress listeners to this * MultipleFileTransferProgressUpdatingListener to receive * ByteTransferred events from each single-file download implementation. */ ProgressListener multipleFileTransferProgressListener = new MultipleFileTransferProgressUpdatingListener( transferProgress, additionalProgressListenerChain); List<DownloadImpl> downloads = new ArrayList<DownloadImpl>(); String description = "Downloading from " + bucketName + "/" + keyPrefix; final MultipleFileDownloadImpl multipleFileDownload = new MultipleFileDownloadImpl(description, transferProgress, additionalProgressListenerChain, keyPrefix, bucketName, downloads); multipleFileDownload.setMonitor(new MultipleFileTransferMonitor(multipleFileDownload, downloads)); final AllDownloadsQueuedLock allTransfersQueuedLock = new AllDownloadsQueuedLock(); MultipleFileTransferStateChangeListener multipleFileTransferStateChangeListener = new MultipleFileTransferStateChangeListener( allTransfersQueuedLock, multipleFileDownload); for (S3ObjectSummary summary : objectSummaries) { // TODO: non-standard delimiters File f = new File(destinationDirectory, summary.getKey()); File parentFile = f.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { throw new RuntimeException("Couldn't create parent directories for " + f.getAbsolutePath()); } // All the single-file downloads share the same // MultipleFileTransferProgressUpdatingListener and // MultipleFileTransferStateChangeListener downloads .add((DownloadImpl) download( new GetObjectRequest(summary.getBucketName(), summary.getKey()) .withGeneralProgressListener(multipleFileTransferProgressListener), f, multipleFileTransferStateChangeListener)); } if (downloads.isEmpty()) { multipleFileDownload.setState(TransferState.Completed); return multipleFileDownload; } // Notify all state changes waiting for the downloads to all be queued // to wake up and continue. synchronized (allTransfersQueuedLock) { allTransfersQueuedLock.allQueued = true; allTransfersQueuedLock.notifyAll(); } return multipleFileDownload; }
From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java
@Override public LogicalNode visitTableSubQuery(Context upperContext, LogicalPlan plan, LogicalPlan.QueryBlock block, TableSubQueryNode node, Stack<LogicalNode> stack) throws PlanningException { Context childContext = new Context(plan, upperContext.requiredSet); stack.push(node);//from w w w . j av a 2 s . c o m LogicalNode child = super.visitTableSubQuery(childContext, plan, block, node, stack); node.setSubQuery(child); stack.pop(); Target[] targets; if (node.hasTargets()) { targets = node.getTargets(); } else { targets = PlannerUtil.schemaToTargets(node.getOutSchema()); } LinkedHashSet<Target> projectedTargets = Sets.newLinkedHashSet(); for (Iterator<Target> it = getFilteredTarget(targets, upperContext.requiredSet); it.hasNext();) { Target target = it.next(); upperContext.addExpr(target); } for (Iterator<Target> it = upperContext.targetListMgr.getFilteredTargets(upperContext.requiredSet); it .hasNext();) { Target target = it.next(); if (LogicalPlanner.checkIfBeEvaluatedAtRelation(block, target.getEvalTree(), node)) { projectedTargets.add(target); upperContext.targetListMgr.markAsEvaluated(target); } } node.setTargets(projectedTargets.toArray(new Target[projectedTargets.size()])); LogicalPlanner.verifyProjectedFields(block, node); return node; }
From source file:com.bstek.dorado.view.output.DataOutputter.java
@SuppressWarnings("rawtypes") private void internalOutputData(Object object, OutputContext context) throws Exception { JsonBuilder json = context.getJsonBuilder(); Stack<Object> dataObjectStack = context.getDataObjectStack(); if (dataObjectStack.contains(object)) { Exception e = new IllegalArgumentException( resourceManager.getString("dorado.common/circuitReferenceError", object.toString())); logger.error(e, e);// w ww.j a v a 2 s.com json.value(null); return; } dataObjectStack.push(object); try { if (object instanceof Collection<?>) { outputDataTypeIfNecessary(context, object); if (object instanceof PagingList) { outputPagingList((PagingList) object, context); } else { json.array(); for (Object e : (Collection<?>) object) { outputData(e, context); } json.endArray(); } } else if (object instanceof Page<?>) { outputPage((Page<?>) object, context); } else { outputEntity(object, context); } } finally { dataObjectStack.pop(); } }