List of usage examples for java.util Queue remove
E remove();
From source file:it.geosolutions.geobatch.unredd.script.publish.PublishingAction.java
/** * Main loop on input files. Single file processing is called on * execute(File xmlFile)/* w w w.j a va 2 s . com*/ */ public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { // **************************************** // initialize PostGISUtils, Geostore and paths // // **************************************** try { initialize(); } catch (Exception e) { LOGGER.error("Exception during component initialization", e); throw new ActionException(this, "Exception during initialization"); } final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>(); while (!events.isEmpty()) { final FileSystemEvent ev = events.remove(); try { if (ev != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("PublishingAction.execute(): working on incoming event: " + ev.getSource()); } File xmlFile = ev.getSource(); // this is the input xml file executeInternal(xmlFile); ret.add(new FileSystemEvent(xmlFile, FileSystemEventType.FILE_ADDED)); } else { LOGGER.error("PublishingAction.execute(): Encountered a NULL event: SKIPPING..."); continue; } } catch (ActionException ex) { // ActionEx have already been processed LOGGER.error(ex.getMessage(), ex); throw ex; } catch (Exception ex) { final String message = "PublishingAction.execute(): Unable to produce the output: " + ex.getLocalizedMessage(); LOGGER.error(message, ex); throw new ActionException(this, message); } } return ret; }
From source file:it.geosolutions.geobatch.actions.commons.ExtractAction.java
/** * Removes TemplateModelEvents from the queue and put *///www .j av a2 s .c om public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.started(); listenerForwarder.setTask("build the output absolute file name"); // return final Queue<EventObject> ret = new LinkedList<EventObject>(); listenerForwarder.setTask("Building/getting the root data structure"); boolean extractMultipleFile; final int size = events.size(); if (size == 0) { throw new ActionException(this, "Empty file list"); } else if (size > 1) { extractMultipleFile = true; } else { extractMultipleFile = false; } final File dest = conf.getDestination(); if (dest != null && !dest.isDirectory()) { if (!dest.mkdirs()) { throw new ActionException(this, "bad destination (not writeable): " + dest); } } while (!events.isEmpty()) { listenerForwarder.setTask("Generating the output"); final EventObject event = events.remove(); if (event == null) { // TODO LOG continue; } if (event instanceof FileSystemEvent) { File source = ((FileSystemEvent) event).getSource(); try { listenerForwarder.setTask("Extracting file: " + source); final File extracted = Extract.extract(source, getTempDir(), false); if (extracted != null) { if (dest != null) { File newDest = new File(dest, extracted.getName()); listenerForwarder.setTask("moving \'" + extracted + "\' to \'" + newDest + "\'"); FileUtils.moveDirectoryToDirectory(extracted, newDest, true); listenerForwarder.terminated(); ret.add(new FileSystemEvent(newDest, FileSystemEventType.DIR_CREATED)); } else { throw new ActionException(this, "Unable to extracto file: " + source); } } else { final String message = "Unable to extract " + source; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } } catch (Exception e) { final String message = "Unable to copy extracted archive"; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(e.getLocalizedMessage()); } } } else { final String message = "Incoming instance is not a FileSystemEvent: " + event; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } // TODO setup task progress } // endwile listenerForwarder.completed(); return ret; }
From source file:bwem.map.MapImpl.java
public WalkPosition breadthFirstSearch(final WalkPosition start, final Pred findCond, final Pred visitCond, final boolean connect8) { if (findCond.isTrue(getData().getMiniTile(start), start, this)) { return start; }//from ww w . j a v a2 s.c o m final Set<WalkPosition> visited = new TreeSet<>((a, b) -> { int result = Integer.compare(a.getX(), b.getX()); if (result != 0) { return result; } return Integer.compare(a.getY(), b.getY()); }); final Queue<WalkPosition> toVisit = new ArrayDeque<>(); toVisit.add(start); visited.add(start); final WalkPosition[] dir8 = { new WalkPosition(-1, -1), new WalkPosition(0, -1), new WalkPosition(1, -1), new WalkPosition(-1, 0), new WalkPosition(1, 0), new WalkPosition(-1, 1), new WalkPosition(0, 1), new WalkPosition(1, 1) }; final WalkPosition[] dir4 = { new WalkPosition(0, -1), new WalkPosition(-1, 0), new WalkPosition(1, 0), new WalkPosition(0, 1) }; final WalkPosition[] directions = connect8 ? dir8 : dir4; while (!toVisit.isEmpty()) { final WalkPosition current = toVisit.remove(); for (final WalkPosition delta : directions) { final WalkPosition next = current.add(delta); if (getData().getMapData().isValid(next)) { final MiniTile miniTile = getData().getMiniTile(next, CheckMode.NO_CHECK); if (findCond.isTrue(miniTile, next, this)) { return next; } if (visitCond.isTrue(miniTile, next, this) && !visited.contains(next)) { toVisit.add(next); visited.add(next); } } } } //TODO: Are we supposed to return start or not? // bwem_assert(false); throw new IllegalStateException(); // return start; }
From source file:org.orekit.models.earth.tessellation.EllipsoidTessellator.java
/** Expand a mesh so it surrounds at least one connected part of a zone. * <p>// w w w . j a v a 2s. c o m * This part of mesh expansion is neighbors based. It includes the seed * node neighbors, and their neighbors, and the neighbors of their * neighbors until the path-connected sub-parts of the zone these nodes * belong to are completely surrounded by the mesh taxicab boundary. * </p> * @param mesh mesh to expand * @param seeds seed nodes (already in the mesh) from which to start expansion * @param zone zone to mesh * @exception OrekitException if tile direction cannot be computed */ private void neighborExpandMesh(final Mesh mesh, final Collection<Mesh.Node> seeds, final SphericalPolygonsSet zone) throws OrekitException { // mesh expansion loop boolean expanding = true; final Queue<Mesh.Node> newNodes = new LinkedList<Mesh.Node>(); newNodes.addAll(seeds); while (expanding) { // first expansion step: set up the mesh so that all its // inside nodes are completely surrounded by at least // one layer of outside nodes while (!newNodes.isEmpty()) { // retrieve an active node final Mesh.Node node = newNodes.remove(); if (node.isInside()) { // the node is inside the zone, the mesh must contain its 8 neighbors addAllNeighborsIfNeeded(node, mesh, newNodes); } } // second expansion step: check if the loop of outside nodes // completely surrounds the zone, i.e. there are no peaks // pointing out of the loop between two nodes expanding = false; final List<Mesh.Node> boundary = mesh.getTaxicabBoundary(false); if (boundary.size() > 1) { Mesh.Node previous = boundary.get(boundary.size() - 1); for (final Mesh.Node node : boundary) { if (meetInside(previous.getS2P(), node.getS2P(), zone)) { // part of the mesh boundary is still inside the zone! // the mesh must be expanded again addAllNeighborsIfNeeded(previous, mesh, newNodes); addAllNeighborsIfNeeded(node, mesh, newNodes); expanding = true; } previous = node; } } } }
From source file:alluxio.proxy.s3.S3RestServiceHandler.java
private List<URIStatus> listObjects(AlluxioURI uri, ListBucketOptions listBucketOptions) throws FileDoesNotExistException, IOException, AlluxioException { List<URIStatus> objects = new ArrayList<>(); Queue<URIStatus> traverseQueue = new ArrayDeque<>(); List<URIStatus> children; String prefix = listBucketOptions.getPrefix(); if (prefix != null && prefix.contains(AlluxioURI.SEPARATOR)) { AlluxioURI prefixDirUri = new AlluxioURI(uri.getPath() + AlluxioURI.SEPARATOR + prefix.substring(0, prefix.lastIndexOf(AlluxioURI.SEPARATOR))); children = mFileSystem.listStatus(prefixDirUri); } else {/* w w w . j a v a 2 s . c o m*/ children = mFileSystem.listStatus(uri); } traverseQueue.addAll(children); while (!traverseQueue.isEmpty()) { URIStatus cur = traverseQueue.remove(); if (!cur.isFolder()) { // Alluxio file is an object. objects.add(cur); } else if (!cur.getName().endsWith(Constants.S3_MULTIPART_TEMPORARY_DIR_SUFFIX)) { // The directory is not a temporary directory of multipart upload, list recursively. List<URIStatus> curChildren = mFileSystem.listStatus(new AlluxioURI(cur.getPath())); if (curChildren.isEmpty()) { // An empty Alluxio directory is considered as a valid object. objects.add(cur); } else { traverseQueue.addAll(curChildren); } } } return objects; }
From source file:org.apache.falcon.resource.AbstractInstanceManager.java
private LineageGraphResult triage(EntityType entityType, Entity entity, String instanceTime, Cluster cluster) throws FalconException { Date instanceDate = SchemaHelper.parseDateUTC(instanceTime); LineageGraphResult result = new LineageGraphResult(); Set<String> vertices = new HashSet<>(); Set<LineageGraphResult.Edge> edges = new HashSet<>(); Map<String, String> instanceStatusMap = new HashMap<>(); // queue containing all instances which need to be triaged Queue<SchedulableEntityInstance> remainingInstances = new LinkedList<>(); SchedulableEntityInstance currentInstance = new SchedulableEntityInstance(entity.getName(), cluster.getName(), instanceDate, entityType); remainingInstances.add(currentInstance); while (!remainingInstances.isEmpty()) { currentInstance = remainingInstances.remove(); if (currentInstance.getEntityType() == EntityType.FEED) { Feed feed = ConfigurationStore.get().get(EntityType.FEED, currentInstance.getEntityName()); FeedInstanceStatus.AvailabilityStatus status = getFeedInstanceStatus(feed, currentInstance.getInstanceTime(), cluster); // add vertex to the graph vertices.add(currentInstance.toString()); instanceStatusMap.put(currentInstance.toString(), "[" + status.name() + "]"); if (status == FeedInstanceStatus.AvailabilityStatus.AVAILABLE) { continue; }// w w w .j a va2 s. co m // find producer process instance and add it to the queue SchedulableEntityInstance producerInstance = FeedHelper.getProducerInstance(feed, currentInstance.getInstanceTime(), cluster); if (producerInstance != null) { remainingInstances.add(producerInstance); //add edge from producerProcessInstance to the feedInstance LineageGraphResult.Edge edge = new LineageGraphResult.Edge(producerInstance.toString(), currentInstance.toString(), "produces"); edges.add(edge); } } else { // entity type is PROCESS Process process = ConfigurationStore.get().get(EntityType.PROCESS, currentInstance.getEntityName()); InstancesResult.WorkflowStatus status = getProcessInstanceStatus(process, currentInstance.getInstanceTime()); // add current process instance as a vertex vertices.add(currentInstance.toString()); if (status == null) { instanceStatusMap.put(currentInstance.toString(), "[ Not Available ]"); } else { instanceStatusMap.put(currentInstance.toString(), "[" + status.name() + "]"); if (status == InstancesResult.WorkflowStatus.SUCCEEDED) { continue; } } // find list of input feed instances - only mandatory ones and not optional ones Set<SchedulableEntityInstance> inputFeedInstances = ProcessHelper.getInputFeedInstances(process, currentInstance.getInstanceTime(), cluster, false); for (SchedulableEntityInstance inputFeedInstance : inputFeedInstances) { remainingInstances.add(inputFeedInstance); //Add edge from inputFeedInstance to consumer processInstance LineageGraphResult.Edge edge = new LineageGraphResult.Edge(inputFeedInstance.toString(), currentInstance.toString(), "consumed by"); edges.add(edge); } } } // append status to each vertex Set<String> relabeledVertices = new HashSet<>(); for (String instance : vertices) { String status = instanceStatusMap.get(instance); relabeledVertices.add(instance + status); } // append status to each edge for (LineageGraphResult.Edge edge : edges) { String oldTo = edge.getTo(); String oldFrom = edge.getFrom(); String newFrom = oldFrom + instanceStatusMap.get(oldFrom); String newTo = oldTo + instanceStatusMap.get(oldTo); edge.setFrom(newFrom); edge.setTo(newTo); } result.setEdges(edges.toArray(new LineageGraphResult.Edge[0])); result.setVertices(relabeledVertices.toArray(new String[0])); return result; }
From source file:candr.yoclip.Parser.java
/** * Creates a {@code ParsedOptionParameter} for the option property parameter at the head of the queue. The value of the parsed option will * contain option property key and value. As an example if the parameters queue head contains "<code>-Dkey=value</code>" the parsed option value * will be the string "<code>key=value</code>" (assuming the bean contains a field annotated with {@link candr.yoclip.annotation.OptionProperties * OptionProperties})./* w ww . j a va 2 s .co m*/ * * @param parameters The current queue of command parameters. * @return a parsed option parameter or {@code null} in the following cases. * <ul> * <li>The parameters queue is empty.</li> * <li>The bean does not contain option property annotations.</li> * <li>The head of the parameters queue does not match an option property annotation on the bean.</li> * </ul> */ protected ParsedOption<T> getParsedOptionProperty(final Queue<String> parameters) { ParsedOption<T> parsedOption = null; String parameter = parameters.peek(); if (!StringUtils.isEmpty(parameter)) { final String prefix = getParserOptions().getPrefix(); if (parameter.startsWith(prefix)) { parameter = parameter.substring(prefix.length()); for (final Pair<Matcher, String> propertyMatcher : getPropertyMatchers()) { final Matcher matcher = propertyMatcher.getLeft(); if (matcher.reset(parameter).matches()) { parameters.remove(); // this always succeeds because the parser has set up the property matcher final String optionParametersKey = propertyMatcher.getRight(); final ParserOption<T> optionParameter = getParserOptions().get(optionParametersKey); final String value = matcher.group(1); parsedOption = new ParsedOption<T>(optionParameter, value); break; } } } } return parsedOption; }
From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetilerAction.java
@Override public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { try {/*w w w. j a v a2 s .c o m*/ if (configuration == null) { final String message = "GeotiffRetiler::execute(): flow configuration is null."; if (LOGGER.isErrorEnabled()) LOGGER.error(message); throw new ActionException(this, message); } if (events.size() == 0) { throw new ActionException(this, "GeotiffRetiler::execute(): Unable to process an empty events queue."); } if (LOGGER.isInfoEnabled()) LOGGER.info("GeotiffRetiler::execute(): Starting with processing..."); listenerForwarder.started(); // The return final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>(); while (events.size() > 0) { FileSystemEvent event = events.remove(); File eventFile = event.getSource(); FileSystemEventType eventType = event.getEventType(); if (eventFile.exists() && eventFile.canRead() && eventFile.canWrite()) { /* * If here: we can start retiler actions on the incoming file event */ if (eventFile.isDirectory()) { File[] fileList = eventFile.listFiles(); int size = fileList.length; for (int progress = 0; progress < size; progress++) { File inFile = fileList[progress]; final String absolutePath = inFile.getAbsolutePath(); final String inputFileName = FilenameUtils.getName(absolutePath); if (LOGGER.isInfoEnabled()) LOGGER.info("is going to retile: " + inputFileName); try { listenerForwarder.setTask("GeotiffRetiler"); GeoTiffRetilerUtils.reTile(inFile, configuration, getTempDir()); // set the output /* * COMMENTED OUT 21 Feb 2011: simone: If the event represents a Dir * we have to return a Dir. Do not matter failing files. * * carlo: we may also want to check if a file is already tiled! * * File outputFile=reTile(inFile); if (outputFile!=null){ //TODO: * here we use the same event for each file in the ret.add(new * FileSystemEvent(outputFile, eventType)); } */ } catch (UnsupportedOperationException uoe) { listenerForwarder.failed(uoe); if (LOGGER.isWarnEnabled()) LOGGER.warn(uoe.getLocalizedMessage(), uoe); continue; } catch (IOException ioe) { listenerForwarder.failed(ioe); if (LOGGER.isWarnEnabled()) LOGGER.warn(ioe.getLocalizedMessage(), ioe); continue; } catch (IllegalArgumentException iae) { listenerForwarder.failed(iae); if (LOGGER.isWarnEnabled()) LOGGER.warn(iae.getLocalizedMessage(), iae); continue; } finally { listenerForwarder.setProgress((progress * 100) / ((size != 0) ? size : 1)); listenerForwarder.progressing(); } } if (LOGGER.isInfoEnabled()) LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource()); // add the directory to the return ret.add(event); } else { // file is not a directory try { listenerForwarder.setTask("GeotiffRetiler"); final File outputFile = GeoTiffRetilerUtils.reTile(eventFile, configuration, getTempDir()); if (LOGGER.isInfoEnabled()) LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource()); listenerForwarder.setProgress(100); ret.add(new FileSystemEvent(outputFile, eventType)); } catch (UnsupportedOperationException uoe) { listenerForwarder.failed(uoe); if (LOGGER.isWarnEnabled()) LOGGER.warn(uoe.getLocalizedMessage(), uoe); continue; } catch (IOException ioe) { listenerForwarder.failed(ioe); if (LOGGER.isWarnEnabled()) LOGGER.warn(ioe.getLocalizedMessage(), ioe); continue; } catch (IllegalArgumentException iae) { listenerForwarder.failed(iae); if (LOGGER.isWarnEnabled()) LOGGER.warn(iae.getLocalizedMessage(), iae); continue; } finally { listenerForwarder.setProgress((100) / ((events.size() != 0) ? events.size() : 1)); listenerForwarder.progressing(); } } } else { final String message = "The passed file event refers to a not existent " + "or not readable/writeable file! File: " + eventFile.getAbsolutePath(); if (LOGGER.isWarnEnabled()) LOGGER.warn(message); final IllegalArgumentException iae = new IllegalArgumentException(message); listenerForwarder.failed(iae); } } // endwile listenerForwarder.completed(); // return if (ret.size() > 0) { events.clear(); return ret; } else { /* * If here: we got an error no file are set to be returned the input queue is * returned */ return events; } } catch (Exception t) { if (LOGGER.isErrorEnabled()) LOGGER.error(t.getLocalizedMessage(), t); final ActionException exc = new ActionException(this, t.getLocalizedMessage(), t); listenerForwarder.failed(exc); throw exc; } }
From source file:it.geosolutions.geobatch.task.TaskExecutor.java
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { listenerForwarder.started();//www .j a v a 2 s.c om if (configuration == null) { final ActionException e = new ActionException(this, "DataFlowConfig is null."); listenerForwarder.failed(e); throw e; } if (events == null || events.size() == 0) { final ActionException e = new ActionException(this, "Empty or null incoming events list"); listenerForwarder.failed(e); throw e; } Queue<FileSystemEvent> outEvents = new LinkedList<FileSystemEvent>(); while (events.size() > 0) { // get the first event final FileSystemEvent event = events.remove(); final File inputFile = event.getSource(); if (inputFile == null) { final ActionException e = new ActionException(this, "Input File is null"); listenerForwarder.failed(e); throw e; } if (!inputFile.exists()) { final ActionException e = new ActionException(this, "Input File doesn't exist"); listenerForwarder.failed(e); throw e; } final String inputFilePath = inputFile.getAbsolutePath(); final String inputFileExt = FilenameUtils.getExtension(inputFilePath); // Getting XSL file definition final String xslPath = configuration.getXsl(); final boolean useDefaultScript; String defaultScriptPath = configuration.getDefaultScript(); if (inputFileExt.equalsIgnoreCase("xml")) { if (LOGGER.isInfoEnabled()) LOGGER.info("Using input file as script: " + inputFilePath); defaultScriptPath = inputFilePath; useDefaultScript = false; } else { if (LOGGER.isInfoEnabled()) LOGGER.info("Using default script: " + configuration.getDefaultScript()); useDefaultScript = true; } final String outputName = configuration.getOutputName(); File xslFile = null; InputStream is = null; try { if (xslPath != null && xslPath.trim().length() > 0) { final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath()); if (path == null) { final ActionException e = new ActionException(this, "XSL file not found: " + path); listenerForwarder.failed(e); throw e; } xslFile = new File(path); } if (!xslFile.exists()) { final ActionException e = new ActionException(this, "XSL file not found: " + xslPath); listenerForwarder.failed(e); throw e; } File xmlFile = null; String outputFile = null; if (useDefaultScript) { if (defaultScriptPath != null && defaultScriptPath.trim().length() > 0) { final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath()); if (path == null) { final ActionException e = new ActionException(this, "XSL file not found: " + path); listenerForwarder.failed(e); throw e; } xmlFile = new File(path); final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // outXmlFile.deleteOnExit(); outputFile = setScriptArguments(xmlFile.getAbsolutePath(), inputFilePath, outputName, outXmlFile); xmlFile = outXmlFile; } } else { xmlFile = inputFile; } if (!xmlFile.exists()) { final ActionException e = new ActionException(this, "XML file not found: " + xmlFile); listenerForwarder.failed(e); throw e; } // Setup an XML source from the input XML file final Source xmlSource = new StreamSource(xmlFile); is = new FileInputStream(xslFile); // XML parsing to setup a command line final String argument = buildArgument(xmlSource, is); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Arguments: " + argument); } final Project project = new Project(); project.init(); final ExecTask execTask = new ExecTask(); execTask.setProject(project); // Setting environment variables coming from the configuration // as an instance: PATH, LD_LIBRARY_PATH and similar Map<String, String> variables = configuration.getVariables(); if (variables != null && !variables.isEmpty()) { for (String key : variables.keySet()) { Variable var = new Variable(); var.setKey(key); final String value = variables.get(key); if (value != null) { var.setValue(variables.get(key)); execTask.addEnv(var); } } } // Setting executable execTask.setExecutable(configuration.getExecutable()); // Setting Error logging final String errorFileName = configuration.getErrorFile(); if (errorFileName != null) { File errorFile = new File(errorFileName); if (!errorFile.exists()) { errorFile = Path.findLocation(errorFileName, getTempDir()); if (errorFile != null && !errorFile.exists()) { try { errorFile.createNewFile(); } catch (Throwable t) { final ActionException e = new ActionException(this, t.getLocalizedMessage(), t); listenerForwarder.failed(e); throw e; } } } if (errorFile.exists()) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Using error file: " + errorFile); execTask.setLogError(true); execTask.setAppend(true); execTask.setError(errorFile); execTask.setFailonerror(true); } } // Setting the timeout Long timeOut = configuration.getTimeOut(); if (timeOut != null) { execTask.setTimeout(timeOut); } // Setting command line argument execTask.createArg().setLine(argument); File output = null; if (configuration.getOutput() != null) { output = new File(configuration.getOutput()); if (output.exists() && output.isDirectory()) { final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // TODO CHECKME: is this var used? // outXmlFile.deleteOnExit(); String destFile = getScriptArguments(xmlFile.getAbsolutePath(), "srcfile"); if (output.isAbsolute()) { // String basename = output = new File(output, FilenameUtils.getBaseName(destFile) + configuration .getOutputName().substring(configuration.getOutputName().indexOf("."))); } else { output = Path.findLocation(configuration.getOutput(), inputFile.getParentFile()); output = new File(output, FilenameUtils.getBaseName(inputFile.getName()) + configuration .getOutputName().substring(configuration.getOutputName().indexOf("."))); } } execTask.setOutput(output); } // Executing execTask.execute(); File outFile = (outputFile != null ? new File(outputFile) : null); if (configuration.getOutput() != null) { if (new File(configuration.getOutput()).isAbsolute()) { if (output.exists() && output.isFile()) { // outFile = output; final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // outXmlFile.deleteOnExit(); outputFile = setScriptArguments(xmlFile.getAbsolutePath(), output.getAbsolutePath(), outputName, outXmlFile); outFile = new File(configuration.getOutput(), FilenameUtils.getBaseName(outputFile) + ".xml"); FileUtils.copyFile(outXmlFile, outFile); } } else { if (outFile == null) outFile = inputFile; } } else if (outFile == null) { outFile = inputFile; } outEvents.add(new FileSystemEvent(outFile, FileSystemEventType.FILE_ADDED)); } catch (Exception e) { listenerForwarder.failed(e); throw new ActionException(this, e.getMessage(), e); } finally { if (is != null) org.apache.commons.io.IOUtils.closeQuietly(is); } } listenerForwarder.completed(); return outEvents; }
From source file:com.github.rinde.rinsim.core.model.road.PlaneRoadModel.java
@Override protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) { final long startTimeConsumed = time.getTimeConsumed(); Point loc = objLocs.get(object); double traveled = 0; final double speed = min(unitConversion.toInSpeed(object.getSpeed()), maxSpeed); if (speed == 0d) { // FIXME add test for this case, also check GraphRoadModel final Measure<Double, Length> dist = Measure.valueOf(0d, getDistanceUnit()); final Measure<Long, Duration> dur = Measure.valueOf(0L, time.getTimeUnit()); return MoveProgress.create(dist, dur, new ArrayList<Point>()); }/*from www . j a v a 2 s .c o m*/ final List<Point> travelledNodes = new ArrayList<>(); while (time.hasTimeLeft() && !path.isEmpty()) { checkArgument(isPointInBoundary(path.peek()), "points in the path must be within the predefined boundary of the " + "plane"); // distance in internal time unit that can be traveled with timeleft final double travelDistance = speed * unitConversion.toInTime(time.getTimeLeft(), time.getTimeUnit()); final double stepLength = unitConversion.toInDist(Point.distance(loc, path.peek())); if (travelDistance >= stepLength) { loc = path.remove(); travelledNodes.add(loc); final long timeSpent = DoubleMath.roundToLong( unitConversion.toExTime(stepLength / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN); time.consume(timeSpent); traveled += stepLength; } else { final Point diff = Point.diff(path.peek(), loc); if (stepLength - travelDistance < DELTA) { loc = path.peek(); traveled += stepLength; } else { final double perc = travelDistance / stepLength; loc = new Point(loc.x + perc * diff.x, loc.y + perc * diff.y); traveled += travelDistance; } time.consumeAll(); } } objLocs.put(object, loc); // convert to external units final Measure<Double, Length> distTraveled = unitConversion.toExDistMeasure(traveled); final Measure<Long, Duration> timeConsumed = Measure.valueOf(time.getTimeConsumed() - startTimeConsumed, time.getTimeUnit()); return MoveProgress.create(distTraveled, timeConsumed, travelledNodes); }