List of usage examples for java.util LinkedList isEmpty
boolean isEmpty();
From source file:org.opennms.netmgt.eventd.adaptors.tcp.TcpStreamHandler.java
/** * The main execution context for processing a remote XML document. Once the * document is processed and an event receipt is returned to the client the * thread will exit./* w ww. j av a2s . c o m*/ */ @Override public void run() { // get the context and stop if necessary m_context = Thread.currentThread(); synchronized (m_context) { m_context.notifyAll(); } // check the stop flag if (m_stop) { LOG.debug("The stop flag was set prior to thread entry, closing connection"); try { m_connection.close(); } catch (final IOException e) { LOG.error("An error occured while closing the connection.", e); } LOG.debug("Thread context exiting"); return; } // Log the startup of this stream handler final InetAddress sender = m_connection.getInetAddress(); LOG.debug("Event Log Stream Handler Started for {}", sender); /* * This linked list is used to exchange * instances of PipedOutputStreams. Whenever a * pipe output stream is recovered it must be * signaled to inform the EOT thread of the * ability to write to the pipe. Also, when * the descriptor is close a EOFException is * passed on the list. */ final LinkedList<Object> pipeXchange = new LinkedList<Object>(); final TcpRecordHandler chunker = new TcpRecordHandler(m_connection, pipeXchange); final Thread tchunker = new Thread(chunker, "TCPRecord Chunker[" + InetAddressUtils.str(m_connection.getInetAddress()) + ":" + m_connection.getPort() + "]"); synchronized (tchunker) { tchunker.start(); try { tchunker.wait(); } catch (final InterruptedException e) { LOG.error("The thread was interrupted.", e); } } MAINLOOP: while (!m_stop && m_parent.getStatus() != Fiber.STOP_PENDING && m_parent.getStatus() != Fiber.STOPPED && m_recsPerConn != 0) { // get a new pipe input stream PipedInputStream pipeIn = null; synchronized (pipeXchange) { while (pipeXchange.isEmpty()) { if (chunker.isAlive()) { try { pipeXchange.wait(500); } catch (final InterruptedException e) { LOG.error("The thread was interrupted.", e); break MAINLOOP; } } else { break MAINLOOP; } } // if an exception occured then just exit the BAL (Big Ass Loop) final Object o = pipeXchange.removeFirst(); if (o instanceof Throwable) { break MAINLOOP; } // construct the other end of the pipe try { pipeIn = new PipedInputStream((PipedOutputStream) o); } catch (final IOException e) { LOG.error("An I/O exception occured construction a record reader.", e); break MAINLOOP; } // signal that we got the stream synchronized (o) { o.notify(); } } // decrement the record count if greater than zero m_recsPerConn -= (m_recsPerConn > 0 ? 1 : 0); // convert the pipe input stream into a buffered input stream final InputStream stream = new BufferedInputStream(pipeIn); // Unmarshal the XML document Log eLog = null; boolean doCleanup = false; try { eLog = JaxbUtils.unmarshal(Log.class, new InputSource(stream)); LOG.debug("Event record converted"); } catch (final Exception e) { LOG.error("Could not unmarshall the XML record.", e); doCleanup = true; } finally { if (stream != null) { IOUtils.closeQuietly(stream); } } // clean up the data on the current pipe if necessary if (doCleanup) { /* * Cleanup a failed record. Need to read * the remaining bytes from the other thread * to synchronize up. The other thread might * be blocked writing. */ try { while (stream.read() != -1) { /* do nothing */; } } catch (final IOException e) { // do nothing } // start from the top! continue MAINLOOP; } // Now that we have a list of events, process them final Event[] events = eLog.getEvents().getEvent(); // sort the events by time Arrays.sort(events, new Comparator<Event>() { @Override public int compare(final Event e1, final Event e2) { final boolean e1t = (e1.getTime() != null); final boolean e2t = (e2.getTime() != null); if (e1t && !e2t) { return 1; } else if (!e1t && e2t) { return -1; } else if (!e1t && !e2t) { return 0; } Date de1 = e1.getTime(); Date de2 = e2.getTime(); if (de1 != null && de2 != null) { return (int) (de1.getTime() - de2.getTime()); } else if (de1 == null && de2 != null) { return -1; } else if (de1 != null && de2 == null) { return 1; } else { return 0; } } }); // process the events if (events != null && events.length != 0) { final List<Event> okEvents = new ArrayList<Event>(events.length); /* * This synchronization loop will hold onto the lock * for a while. If the handlers are going to change * often, which is shouldn't then might want to consider * duplicating the handlers into an array before processing * the events. * * Doing the synchronization in the outer loop prevents spending * lots of cycles doing synchronization when it should not * normally be necesary. */ synchronized (m_handlers) { for (final EventHandler hdl : m_handlers) { /* * get the handler and then have it process all * the events in the document before moving to the * next event handler. */ for (final Event event : events) { /* * Process the event and log any errors, * but don't die on these errors */ try { LOG.debug("handling event: {}", event); // shortcut and BOTH parts MUST execute! if (hdl.processEvent(event)) { if (!okEvents.contains(event)) { okEvents.add(event); } } } catch (final Throwable t) { LOG.warn("An exception occured while processing an event.", t); } } } } // Now process the good events and send a receipt message boolean hasReceipt = false; final EventReceipt receipt = new EventReceipt(); for (final Event event : okEvents) { if (event.getUuid() != null) { receipt.addUuid(event.getUuid()); hasReceipt = true; } } if (hasReceipt) { // Transform it to XML and send it to the socket in one call try { final Writer writer = new BufferedWriter( new OutputStreamWriter(m_connection.getOutputStream(), "UTF-8")); JaxbUtils.marshal(receipt, writer); writer.flush(); synchronized (m_handlers) { for (final EventHandler hdl : m_handlers) { /* * Get the handler and then have it process all * the events in the document before moving to * the next event hander. */ try { hdl.receiptSent(receipt); } catch (final Throwable t) { LOG.warn("An exception occured while processing an event receipt.", t); } } } if (LOG.isDebugEnabled()) { try { final StringWriter swriter = new StringWriter(); JaxbUtils.marshal(receipt, swriter); LOG.debug("Sent Event Receipt {"); LOG.debug(swriter.getBuffer().toString()); LOG.debug("}"); } catch (final Throwable e) { LOG.error("An error occured during marshalling of event receipt for the log.", e); } } } catch (final IOException e) { LOG.warn("Failed to send event-receipt XML document.", e); break MAINLOOP; } } } else { LOG.debug("The agent sent an empty event stream"); } } try { LOG.debug("stopping record handler"); chunker.stop(); LOG.debug("record handler stopped"); } catch (final InterruptedException e) { LOG.warn("The thread was interrupted while trying to close the record handler.", e); } // regardless of any errors, be sure to release the socket. try { LOG.debug("closing connnection"); m_connection.close(); LOG.debug("connnection closed "); } catch (final IOException e) { LOG.warn("An I/O exception occured while closing the TCP/IP connection.", e); } LOG.debug("Thread exiting"); }
From source file:com.act.lcms.v2.fullindex.Builder.java
protected void extractTriples(Iterator<LCMSSpectrum> iter, List<MZWindow> windows) throws RocksDBException, IOException { /* Warning: this method makes heavy use of ByteBuffers to perform memory efficient collection of values and * conversion of those values into byte arrays that RocksDB can consume. If you haven't already, go read this * tutorial on ByteBuffers: http://mindprod.com/jgloss/bytebuffer.html */* w w w . ja v a 2s. c om*/ * ByteBuffers are quite low-level structures, and they use some terms you need to watch out for: * capacity: The total number of bytes in the array backing the buffer. Don't write more than this. * position: The next index in the buffer to read or write a byte. Moves with each read or write op. * limit: A mark of where the final byte in the buffer was written. Don't read past this. * The remaining() call is affected by the limit. * mark: Ignore this for now, we don't use it. (We'll always, always read buffers from 0.) * * And here are some methods that we'll use often: * clear: Set position = 0, limit = 0. Pretend the buffer is empty, and is ready for more writes. * flip: Set limit = position, then position = 0. This remembers how many bytes were written to the buffer * (as the current position), and then puts the position at the beginning. * Always call this after the write before a read. * rewind: Set position = 0. Buffer is ready for reading, but unless the limit was set we might now know how * many bytes there are to read. Always call flip() before rewind(). Can rewind many times to re-read * the buffer repeatedly. * remaining: How many bytes do we have left to read? Requires an accurate limit value to avoid garbage bytes. * reset: Don't use this. It uses the mark, which we don't need currently. * * Write/read patterns look like: * buffer.clear(); // Clear out anything already in the buffer. * buffer.put(thing1).put(thing2)... // write a bunch of stuff * buffer.flip(); // Prep for reading. Call *once*! * * while (buffer.hasRemaining()) { buffer.get(); } // Read a bunch of stuff. * buffer.rewind(); // Ready for reading again! * while (buffer.hasRemaining()) { buffer.get(); } // Etc. * buffer.reset(); // Forget what was written previously, buffer is ready for reuse. * * We use byte buffers because they're fast, efficient, and offer incredibly convenient means of serializing a * stream of primitive types to their minimal binary representations. The same operations on objects + object * streams require significantly more CPU cycles, consume more memory, and tend to be brittle (i.e. if a class * definition changes slightly, serialization may break). Since the data we're dealing with is pretty simple, we * opt for the low-level approach. */ /* Because we'll eventually use the window indices to map a mz range to a list of triples that fall within that * range, verify that all of the indices are unique. If they're not, we'll end up overwriting the data in and * corrupting the structure of the index. */ ensureUniqueMZWindowIndices(windows); // For every mz window, allocate a buffer to hold the indices of the triples that fall in that window. ByteBuffer[] mzWindowTripleBuffers = new ByteBuffer[windows.size()]; for (int i = 0; i < mzWindowTripleBuffers.length; i++) { /* Note: the mapping between these buffers and their respective mzWindows is purely positional. Specifically, * mzWindows.get(i).getIndex() != i, but mzWindowTripleBuffers[i] belongs to mzWindows.get(i). We'll map windows * indices to the contents of mzWindowTripleBuffers at the very end of this function. */ mzWindowTripleBuffers[i] = ByteBuffer.allocate(Long.BYTES * 4096); // Start with 4096 longs = 8 pages per window. } // Every TMzI gets an index which we'll use later when we're querying by m/z and time. long counter = -1; // We increment at the top of the loop. // Note: we could also write to an mmapped file and just track pointers, but then we might lose out on compression. // We allocate all the buffers strictly here, as we know how many bytes a long and a triple will take. Then reuse! ByteBuffer counterBuffer = ByteBuffer.allocate(Long.BYTES); ByteBuffer valBuffer = ByteBuffer.allocate(TMzI.BYTES); List<Float> timepoints = new ArrayList<>(2000); // We can be sloppy here, as the count is small. /* We use a sweep-line approach to scanning through the m/z windows so that we can aggregate all intensities in * one pass over the current LCMSSpectrum (this saves us one inner loop in our extraction process). The m/z * values in the LCMSSpectrum become our "critical" or "interesting points" over which we sweep our m/z ranges. * The next window in m/z order is guaranteed to be the next one we want to consider since we address the points * in m/z order as well. As soon as we've passed out of the range of one of our windows, we discard it. It is * valid for a window to be added to and discarded from the working queue in one application of the work loop. */ LinkedList<MZWindow> tbdQueueTemplate = new LinkedList<>(windows); // We can reuse this template to init the sweep. int spectrumCounter = 0; while (iter.hasNext()) { LCMSSpectrum spectrum = iter.next(); float time = spectrum.getTimeVal().floatValue(); // This will record all the m/z + intensity readings that correspond to this timepoint. Exactly sized too! ByteBuffer triplesForThisTime = ByteBuffer.allocate(Long.BYTES * spectrum.getIntensities().size()); // Batch up all the triple writes to reduce the number of times we hit the disk in this loop. // Note: huge success! RocksDBAndHandles.RocksDBWriteBatch<ColumnFamilies> writeBatch = dbAndHandles.makeWriteBatch(); // Initialize the sweep line lists. Windows go follow: tbd -> working -> done (nowhere). LinkedList<MZWindow> workingQueue = new LinkedList<>(); LinkedList<MZWindow> tbdQueue = (LinkedList<MZWindow>) tbdQueueTemplate.clone(); // clone is in the docs, so okay! for (Pair<Double, Double> mzIntensity : spectrum.getIntensities()) { // Very important: increment the counter for every triple. Otherwise we'll overwrite triples = Very Bad (tm). counter++; // Brevity = soul of wit! Double mz = mzIntensity.getLeft(); Double intensity = mzIntensity.getRight(); // Reset the buffers so we end up re-using the few bytes we've allocated. counterBuffer.clear(); // Empty (virtually). counterBuffer.putLong(counter); counterBuffer.flip(); // Prep for reading. valBuffer.clear(); // Empty (virtually). TMzI.writeToByteBuffer(valBuffer, time, mz, intensity.floatValue()); valBuffer.flip(); // Prep for reading. // First, shift any applicable ranges onto the working queue based on their minimum mz. while (!tbdQueue.isEmpty() && tbdQueue.peekFirst().getMin() <= mz) { workingQueue.add(tbdQueue.pop()); } // Next, remove any ranges we've passed. while (!workingQueue.isEmpty() && workingQueue.peekFirst().getMax() < mz) { workingQueue.pop(); // TODO: add() this to a recovery queue which can then become the tbdQueue. Edge cases! } /* In the old indexed trace extractor world, we could bail here if there were no target m/z's in our window set * that matched with the m/z of our current mzIntensity. However, since we're now also recording the links * between timepoints and their (t, m/z, i) triples, we need to keep on keepin' on regardless of whether we have * any m/z windows in the working set right now. */ // The working queue should now hold only ranges that include this m/z value. Sweep line swept! /* Now add this intensity to the buffers of all the windows in the working queue. Note that since we're only * storing the *index* of the triple, these buffers are going to consume less space than they would if we * stored everything together. */ for (MZWindow window : workingQueue) { // TODO: count the number of times we add intensities to each window's accumulator for MS1-style warnings. counterBuffer.rewind(); // Already flipped. mzWindowTripleBuffers[window.getIndex()] = // Must assign when calling appendOrRealloc. Utils.appendOrRealloc(mzWindowTripleBuffers[window.getIndex()], counterBuffer); } // We flipped after reading, so we should be good to rewind (to be safe) and write here. counterBuffer.rewind(); valBuffer.rewind(); writeBatch.put(ColumnFamilies.ID_TO_TRIPLE, Utils.toCompactArray(counterBuffer), Utils.toCompactArray(valBuffer)); // Rewind again for another read. counterBuffer.rewind(); triplesForThisTime.put(counterBuffer); } writeBatch.write(); assert (triplesForThisTime.position() == triplesForThisTime.capacity()); ByteBuffer timeBuffer = ByteBuffer.allocate(Float.BYTES).putFloat(time); timeBuffer.flip(); // Prep both bufers for reading so they can be written to the DB. triplesForThisTime.flip(); dbAndHandles.put(ColumnFamilies.TIMEPOINT_TO_TRIPLES, Utils.toCompactArray(timeBuffer), Utils.toCompactArray(triplesForThisTime)); timepoints.add(time); spectrumCounter++; if (spectrumCounter % 1000 == 0) { LOGGER.info("Extracted %d time spectra", spectrumCounter); } } LOGGER.info("Extracted %d total time spectra", spectrumCounter); // Now write all the mzWindow to triple indexes. RocksDBAndHandles.RocksDBWriteBatch<ColumnFamilies> writeBatch = dbAndHandles.makeWriteBatch(); ByteBuffer idBuffer = ByteBuffer.allocate(Integer.BYTES); for (int i = 0; i < mzWindowTripleBuffers.length; i++) { idBuffer.clear(); idBuffer.putInt(windows.get(i).getIndex()); idBuffer.flip(); ByteBuffer triplesBuffer = mzWindowTripleBuffers[i]; triplesBuffer.flip(); // Prep for read. writeBatch.put(ColumnFamilies.WINDOW_ID_TO_TRIPLES, Utils.toCompactArray(idBuffer), Utils.toCompactArray(triplesBuffer)); } writeBatch.write(); dbAndHandles.put(ColumnFamilies.TIMEPOINTS, TIMEPOINTS_KEY, Utils.floatListToByteArray(timepoints)); dbAndHandles.flush(true); }
From source file:com.android.screenspeak.menurules.RuleViewPager.java
@Override public List<ContextMenuItem> getMenuItemsForNode(ScreenSpeakService service, ContextMenuItemBuilder menuItemBuilder, AccessibilityNodeInfoCompat node) { final LinkedList<ContextMenuItem> items = new LinkedList<>(); AccessibilityNodeInfoCompat rootNode = null; AccessibilityNodeInfoCompat pagerNode = null; try {//from w ww.j ava 2s .co m rootNode = AccessibilityNodeInfoUtils.getRoot(node); if (rootNode == null) { return items; } pagerNode = AccessibilityNodeInfoUtils.searchFromBfs(rootNode, FILTER_PAGED); if (pagerNode == null) { return items; } if (AccessibilityNodeInfoUtils.supportsAnyAction(pagerNode, AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD)) { final ContextMenuItem prevPage = menuItemBuilder.createMenuItem(service, Menu.NONE, R.id.viewpager_breakout_prev_page, Menu.NONE, service.getString(R.string.title_viewpager_breakout_prev_page)); items.add(prevPage); } if (AccessibilityNodeInfoUtils.supportsAnyAction(pagerNode, AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD)) { final ContextMenuItem nextPage = menuItemBuilder.createMenuItem(service, Menu.NONE, R.id.viewpager_breakout_next_page, Menu.NONE, service.getString(R.string.title_viewpager_breakout_next_page)); items.add(nextPage); } if (items.isEmpty()) { return items; } final AccessibilityNodeInfoCompat pagerNodeClone = AccessibilityNodeInfoCompat.obtain(pagerNode); final ViewPagerItemClickListener itemClickListener = new ViewPagerItemClickListener(pagerNodeClone); for (ContextMenuItem item : items) { item.setOnMenuItemClickListener(itemClickListener); } return items; } finally { AccessibilityNodeInfoUtils.recycleNodes(rootNode, pagerNode); } }
From source file:org.nuxeo.ecm.core.storage.sql.jdbc.JDBCMapper.java
/** * Uses iterative parentid selection.//from w ww .j a va 2 s . c o m */ protected Set<Serializable> getAncestorsIdsIterative(Collection<Serializable> ids) throws StorageException { PreparedStatement ps = null; try { LinkedList<Serializable> todo = new LinkedList<Serializable>(ids); Set<Serializable> done = new HashSet<Serializable>(); Set<Serializable> res = new HashSet<Serializable>(); while (!todo.isEmpty()) { done.addAll(todo); SQLInfoSelect select = sqlInfo.getSelectParentIds(todo.size()); if (logger.isLogEnabled()) { logger.logSQL(select.sql, todo); } Column what = select.whatColumns.get(0); Column where = select.whereColumns.get(0); ps = connection.prepareStatement(select.sql); int i = 1; for (Serializable id : todo) { where.setToPreparedStatement(ps, i++, id); } ResultSet rs = ps.executeQuery(); countExecute(); todo = new LinkedList<Serializable>(); List<Serializable> debugIds = null; if (logger.isLogEnabled()) { debugIds = new LinkedList<Serializable>(); } while (rs.next()) { Serializable id = what.getFromResultSet(rs, 1); if (id != null) { res.add(id); if (!done.contains(id)) { todo.add(id); } if (logger.isLogEnabled()) { debugIds.add(id); } } } if (logger.isLogEnabled()) { logger.logIds(debugIds, false, 0); } ps.close(); ps = null; } return res; } catch (Exception e) { checkConnectionReset(e); throw new StorageException("Failed to get ancestors ids", e); } finally { if (ps != null) { try { closeStatement(ps); } catch (SQLException e) { log.error(e.getMessage(), e); } } } }
From source file:org.apache.fop.layoutmgr.table.TableStepper.java
/** * Creates the combined element list for a row group. * @param context Active LayoutContext// ww w .j a v a2 s. c o m * @param rows the row group * @param bodyType Indicates what type of body is processed (body, header or footer) * @return the combined element list */ public LinkedList getCombinedKnuthElementsForRowGroup(LayoutContext context, EffRow[] rows, int bodyType) { setup(rows); activateCells(activeCells, 0); calcTotalHeight(); int cumulateLength = 0; // Length of the content accumulated before the break TableContentPosition lastTCPos = null; LinkedList returnList = new LinkedList(); int laststep = 0; int step = getFirstStep(); do { int maxRemainingHeight = getMaxRemainingHeight(); int penaltyOrGlueLen = step + maxRemainingHeight - totalHeight; int boxLen = step - cumulateLength - Math.max(0, penaltyOrGlueLen)/* penalty, if any */; cumulateLength += boxLen + Math.max(0, -penaltyOrGlueLen)/* the glue, if any */; if (log.isDebugEnabled()) { log.debug("Next step: " + step + " (+" + (step - laststep) + ")"); log.debug(" max remaining height: " + maxRemainingHeight); if (penaltyOrGlueLen >= 0) { log.debug(" box = " + boxLen + " penalty = " + penaltyOrGlueLen); } else { log.debug(" box = " + boxLen + " glue = " + (-penaltyOrGlueLen)); } } LinkedList footnoteList = new LinkedList(); //Put all involved grid units into a list List cellParts = new java.util.ArrayList(activeCells.size()); for (Iterator iter = activeCells.iterator(); iter.hasNext();) { ActiveCell activeCell = (ActiveCell) iter.next(); CellPart part = activeCell.createCellPart(); cellParts.add(part); activeCell.addFootnotes(footnoteList); } //Create elements for step TableContentPosition tcpos = new TableContentPosition(getTableLM(), cellParts, rowGroup[activeRowIndex]); if (delayingNextRow) { tcpos.setNewPageRow(rowGroup[activeRowIndex + 1]); } if (returnList.size() == 0) { tcpos.setFlag(TableContentPosition.FIRST_IN_ROWGROUP, true); } lastTCPos = tcpos; // TODO TableStepper should remain as footnote-agnostic as possible if (footnoteList.isEmpty()) { returnList.add(new KnuthBox(boxLen, tcpos, false)); } else { returnList.add(new KnuthBlockBox(boxLen, footnoteList, tcpos, false)); } int effPenaltyLen = Math.max(0, penaltyOrGlueLen); TableHFPenaltyPosition penaltyPos = new TableHFPenaltyPosition(getTableLM()); if (bodyType == TableRowIterator.BODY) { if (!getTableLM().getTable().omitHeaderAtBreak()) { effPenaltyLen += tclm.getHeaderNetHeight(); penaltyPos.headerElements = tclm.getHeaderElements(); } if (!getTableLM().getTable().omitFooterAtBreak()) { effPenaltyLen += tclm.getFooterNetHeight(); penaltyPos.footerElements = tclm.getFooterElements(); } } Keep keep = getTableLM().getKeepTogether(); int stepPenalty = 0; for (Iterator iter = activeCells.iterator(); iter.hasNext();) { ActiveCell activeCell = (ActiveCell) iter.next(); keep = keep.compare(activeCell.getKeepWithNext()); stepPenalty = Math.max(stepPenalty, activeCell.getPenaltyValue()); } if (!rowFinished) { keep = keep.compare(rowGroup[activeRowIndex].getKeepTogether()); } else if (activeRowIndex < rowGroup.length - 1) { keep = keep.compare(rowGroup[activeRowIndex].getKeepWithNext()); keep = keep.compare(rowGroup[activeRowIndex + 1].getKeepWithPrevious()); nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass, rowGroup[activeRowIndex].getBreakAfter()); nextBreakClass = BreakUtil.compareBreakClasses(nextBreakClass, rowGroup[activeRowIndex + 1].getBreakBefore()); } int p = keep.getPenalty(); if (rowHeightSmallerThanFirstStep) { rowHeightSmallerThanFirstStep = false; p = KnuthPenalty.INFINITE; } p = Math.max(p, stepPenalty); int breakClass = keep.getContext(); if (nextBreakClass != Constants.EN_AUTO) { log.trace("Forced break encountered"); p = -KnuthPenalty.INFINITE; //Overrides any keeps (see 4.8 in XSL 1.0) breakClass = nextBreakClass; } returnList.add(new BreakElement(penaltyPos, effPenaltyLen, p, breakClass, context)); if (penaltyOrGlueLen < 0) { returnList.add(new KnuthGlue(-penaltyOrGlueLen, 0, 0, new Position(null), true)); } laststep = step; step = getNextStep(); } while (step >= 0); assert !returnList.isEmpty(); lastTCPos.setFlag(TableContentPosition.LAST_IN_ROWGROUP, true); return returnList; }
From source file:gaffer.gafferpop.GafferPopGraph.java
private Iterator<GafferPopVertex> verticesWithSeedsAndView(final List<ElementSeed> seeds, final View view) { final boolean getAll = null == seeds || seeds.isEmpty(); final LinkedList<Vertex> idVertices = new LinkedList<>(); final GetOperation<? extends ElementSeed, Entity> getOperation; if (getAll) { getOperation = new GetAllEntities.Builder().view(view).build(); } else {/* w w w .j a v a 2 s . co m*/ getOperation = new GetRelatedEntities.Builder().seeds(seeds).view(view).build(); if (null == view || view.getEntityGroups().contains(ID_LABEL)) { for (ElementSeed elementSeed : seeds) { if (elementSeed instanceof EntitySeed) { idVertices.add(new GafferPopVertex(ID_LABEL, ((EntitySeed) elementSeed).getVertex(), this)); } } } } final Iterable<GafferPopVertex> result = execute( new Builder().first(getOperation).then(new GenerateObjects.Builder<Entity, GafferPopVertex>() .generator(new GafferPopVertexGenerator(this)).build()).build()); return idVertices.isEmpty() ? result.iterator() : new WrappedIterable<GafferPopVertex>(result, idVertices).iterator(); }
From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.AddExerciseAction.java
@Override public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON); User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT); JsonElement titleElement = json.get(Constants.ACTION_PARAM_TITLE); JsonElement topicsElement = json.get(Constants.ACTION_PARAM_TOPICS); JsonElement descriptionElement = json.get(Constants.ACTION_PARAM_DESCRIPTION); JsonElement difficultyElement = json.get(Constants.ACTION_PARAM_DIFFICULTY); JsonElement technologyElement = json.get(Constants.ACTION_PARAM_TECHNOLOGY); JsonElement durationElement = json.get(Constants.ACTION_PARAM_DURATION); JsonElement trophyTitleElement = json.get(Constants.ACTION_PARAM_TROPHY_TITLE); JsonElement trophyDescriptionElement = json.get(Constants.ACTION_PARAM_TROPHY_DESCRIPTION); JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS); JsonElement typeElement = json.get(Constants.ACTION_PARAM_TYPE); JsonElement authorElement = json.get(Constants.ACTION_PARAM_AUTHOR); AvailableExercise exercise = new AvailableExercise(); exercise.setDescription(descriptionElement.getAsString()); exercise.setDifficulty(difficultyElement.getAsString()); exercise.setDuration(durationElement.getAsInt()); exercise.setTitle(titleElement.getAsString()); exercise.setSubtitle(topicsElement.getAsString()); exercise.setTechnology(technologyElement.getAsString()); exercise.setStatus(AvailableExerciseStatus.getStatusFromStatusCode(statusElement.getAsInt())); exercise.setAuthor(authorElement.getAsString()); exercise.setUuid(UUID.randomUUID().toString()); exercise.setVersion(0);/* w w w. jav a 2 s . c o m*/ AvailableExerciseType validType = AvailableExerciseType.getStatusFromName(typeElement.getAsString()); if (validType == null) validType = AvailableExerciseType.BOTH; exercise.setExerciseType(validType); Trophy trophy = new Trophy(); trophy.setDescription(trophyDescriptionElement.getAsString()); trophy.setName(trophyTitleElement.getAsString()); trophy.setTechnology(exercise.getTechnology()); exercise.setTrophy(trophy); JsonElement flags = json.get(Constants.ACTION_PARAM_FLAGS_LIST); JsonElement infos = json.get(Constants.ACTION_PARAM_INFO_LIST); JsonElement resources = json.get(Constants.ACTION_PARAM_RESOURCE_LIST); JsonElement referenceFile = json.get(Constants.ACTION_PARAM_REFERENCE_FILE); if (null != referenceFile) { JsonObject referenceFileObj = referenceFile.getAsJsonObject(); String tmpReferenceFileString = referenceFileObj.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpReferenceFile = null; try { tmpReferenceFileString = tmpReferenceFileString.replaceFirst("(.*);base64,", ""); tmpReferenceFile = Base64.decodeBase64(tmpReferenceFileString); } catch (Exception e) { logger.warn("ReferenceFile Parsing error for user " + sessionUser.getIdUser() + " in adding exercise " + titleElement.getAsString() + " due to: " + e.getMessage(), response); } if (null != tmpReferenceFile && tmpReferenceFile.length != 0) { AvailableExerciseReferenceFile refFile = new AvailableExerciseReferenceFile(); refFile.setFile(tmpReferenceFile); refFile.setFilename(referenceFileObj.get(Constants.ACTION_PARAM_NAME).getAsString()); exercise.setReferenceFile(refFile); exercise.setReferenceFileAvailable(true); } else { exercise.setReferenceFileAvailable(false); } } else { exercise.setReferenceFileAvailable(false); } JsonElement solutionFile = json.get(Constants.ACTION_PARAM_SOLUTION_FILE); JsonObject solutionFileObj = solutionFile.getAsJsonObject(); String tmpSolutionFileString = solutionFileObj.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpSolutioneFile = null; try { tmpSolutionFileString = tmpSolutionFileString.replaceFirst("(.*);base64,", ""); tmpSolutioneFile = Base64.decodeBase64(tmpSolutionFileString); } catch (Exception e) { MessageGenerator.sendErrorMessage("solutioneFileParsing", response); return; } if (null == tmpSolutioneFile || tmpSolutioneFile.length == 0) { MessageGenerator.sendErrorMessage("solutioneFileEmpty", response); return; } AvailableExerciseSolutionFile solFile = new AvailableExerciseSolutionFile(); solFile.setFilename(solutionFileObj.get(Constants.ACTION_PARAM_NAME).getAsString()); solFile.setFile(tmpSolutioneFile); exercise.setSolutionFile(solFile); Map<String, String> resourceMap = new HashMap<String, String>(); for (JsonElement resourceElem : resources.getAsJsonArray()) { JsonObject tmpResource = resourceElem.getAsJsonObject(); resourceMap.put(tmpResource.get(Constants.ACTION_PARAM_TITLE).getAsString(), tmpResource.get(Constants.ACTION_PARAM_URL).getAsString()); } exercise.setResources(resourceMap); LinkedList<AvailableExerciseInfo> infoList = new LinkedList<AvailableExerciseInfo>(); int n = 0; for (JsonElement infoElem : infos.getAsJsonArray()) { JsonObject tmpInfo = infoElem.getAsJsonObject(); AvailableExerciseInfo tmpExInfo = new AvailableExerciseInfo(); tmpExInfo.setTitle(tmpInfo.get(Constants.ACTION_PARAM_TITLE).getAsString()); tmpExInfo.setDescription(tmpInfo.get(Constants.ACTION_PARAM_DESCRIPTION).getAsString()); tmpExInfo.setInfoOrder(n); JsonObject tmpImage = tmpInfo.get(Constants.ACTION_PARAM_IMAGE).getAsJsonObject(); String imageString = tmpImage.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpImageFile = null; try { imageString = imageString.replaceFirst("(.*);base64,", ""); tmpImageFile = Base64.decodeBase64(imageString); } catch (Exception e) { MessageGenerator.sendErrorMessage("infoImageParsing", response); return; } tmpExInfo.setImage(tmpImageFile); infoList.add(tmpExInfo); n++; } exercise.setInfoList(infoList); if (infoList.isEmpty()) { MessageGenerator.sendErrorMessage("infoListEmpty", response); return; } Integer totalScore = 0; LinkedList<Flag> flagList = new LinkedList<Flag>(); for (JsonElement flagElem : flags.getAsJsonArray()) { Flag flag = new Flag(); JsonObject tmpFlag = flagElem.getAsJsonObject(); JsonElement flagTitle = tmpFlag.get(Constants.ACTION_PARAM_TITLE); JsonElement flagCategory = tmpFlag.get(Constants.ACTION_PARAM_CATEGORY); JsonElement flagQuestions = tmpFlag.get(Constants.ACTION_PARAM_FLAG_QUESTIONS); flag.setCategory(flagCategory.getAsString()); flag.setTitle(flagTitle.getAsString()); LinkedList<FlagQuestion> questionList = new LinkedList<FlagQuestion>(); for (JsonElement questionElem : flagQuestions.getAsJsonArray()) { FlagQuestion tmpQuestion = new FlagQuestion(); JsonObject qEl = questionElem.getAsJsonObject(); tmpQuestion.setType(qEl.get(Constants.ACTION_PARAM_TYPE).getAsString()); tmpQuestion.setOptional(qEl.get(Constants.ACTION_PARAM_OPTIONAL).getAsBoolean()); if (!tmpQuestion.getOptional()) { tmpQuestion.setMaxScore(qEl.get(Constants.ACTION_PARAM_MAX_SCORE).getAsInt()); totalScore += tmpQuestion.getMaxScore(); } tmpQuestion .setSelfCheckAvailable(qEl.get(Constants.ACTION_PARAM_SELF_CHECK_AVAILABLE).getAsBoolean()); if (tmpQuestion.getSelfCheckAvailable()) tmpQuestion.setSelfCheckName(qEl.get(Constants.ACTION_PARAM_SELF_CHECK).getAsString()); else tmpQuestion.setSelfCheckName(null); tmpQuestion.setInstructions(qEl.get(Constants.ACTION_PARAM_INSTRUCTIONS).getAsString()); tmpQuestion.setHintAvailable(qEl.get(Constants.ACTION_PARAM_HINT_AVAILABLE).getAsBoolean()); if (tmpQuestion.getHintAvailable()) { FlagQuestionHint tmpQuestionHint = new FlagQuestionHint(); tmpQuestionHint.setType(tmpQuestion.getType()); Gson gson = new Gson(); FlagQuestionHint newHint = gson.fromJson(qEl.get(Constants.ACTION_PARAM_HINT).getAsJsonObject(), FlagQuestionHint.class); if (null != newHint) { tmpQuestionHint.setText(newHint.getText()); if (!tmpQuestion.getOptional()) tmpQuestionHint.setScoreReducePercentage(newHint.getScoreReducePercentage()); tmpQuestion.setHint(tmpQuestionHint); } else { MessageGenerator.sendErrorMessage("hintEmpty", response); return; } } else { tmpQuestion.setHint(null); } questionList.add(tmpQuestion); } flag.setFlagQuestionList(questionList); flagList.add(flag); } exercise.setFlags(flagList); if (flagList.isEmpty()) { MessageGenerator.sendErrorMessage("flagListEmpty", response); return; } exercise.setScore(totalScore); Integer id = hpc.addAvailableExercise(exercise); if (null != id) MessageGenerator.sendSuccessMessage(response); else MessageGenerator.sendErrorMessage("Error", response); }
From source file:com.rapleaf.hank.storage.incremental.IncrementalPartitionUpdater.java
/** * Return the list of versions needed to update to the specific version given that * the specified current version and cached bases are available. * * @param currentVersion//w w w . j av a 2 s . co m * @param cachedBases * @param updatingToVersion * @return * @throws java.io.IOException */ protected IncrementalUpdatePlan computeUpdatePlan(DomainVersion currentVersion, Set<DomainVersion> cachedBases, DomainVersion updatingToVersion) throws IOException { LinkedList<DomainVersion> updatePlanVersions = new LinkedList<DomainVersion>(); // Backtrack versions (ignoring defunct versions) until we find: // - a base (no parent) // - or the current version (which is by definition a base or a rebased delta) // - or a version that is a base and that is cached DomainVersion parentVersion = updatingToVersion; while (parentVersion != null) { // Ignore completely defunct versions if (!parentVersion.isDefunct()) { // If a version along the path is still open, abort if (!DomainVersions.isClosed(parentVersion)) { throw new IOException("Detected a domain version that is still open" + " along the path from current version to version to update to: " + " domain: " + domain + " open version: " + parentVersion + " current version: " + currentVersion + " updating to version: " + updatingToVersion); } // If backtrack to current version, use it and stop backtracking if (currentVersion != null && parentVersion.equals(currentVersion)) { // If we only need the current version, we don't need any plan if (updatePlanVersions.isEmpty()) { return null; } else { updatePlanVersions.add(parentVersion); break; } } // If backtrack to cached base version, use it and stop backtracking if (cachedBases.contains(parentVersion)) { updatePlanVersions.add(parentVersion); break; } // Add backtracked version to versions needed updatePlanVersions.add(parentVersion); } // Move to parent version parentVersion = getParentDomainVersion(parentVersion); } if (updatePlanVersions.isEmpty()) { return null; } // The base is the last version that was added (a base, the current version or a cached base) DomainVersion base = updatePlanVersions.removeLast(); // Reverse list of deltas as we have added versions going backwards Collections.reverse(updatePlanVersions); return new IncrementalUpdatePlan(base, updatePlanVersions); }
From source file:io.apptik.widget.MultiSlider.java
@Override public boolean onTouchEvent(MotionEvent event) { if (!mIsUserSeekable || !isEnabled()) { return false; }//from w w w .j av a 2 s. c o m int pointerIdx = event.getActionIndex(); Thumb currThumb = null; if (mDraggingThumbs.size() > pointerIdx) { currThumb = mDraggingThumbs.get(pointerIdx); } else { LinkedList<Thumb> closestOnes = getClosestThumb((int) event.getX(event.getActionIndex())); if (closestOnes != null && !closestOnes.isEmpty()) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN || event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { if (closestOnes.size() == 1) { currThumb = closestOnes.getFirst(); onStartTrackingTouch(currThumb); drawableStateChanged(); } else { //we have more than one thumb at the same place and we touched there exactTouched = closestOnes; } } else if (exactTouched != null && !exactTouched.isEmpty() && event.getActionMasked() == MotionEvent.ACTION_MOVE) { //we have thumbs waiting to be selected to move currThumb = getMostMovable(exactTouched, event); //check if move actually changed value if (currThumb == null) return false; exactTouched = null; onStartTrackingTouch(currThumb); drawableStateChanged(); } else { currThumb = closestOnes.getFirst(); onStartTrackingTouch(currThumb); drawableStateChanged(); } } } switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (isInScrollingContainer()) { mTouchDownX = event.getX(); } else { //currThumb = getClosestThumb(newValue); //onStartTrackingTouch(currThumb); setPressed(true); if (currThumb != null && currThumb.getThumb() != null) { invalidate(currThumb.getThumb().getBounds()); // This may be within the padding region } int value = getValue(event, currThumb); setThumbValue(currThumb, value, true); attemptClaimDrag(); } break; case MotionEvent.ACTION_POINTER_DOWN: if (isInScrollingContainer()) { mTouchDownX = event.getX(); } else { //currThumb = getClosestThumb(newValue); //onStartTrackingTouch(currThumb); setPressed(true); if (currThumb != null && currThumb.getThumb() != null) { invalidate(currThumb.getThumb().getBounds()); // This may be within the padding region } setThumbValue(currThumb, getValue(event, currThumb), true); attemptClaimDrag(); } invalidate(); break; //with move we dont have pointer action so set them all case MotionEvent.ACTION_MOVE: if (!mDraggingThumbs.isEmpty()) { //need the index for (int i = 0; i < mDraggingThumbs.size(); i++) { setPressed(true); if (mDraggingThumbs.get(i) != null && mDraggingThumbs.get(i).getThumb() != null) { invalidate(mDraggingThumbs.get(i).getThumb().getBounds()); // This may be within the padding region } setThumbValue(mDraggingThumbs.get(i), getValue(event, i, mDraggingThumbs.get(i)), true); attemptClaimDrag(); } } else { final float x = event.getX(); if (Math.abs(x - mTouchDownX) > mScaledTouchSlop) { //currThumb = getClosestThumb(newValue); //onStartTrackingTouch(currThumb); setPressed(true); if (currThumb != null && currThumb.getThumb() != null) { invalidate(currThumb.getThumb().getBounds()); // This may be within the padding region } setThumbValue(currThumb, getValue(event, currThumb), true); attemptClaimDrag(); } } break; //there are other pointers left case MotionEvent.ACTION_POINTER_UP: if (currThumb != null) { setThumbValue(currThumb, getValue(event, currThumb), true); onStopTrackingTouch(currThumb); } else { // currThumb = getClosestThumb(newValue); // // Touch up when we never crossed the touch slop threshold should // // be interpreted as a tap-seek to that location. // onStartTrackingTouch(currThumb); // setThumbValue(currThumb, newValue, true); // onStopTrackingTouch(currThumb); } // ProgressBar doesn't know to repaint the thumb drawable // in its inactive state when the touch stops (because the // value has not apparently changed) invalidate(); break; //we normally have one single pointer here and its gone now case MotionEvent.ACTION_UP: if (currThumb != null) { int value = getValue(event, currThumb); setThumbValue(currThumb, value, true); onStopTrackingTouch(currThumb); } else { // currThumb = getClosestThumb(newValue); // // Touch up when we never crossed the touch slop threshold should // // be interpreted as a tap-seek to that location. // onStartTrackingTouch(currThumb); // setThumbValue(currThumb, newValue, true); // onStopTrackingTouch(); } setPressed(false); // ProgressBar doesn't know to repaint the thumb drawable // in its inactive state when the touch stops (because the // value has not apparently changed) invalidate(); break; case MotionEvent.ACTION_CANCEL: if (mDraggingThumbs != null) { onStopTrackingTouch(); setPressed(false); } invalidate(); // see above explanation break; } return true; }
From source file:org.jahia.services.templates.ModuleBuildHelper.java
private boolean saveFile(InputStream source, File target) throws IOException { Charset transCodeTarget = null; if (target.getParentFile().getName().equals("resources") && target.getName().endsWith(".properties")) { transCodeTarget = Charsets.ISO_8859_1; }/*www . j ava 2s . c o m*/ if (!target.exists()) { if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) { throw new IOException("Unable to create path for: " + target.getParentFile()); } if (target.getParentFile().isFile()) { target.getParentFile().delete(); target.getParentFile().mkdirs(); } if (transCodeTarget != null) { FileUtils.writeLines(target, transCodeTarget.name(), convertToNativeEncoding(IOUtils.readLines(source, Charsets.UTF_8), transCodeTarget), "\n"); } else { FileOutputStream output = FileUtils.openOutputStream(target); try { IOUtils.copy(source, output); output.close(); } finally { IOUtils.closeQuietly(output); } } // Save repository.xml file after first generation if (target.getName().equals("repository.xml")) { FileUtils.copyFile(target, new File(target.getPath() + ".generated")); } return true; } else { List<String> targetContent = FileUtils.readLines(target, transCodeTarget != null ? transCodeTarget : Charsets.UTF_8); if (!isBinary(targetContent)) { File previouslyGenerated = new File(target.getPath() + ".generated"); List<String> previouslyGeneratedContent = targetContent; if (previouslyGenerated.exists()) { previouslyGeneratedContent = FileUtils.readLines(previouslyGenerated, transCodeTarget != null ? transCodeTarget : Charsets.UTF_8); } DiffMatchPatch dmp = new DiffMatchPatch(); List<String> sourceContent = IOUtils.readLines(source, Charsets.UTF_8); if (transCodeTarget != null) { sourceContent = convertToNativeEncoding(sourceContent, transCodeTarget); } LinkedList<DiffMatchPatch.Patch> l = dmp.patch_make( StringUtils.join(previouslyGeneratedContent, "\n"), StringUtils.join(sourceContent, "\n")); if (target.getName().equals("repository.xml")) { // Keep generated file uptodate FileUtils.writeLines(new File(target.getPath() + ".generated"), transCodeTarget != null ? transCodeTarget.name() : "UTF-8", sourceContent); } if (!l.isEmpty()) { Object[] objects = dmp.patch_apply(l, StringUtils.join(targetContent, "\n")); for (boolean b : ((boolean[]) objects[1])) { if (!b) { throw new IOException("Cannot apply modification on " + target.getName() + ", check generated file at : " + target.getPath() + ".generated"); } } FileUtils.write(target, (CharSequence) objects[0], transCodeTarget != null ? transCodeTarget.name() : "UTF-8"); return true; } } else { byte[] sourceArray = IOUtils.toByteArray(source); FileInputStream input = new FileInputStream(target); FileOutputStream output = null; try { byte[] targetArray = IOUtils.toByteArray(input); if (!Arrays.equals(sourceArray, targetArray)) { output = new FileOutputStream(target); IOUtils.write(sourceArray, output); return true; } } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } } return false; }