List of usage examples for java.util LinkedList getFirst
public E getFirst()
From source file:org.apache.impala.infra.tableflattener.SchemaFlattener.java
private void createChildDataset(String name, Schema srcSchema, LinkedList<Field> parentFields, FlattenedSchema parentDataset) { // Ensure that the parent schema has an id field so the child can reference the // parent. A single id field is sufficient. if (parentFields.isEmpty() || !parentFields.getFirst().name().equals(parentDataset.getIdFieldName())) { parentFields.addFirst(SchemaUtil.createField(parentDataset.getIdFieldName(), Type.LONG)); }/* ww w .j ava2 s . c o m*/ FlattenedSchema childDataset = new FlattenedSchema(name, parentDataset); LinkedList<Field> fields = Lists.newLinkedList(); String parentIdFieldName = parentDataset.getName() + childDataset.getNameSeparator() + childDataset.getIdFieldName(); Field parentIdField = SchemaUtil.createField(parentIdFieldName, Type.LONG); childDataset.setParentIdField(parentIdField); fields.add(parentIdField); Schema valueSchema; if (srcSchema.getType() == Type.ARRAY) { fields.add(SchemaUtil.createField(childDataset.getArrayIdxFieldName(), Type.LONG)); valueSchema = srcSchema.getElementType(); } else { Preconditions.checkState(srcSchema.getType() == Type.MAP); fields.add(SchemaUtil.createField(childDataset.getMapKeyFieldName(), Type.STRING)); valueSchema = srcSchema.getValueType(); } if (SchemaUtil.isSimpleType(valueSchema)) { fields.add(SchemaUtil.createField(childDataset.getCollectionValueFieldName(), valueSchema)); } else { if (SchemaUtil.isNullable(valueSchema)) { fields.add(SchemaUtil.createField( childDataset.getIsNullFieldName(childDataset.getCollectionValueFieldName()), Type.BOOLEAN)); valueSchema = SchemaUtil.reduceUnionToNonNull(valueSchema); } if (SchemaUtil.requiresChildDataset(valueSchema)) { createChildDataset(childDataset.getChildOfCollectionName(), valueSchema, fields, childDataset); } else { addRecordFields(valueSchema, childDataset, fields, childDataset.getCollectionValueFieldName() + childDataset.getNameSeparator()); } } finishCreatingDataset(fields, childDataset); }
From source file:org.quickconnectfamily.json.JSONParser.java
@SuppressWarnings("rawtypes") private int peekStatus(LinkedList statusStack) { if (statusStack.size() == 0) return -1; Integer status = (Integer) statusStack.getFirst(); return status.intValue(); }
From source file:eu.stratosphere.nephele.multicast.MulticastManager.java
/** * Returns the TreeNode which is closest to the given indicator Node. Proximity is determined * either using topology-information (if given), penalty information (if given) or it returns * the first node in the list.//from ww w .ja va 2 s . c om * * @param indicator * @param nodes * @return */ private TreeNode getClosestNode(final TreeNode indicator, final LinkedList<TreeNode> nodes) { if (indicator == null) { return nodes.getFirst(); } TreeNode closestNode = null; for (TreeNode n : nodes) { if (closestNode == null || n.getDistance(indicator) < closestNode.getDistance(indicator)) { closestNode = n; } } return closestNode; }
From source file:cn.keke.travelmix.publictransport.type.EfaConnectionResponseHandler.java
public RouteResult readRouteInfo(LinkedList<PartialRoute> partialRoutes) { String startPoint = partialRoutes.getFirst().getOriginLocation().getName(); String endPoint = partialRoutes.getLast().getDestinationLocation().getName(); long individualTotalDistance = 0; int individualTotalTimeMinute = 0; List<Coordinate> coordinates = new LinkedList<Coordinate>(); List<Instruction> instructions = new LinkedList<Instruction>(); for (PartialRoute partialRoute : partialRoutes) { if (partialRoute.getType() == TransportType.IT) { individualTotalTimeMinute += partialRoute.getTimeMinute(); individualTotalDistance += partialRoute.getDistance(); }/*from w w w.j a v a 2s . co m*/ LocationPoint originLocation = partialRoute.getOriginLocation(); coordinates.add(originLocation.getCoordinate()); int idx = coordinates.size() - 1; Instruction instruction = createOriginLocationInstruction(partialRoute, originLocation, idx); instructions.add(instruction); if (partialRoute.getType() == TransportType.IT) { for (PathDescription description : partialRoute.getDescriptions()) { instruction = new Instruction(partialRoute.getMot(), createInstruction(description.getDirection(), description.getStreet()), description.getDistance(), description.getCoordIdxFrom() + idx, description.getDuration(), createDistanceText(description.getDistance()), description.getSkyDirection(), description.getDirection()); instructions.add(instruction); // System.out.println(instruction.getInstructionText()); } } coordinates.addAll(partialRoute.getCoordinates()); LocationPoint destinationLocation = partialRoute.getDestinationLocation(); coordinates.add(destinationLocation.getCoordinate()); idx = coordinates.size() - 1; instruction = createDestinationLocationInstruction(partialRoute, destinationLocation, idx); instructions.add(instruction); } long totalDistance = getTotalDistance(coordinates); int totalTimeMinute = getLocationMinutesDiff(partialRoutes.getFirst().getOriginLocation(), partialRoutes.getLast().getDestinationLocation()); RouteResult result = new RouteResult(startPoint, endPoint, totalDistance, totalTimeMinute * 60, individualTotalDistance, individualTotalTimeMinute * 60, coordinates, instructions); return result; }
From source file:fi.hsl.parkandride.back.UtilizationDao.java
@Transactional(readOnly = true, isolation = READ_COMMITTED, propagation = MANDATORY) @Override/*from w w w .ja v a2s . c o m*/ public List<Utilization> findUtilizationsWithResolution(UtilizationKey utilizationKey, DateTime start, DateTime end, Minutes resolution) { ArrayList<Utilization> results = new ArrayList<>(); Optional<Utilization> first = findUtilizationAtInstant(utilizationKey, start); try (CloseableIterator<Utilization> rest = findUtilizationsBetween(utilizationKey, start, end)) { LinkedList<Utilization> utilizations = Stream .concat(StreamUtil.asStream(first), StreamUtil.asStream(rest)) .collect(Collectors.toCollection(LinkedList::new)); Utilization current = null; for (DateTime instant = start; !instant.isAfter(end); instant = instant.plus(resolution)) { while (!utilizations.isEmpty() && !utilizations.getFirst().timestamp.isAfter(instant)) { current = utilizations.removeFirst(); } if (current != null) { current.timestamp = instant; results.add(current.copy()); } } } return results; }
From source file:org.eurekastreams.server.service.opensocial.spi.PersonServiceImpl.java
/** * This is the implementation of the getPerson method specified by Shindig. This is how Shindig's OpenSocial api * will interact with our database./*from ww w. j a v a 2s. c o m*/ * * @param id * - userid making the request. * @param fields * - set of fields to be retrieved with this request. * @param token * - token that goes with this request. * * @return instance of Person object */ public Future<Person> getPerson(final UserId id, final Set<String> fields, final SecurityToken token) { log.trace("Entering getPerson"); Person osPerson = new PersonImpl(); String openSocialId = null; // Retrieve the user id. if (id.getUserId(token) != null) { openSocialId = id.getUserId(token); } else // userId is null and so is the type cannot proceed. { log.debug("Id of the person requested was null"); throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "No id supplied"); } try { log.debug("User id requested is: " + openSocialId); LinkedList<String> userIdList = new LinkedList<String>(); userIdList.add(openSocialId); // Build up request to retrieve a single person. GetPeopleByOpenSocialIdsRequest currentRequest = new GetPeopleByOpenSocialIdsRequest(userIdList, Type.all.toString()); // Create the actionContext PrincipalActionContext ac = new ServiceActionContext(currentRequest, getPrincipal(token)); // execute action. LinkedList<PersonModelView> people = (LinkedList<PersonModelView>) serviceActionController .execute((ServiceActionContext) ac, getPeopleAction); if (people.size() > 0) { osPerson = convertToOSPerson(people.getFirst()); } } catch (NumberFormatException e) { log.error("number format exception " + e.getMessage()); throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "Id supplied is bad."); } catch (Exception e) { log.error("Error occurred retrieving person " + e.getMessage()); throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } return ImmediateFuture.newInstance(osPerson); }
From source file:jext2.DataInode.java
/** * Write data in buffer to disk. This works best when whole blocks which * are a multiple of blocksize in size are written. Partial blocks are * written by first reading the block and then writing the new data * to that buffer than write that new buffer to disk. * @throws NoSpaceLeftOnDevice/*w ww. j av a2s . c o m*/ * @throws FileTooLarge */ public int writeData(ByteBuffer buf, long offset) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge { /* * Note on sparse file support: * getBlocksAllocate does not care if there are holes. Just write as much * blocks as the buffer requires at the desired location an set inode.size * accordingly. */ int blocksize = superblock.getBlocksize(); long start = offset / blocksize; long end = (buf.capacity() + blocksize) / blocksize + start; int startOff = (int) (offset % blocksize); if (startOff > 0) end += 1; buf.rewind(); while (start < end) { LinkedList<Long> blockNrs = accessData().getBlocksAllocate(start, 1); int bytesLeft = buf.capacity() - buf.position(); if (bytesLeft < blocksize || startOff > 0) { /* write partial block */ ByteBuffer onDisk = blockAccess.read(blockNrs.getFirst()); onDisk.position(startOff); assert onDisk.limit() == blocksize; buf.limit(buf.position() + Math.min(bytesLeft, onDisk.remaining())); onDisk.put(buf); onDisk.position(startOff); blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, onDisk); } else { /* write whole block */ buf.limit(buf.position() + blocksize); blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, buf); } start += 1; startOff = 0; accessData().unlockHierarchyChanges(); } int written = buf.position(); assert written == buf.capacity(); /* increase inode.size if we grew the file */ if (offset + written > getSize()) { /* file grew */ setStatusChangeTime(new Date()); setSize(offset + written); } return written; }
From source file:org.mycore.common.content.transformer.MCRXSLTransformer.java
protected XMLReader getXMLReader(LinkedList<TransformerHandler> transformHandlerList) throws SAXException { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(ENTITY_RESOLVER); reader.setContentHandler(transformHandlerList.getFirst()); return reader; }
From source file:playground.johannes.socialnets.NetworkGenerator2.java
public SocialNetwork generate(Population population) { random = new Random(); logger.info("Initializing social network..."); SocialNetwork net = new SocialNetwork(); for (Person p : population) { egoList.add(net.addEgo(p));//from w w w . j ava2s. co m } logger.info("Initializing degree distribution..."); TObjectIntHashMap<Ego> stubsMap = initDegreeDistribution(net.getVertices()); // try { // dumpStats(net, null, 0); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } LinkedList<Ego> pendingNodes = new LinkedList<Ego>(net.getVertices()); Collections.shuffle(pendingNodes); while (!pendingNodes.isEmpty()) { logger.info("Starting new component..."); Ego v1 = pendingNodes.getFirst(); Collection<Ego> nextWave = new HashSet<Ego>(); int stubs = stubsMap.get(v1); for (int i = 0; i < stubs; i++) { Ego n1 = findNeighbour(v1, egoList, stubsMap, false); if (n1 == null) { pendingNodes.remove(v1); break; } if (!formConnection(v1, n1, net, stubsMap)) { /* * Should never happen (?) */ int v2stubs = stubsMap.get(v1); int v3stubs = stubsMap.get(n1); System.err.println("The selected neighbour is not valid!" + " v2stubs=" + v2stubs + ", v3stubs=" + v3stubs); System.exit(-1); } else { nextWave.add(n1); if (stubsMap.get(n1) == 0) pendingNodes.remove(n1); } } if (stubsMap.get(v1) == 0) pendingNodes.remove(v1); while (!nextWave.isEmpty()) { nextWave = closeTriads(nextWave, stubsMap, pendingNodes, net); } } int sum = 0; for (int val : stubsMap.getValues()) { sum += val; } System.err.println(sum + " stubs left!"); return net; }
From source file:com.scm.reader.livescanner.search.ImageRecognizer.java
/** * @param context/* w ww . j av a2 s. c o m*/ * @param data * @param dataToPopulate * @return * @throws IOException * @throws JSONException * @return Search object * * TODO refactor and make this method more readable if time */ public Search parseJSON(Context context, String data, Search dataToPopulate) throws IOException, JSONException { dataToPopulate.setSearchTime(new Date()); dataToPopulate.setPending(false); JSONObject jObject; jObject = new JSONObject(data); dataToPopulate.setUuid(jObject.getString("query_id")); JSONArray resultArray = (JSONArray) jObject.get("results"); //no results if (resultArray.length() == 0) { dataToPopulate.setRecognized(false); dataToPopulate.setTitle(context.getResources().getString(R.string.image_not_recognized_title)); dataToPopulate.setUrl("http://"); } //only one item result else if (resultArray.length() < 2) { System.out.println("only one item result"); JSONObject result = resultArray.getJSONObject(0); JSONArray recognitions = result.getJSONArray("recognitions"); dataToPopulate.setRecognized(true); //dataToPopulate.setTitle(result.getString("title")); JSONArray metaDataArray = result.getJSONArray("metadata"); JSONObject metaDataObj = metaDataArray.getJSONObject(0); JSONObject recognition = recognitions.getJSONObject(0); //setting right language String title = extractFromLanguageString(metaDataObj.getJSONObject("title")); dataToPopulate.setTitle(title); String subtitle = extractFromLanguageString(metaDataObj.getJSONObject("subtitle")); dataToPopulate.setDetail(subtitle); dataToPopulate.setItemUuid(metaDataObj.getString("uuid")); String url = ""; if (metaDataObj.has("response")) { System.out.println("direct response"); JSONObject responseObject = metaDataObj.getJSONObject("response"); url = responseObject.getString("content"); LogUtils.logDebug("response qurl " + url); System.out.println(url); } else { System.out.println("normal response"); url = createResultUrl(metaDataObj.getString("uuid"), recognition.getString("id")); LogUtils.logDebug("normal response response qurl " + url); } dataToPopulate.setUrl(url); } //multiple results else { //reading objects inside "results" node //inserting ads first for (int i = 0; i < resultArray.length(); i++) { JSONObject result = resultArray.getJSONObject(i); JSONArray metaDataArray = result.getJSONArray("metadata"); JSONObject metaDataObj = metaDataArray.getJSONObject(0); boolean hasKind = false; for (int ind = 0; ind < metaDataArray.length(); ind++) { if (metaDataArray.getJSONObject(ind).has("kind")) { hasKind = true; break; } } if (hasKind) { if (!dataToPopulate.hasSections() && metaDataObj.getString("kind").equals("Ad")) { dataToPopulate.addSection(parseSectionJSON(resultArray, result)); } } } //inserting everything else than ads for (int i = 0; i < resultArray.length(); i++) { JSONObject result = resultArray.getJSONObject(i); JSONArray metaDataArray = result.getJSONArray("metadata"); JSONObject metaDataObj = metaDataArray.getJSONObject(0); dataToPopulate.setTitle(context.getResources().getString(R.string.multiple_matches)); if (dataToPopulate.hasSections()) { //checking that there is no two of same headers /** * If any of the sections contains same header the insert boolean * will be set false and loop is determined */ boolean insert = false; for (int index = 0; index < dataToPopulate.getSections().size(); index++) { if (!metaDataObj.has("kind")) { break; } SearchResultSection section = dataToPopulate.getSections().get(index); if (!metaDataObj.getString("kind").equals(section.getHeader())) { insert = true; } else { insert = false; break; } } if (insert) { dataToPopulate.addSection(parseSectionJSON(resultArray, result)); } } else { dataToPopulate.addSection(parseSectionJSON(resultArray, result)); } } dataToPopulate.setRecognized(true); } //TODO check here if (!dataToPopulate.hasSections()) { if (dataToPopulate.getUrl() == null || dataToPopulate.getUrl().length() == 0) { throw new JSONException("url not found"); } if (dataToPopulate.getTitle() == null || dataToPopulate.getTitle().length() == 0) { System.out.println(dataToPopulate.getTitle()); throw new JSONException("title not found"); } } else { // If we have a section with a single object, set title to the item's title // This is to avoid bug KOOABA-20 LinkedList<SearchResultSection> sections = dataToPopulate.getSections(); if (sections.size() == 1) { LinkedList<SearchResultItem> items = sections.getFirst().getItems(); if (items.size() == 1) { dataToPopulate.setTitle(items.getFirst().getTitle()); } } } return dataToPopulate; }