List of usage examples for java.io BufferedReader ready
public boolean ready() throws IOException
From source file:org.apache.streams.twitter.test.TweetSerDeTest.java
@Test public void Tests() { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.TRUE); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE); InputStream is = TweetSerDeTest.class.getResourceAsStream("/testtweets.txt"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int tweetlinks = 0; int retweetlinks = 0; try {// w ww.ja v a 2s . c o m while (br.ready()) { String line = br.readLine(); if (!StringUtils.isEmpty(line)) { LOGGER.info("raw: {}", line); Class detected = TwitterEventClassifier.detectClass(line); ObjectNode event = (ObjectNode) mapper.readTree(line); assertThat(event, is(not(nullValue()))); if (detected == Tweet.class) { Tweet tweet = mapper.convertValue(event, Tweet.class); assertThat(tweet, is(not(nullValue()))); assertThat(tweet.getCreatedAt(), is(not(nullValue()))); assertThat(tweet.getText(), is(not(nullValue()))); assertThat(tweet.getUser(), is(not(nullValue()))); tweetlinks += Optional.fromNullable(tweet.getEntities().getUrls().size()).or(0); } else if (detected == Retweet.class) { Retweet retweet = mapper.convertValue(event, Retweet.class); assertThat(retweet.getRetweetedStatus(), is(not(nullValue()))); assertThat(retweet.getRetweetedStatus().getCreatedAt(), is(not(nullValue()))); assertThat(retweet.getRetweetedStatus().getText(), is(not(nullValue()))); assertThat(retweet.getRetweetedStatus().getUser(), is(not(nullValue()))); assertThat(retweet.getRetweetedStatus().getUser().getId(), is(not(nullValue()))); assertThat(retweet.getRetweetedStatus().getUser().getCreatedAt(), is(not(nullValue()))); retweetlinks += Optional .fromNullable(retweet.getRetweetedStatus().getEntities().getUrls().size()).or(0); } else if (detected == Delete.class) { Delete delete = mapper.convertValue(event, Delete.class); assertThat(delete.getDelete(), is(not(nullValue()))); assertThat(delete.getDelete().getStatus(), is(not(nullValue()))); assertThat(delete.getDelete().getStatus().getId(), is(not(nullValue()))); assertThat(delete.getDelete().getStatus().getUserId(), is(not(nullValue()))); } else { Assert.fail(); } } } } catch (Exception e) { System.out.println(e); e.printStackTrace(); Assert.fail(); } assertThat(tweetlinks, is(greaterThan(0))); assertThat(retweetlinks, is(greaterThan(0))); }
From source file:com.nlworks.wowapi.util.ConnectionManager.java
public String sendRequest(String url, long lastModified, String publicKey, String privateKey) { String ret = null;//from w w w .j a v a2 s .c om System.out.println("URL to send: " + url); if (publicKey != null && publicKey.length() > 0 && privateKey != null && privateKey.length() > 0) { // generateSignature(St) // TODO private key signing of requests // String stringToSign = urlConnection.getRequestMethod() + "\n" + dateStr + "\n" + UrlPath + "\n"; // String sig = generateHmacSHA1Signature(stringToSign, privateKey); // try { // urlConnection.setRequestProperty("Authorization", "BNET" + " " + publicKey + ":" + sig); // urlConnection.setRequestProperty("Date", dateStr); // if (lastModified != 0) // urlConnection.setIfModifiedSince(lastModified); // } catch (IllegalStateException e) { // e.printStackTrace(); // } } HttpGet httpGet = new HttpGet(url); if (lastModified > 0) { httpGet.addHeader(new BasicHeader("If-Modified-Since", Long.toString(lastModified))); } try { HttpResponse response = httpClient.execute(httpGet); System.out.println("Resp Status: " + response.getStatusLine()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(1024); while (reader.ready()) { sb.append(reader.readLine()).append('\n'); } ret = sb.toString(); System.out.println("Resp Data: " + ret); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:org.talend.dataprofiler.core.migration.impl.ModelIndicatorTdColumnToModelElementTask.java
/** * //from w w w.j a v a 2 s . com * DOC mzhao string replacement method. * * @param srcFile * @return */ private void replace(File srcFile) throws Throwable { File destFile = new File(srcFile.getAbsolutePath() + MIGRATION_FILE_EXT); BufferedReader fileReader = new BufferedReader(new FileReader(srcFile)); BufferedWriter fileWriter = new BufferedWriter(new FileWriter(destFile)); while (fileReader.ready()) { String line = fileReader.readLine(); if (StringUtils.contains(line, TO_BE_RPLACED_STRING_PREFIX) && !StringUtils.contains(line, REPLACED_STRING)) { line = StringUtils.replace(line, TO_BE_RPLACED_STRING_PREFIX, TO_BE_RPLACED_STRING_PREFIX + REPLACED_STRING); log.debug(line); } fileWriter.append(line); fileWriter.newLine(); } fileWriter.flush(); fileWriter.close(); fileWriter = null; fileReader.close(); fileReader = null; }
From source file:org.londonsburning.proxy.ProxyPrinter.java
/** * @param cardName Name of Card/*w w w .j av a 2s.c om*/ * @return String Url * @throws URISyntaxException Exception * @throws IOException Exception * @throws InterruptedException Exception */ private String getURL(final String cardName) throws URISyntaxException, IOException, InterruptedException { URI uri = new URI("http", "magiccards.info", "/query", "q=!" + cardName, null); String request = uri.toString(); URL url = new URL(request); InputStream inputStream = url.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); Thread.sleep(1000); while (bufferedReader.ready()) { String lineHtml = bufferedReader.readLine(); Thread.sleep(1); if (lineHtml.contains("http://magiccards.info/scans/en") && lineHtml.contains("jpg")) { return lineHtml.substring(lineHtml.indexOf("http"), lineHtml.indexOf("jpg") + ".jpg".length() - 1); } } String tokenUrl = parseTokens(cardName); if (tokenUrl.isEmpty()) { return proxyBackUrl; } else { return tokenUrl; } }
From source file:TextPrinterExample.java
/** * Read in the file and return its contents * @param fileName/*w w w . j a v a2s .co m*/ * @return * @throws FileNotFoundException * @throws IOException */ private String getFileContents(String fileName) throws FileNotFoundException, IOException { StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { // Read in the file reader = new BufferedReader(new FileReader(fileName)); while (reader.ready()) { contents.append(reader.readLine()); contents.append("\n"); // Throw away LF chars, and just replace CR } } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } return contents.toString(); }
From source file:org.rhq.enterprise.server.plugins.alertSms.SmsSender.java
/** * Get a token from the secure token server if needed. Store the token * in preferences for caching purposes.// ww w .ja va 2s. c o m * @return a token if everything is ok * @throws Exception if no token can be obtained. */ private String getToken() throws Exception { String token = preferences.getSimpleValue(TOKEN, null); PropertySimple tokenTimeProp = preferences.getSimple(TOKEN_EXPIRY_TIME); Long tokenExpTime = null; if (tokenTimeProp != null) tokenExpTime = tokenTimeProp.getLongValue(); if (token == null || tokenExpTime == null || tokenExpTime < System.currentTimeMillis() + TWO_MINUTES) { String userId = preferences.getSimpleValue("login", null); String password = preferences.getSimpleValue("password", null); if (userId == null || password == null) throw new IllegalArgumentException("User name or password were missing"); Credentials credentials = new UsernamePasswordCredentials(userId, password); HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials(AuthScope.ANY, credentials); httpClient.getParams().setAuthenticationPreemptive(true); ClientExecutor clientExecutor = new ApacheHttpClientExecutor(httpClient); try { URI uri = new URI(DEVGARDEN_SECURE_TOKEN_SERVER); ClientRequestFactory fac = new ClientRequestFactory(clientExecutor, uri); ClientRequest request = fac.createRequest(DEVGARDEN_SECURE_TOKEN_SERVER); request.accept(MediaType.TEXT_PLAIN_TYPE); ClientResponse resp = request.get(String.class); // TODO check status System.out.println(resp.getStatus()); String response = (String) resp.getEntity(); BufferedReader reader = new BufferedReader(new StringReader(response)); while (reader.ready()) { String line = reader.readLine(); if (line.startsWith("token=")) { token = line.substring(6); break; } } System.out.println("Token: " + token); MultivaluedMap<String, List> headers = resp.getHeaders(); List expiresList = headers.get("Expires"); String expires = (String) expiresList.get(0); SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); Date date = df.parse(expires); if (tokenTimeProp == null) { tokenTimeProp = new PropertySimple(TOKEN_EXPIRY_TIME, date.getTime()); preferences.put(tokenTimeProp); } else tokenTimeProp.setLongValue(date.getTime()); PropertySimple tokenProp = preferences.getSimple(TOKEN); if (tokenProp == null) { tokenProp = new PropertySimple(TOKEN, token); preferences.put(tokenProp); } else { tokenProp.setStringValue(token); } ConfigurationManagerLocal mgr = LookupUtil.getConfigurationManager(); mgr.mergeConfiguration(preferences); } catch (Exception e) { e.printStackTrace(); // TODO: Customise this generated block throw e; } } return token; }
From source file:org.apache.streams.rss.test.RssStreamProviderIT.java
@Test public void testRssStreamProvider() throws Exception { final String configfile = "./target/test-classes/RssStreamProviderIT.conf"; final String outfile = "./target/test-classes/RssStreamProviderIT.stdout.txt"; InputStream is = RssStreamProviderIT.class.getResourceAsStream("/top100.txt"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); RssStreamConfiguration configuration = new RssStreamConfiguration(); List<FeedDetails> feedArray = new ArrayList<>(); try {//from www . j a va2s. c o m while (br.ready()) { String line = br.readLine(); if (!StringUtils.isEmpty(line)) { feedArray.add(new FeedDetails().withUrl(line).withPollIntervalMillis(5000L)); } } configuration.setFeeds(feedArray); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } org.junit.Assert.assertThat(configuration.getFeeds().size(), greaterThan(70)); OutputStream os = new FileOutputStream(configfile); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); // write conf ObjectNode feedsNode = mapper.convertValue(configuration, ObjectNode.class); JsonNode configNode = mapper.createObjectNode().set("rss", feedsNode); bw.write(mapper.writeValueAsString(configNode)); bw.flush(); bw.close(); File config = new File(configfile); assert (config.exists()); assert (config.canRead()); assert (config.isFile()); RssStreamProvider.main(new String[] { configfile, outfile }); File out = new File(outfile); assert (out.exists()); assert (out.canRead()); assert (out.isFile()); FileReader outReader = new FileReader(out); LineNumberReader outCounter = new LineNumberReader(outReader); while (outCounter.readLine() != null) { } assert (outCounter.getLineNumber() >= 200); }
From source file:org.agnitas.service.impl.UserActivityLogServiceImpl.java
private int[] processFile(UserActivityLogForm aForm, int rownums, List<AdminEntry> admins, DateFormat df, Date today, Date fromDate, Date toDate, File currentDayLogFile, int offset, List<Map> result, int rowCount, int totalRows, File currentFile) throws ParseException, IOException { List<Map> intermediateResult = new ArrayList<Map>(); String currentDateString = currentFile.getName().substring(currentDayLogFile.getName().length()); Date currentFileDate = null;/*from w w w . j a v a 2 s. c o m*/ if (!StringUtils.isEmpty(currentDateString)) { currentFileDate = df.parse(currentDateString.substring(1)); } if ((currentFileDate == null && (today.equals(fromDate) || today.equals(toDate))) || (currentFileDate != null && ((currentFileDate.after(fromDate) && currentFileDate.before(toDate) || currentFileDate.equals(fromDate) || currentFileDate.equals(toDate))))) { AgnUtils.logger().info("Starting to process log file " + currentFile.getName()); final InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(currentFile)); final BufferedReader in = new BufferedReader(inputStreamReader); while (in.ready()) { final String line = in.readLine(); if (line == null) { break; } try { String[] row = new CsvTokenizer(line, " ", "").toArray(); AgnUtils.logger().info("Successfully parsed log record: '" + line); putLogIntoList(intermediateResult, row, 0); } catch (Exception e) { AgnUtils.logger().error("Failed to parse log record: '" + line); AgnUtils.logger().error("Structure log file error", e); } } } else { AgnUtils.logger().info("Skipping log file " + currentFile.getName()); } if (!intermediateResult.isEmpty()) { for (Map map : intermediateResult) { boolean firstCondition = (StringUtils.isEmpty(aForm.getUsername()) || aForm.getUsername().equals("0")) && checkUsernameByCompanyId(map.get("username") + ":", admins); boolean secondCondition = aForm.getUsername() != null && aForm.getUsername().equals(map.get("username")); if (firstCondition || secondCondition) { if (aForm.getUserActivityLogAction() == UserActivityLogActions.ANY.getIntValue() || actionMachesRequest(map, aForm) || notLoginOrLogout(map, aForm) || loginOrLogout(map, aForm)) { if (rownums > result.size()) { if (rowCount >= offset) { result.add(map); } rowCount++; } totalRows++; } } } } return new int[] { rowCount, totalRows }; }
From source file:org.n52.ifgicopter.spf.xml.PluginXMLTools.java
public static Plugin parsePlugin(InputStream is) throws Exception { /*/* ww w. j a v a 2s . c o m*/ * the final result get init */ Plugin result = new Plugin(); List<String> outputProperties = new ArrayList<String>(); List<String> mandatoryProperties = new ArrayList<String>(); List<String> inputProperties = new ArrayList<String>(); Map<String, Item> items = new HashMap<String, Item>(); StringBuilder sb = new StringBuilder(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.ready()) { sb.append(br.readLine()); } PluginDocument doc = null; try { doc = PluginDocument.Factory.parse(sb.toString()); } catch (XmlException e) { throw e; } /* * do we validate? */ if (java.lang.Boolean .parseBoolean(SPFRegistry.getInstance().getConfigProperty(SPFRegistry.VALIDATE_XML_PROP))) { XmlOptions opts = new XmlOptions(); List<XmlError> errors = new ArrayList<XmlError>(); opts.setErrorListener(errors); if (!doc.validate(opts)) { throw new Exception("Document is not a valid plugin description. Please recheck: " + errors); } } PluginType plugin = doc.getPlugin(); String name = plugin.getName().trim(); /* * * PARSE the SensorML * */ SensorML sensorML = plugin.getSensorML(); PluginMetadata metadata = new PluginMetadata(); metadata.setName(name); /* * do schematron XSLT transformations */ SchematronValidator schematron = new SchematronValidator(sb); if (!schematron.validate()) { throw new Exception( "The plugin description file is not a valid SPF-schematron SensorML profile instance: " + schematron.getAssertFails()); } /* * get the input items */ boolean mobile = true; Location location = null; Time time = null; AbstractProcessType process = sensorML.getMemberArray(0).getProcess(); if (process instanceof SystemType) { /* * parse the system */ SystemType system = (SystemType) process; /* * parse contact and identification */ Contact[] cont = system.getContactArray(); if (cont.length > 0) { if (cont[0].isSetResponsibleParty() && cont[0].getResponsibleParty().isSetContactInfo() && cont[0].getResponsibleParty().getContactInfo().isSetAddress() && cont[0] .getResponsibleParty().getContactInfo().getAddress().isSetElectronicMailAddress()) { metadata.setContactEmail(cont[0].getResponsibleParty().getContactInfo().getAddress() .getElectronicMailAddress().trim()); } } Identification[] ident = system.getIdentificationArray(); if (ident.length > 0) { if (ident[0].isSetIdentifierList()) { for (int j = 0; j < ident[0].getIdentifierList().getIdentifierArray().length; j++) { if (ident[0].getIdentifierList().getIdentifierArray()[j].isSetName() && ident[0].getIdentifierList().getIdentifierArray()[j].getName() .equals("uniqueID")) { metadata.setUniqueID(ident[0].getIdentifierList().getIdentifierArray()[j].getTerm() .getValue().trim()); } } } } /* * check if we have a mobile or a stationary platform */ if (system.isSetBoundedBy()) { /* * this indicates a mobile sensor * -> a swe:Position should be available * in the sml:inputs */ BoundingShapeType boundedBy = system.getBoundedBy(); if (boundedBy.isSetEnvelope()) { EnvelopeType envelope = boundedBy.getEnvelope(); if ((envelope.isSetLowerCorner() && envelope.isSetUpperCorner()) || envelope.getPosArray().length == 2) { /* * valid envelope defintion */ mobile = true; metadata.setMobile(true); metadata.setPosition(envelope.getLowerCorner().getStringValue().trim()); } } } else if (system.isSetPosition()) { /* * if we have a static platform use the sml:location element * -> stationary */ location = new Location("staticPosition"); Position position = system.getPosition(); VectorPropertyType loc = position.getPosition().getLocation(); if (loc.isSetVector()) { VectorType vector = loc.getVector(); location.setReferenceFrame(position.getPosition().getReferenceFrame()); /* * get the axis order dependent on * the CRS. * the coordinate array will then be treated * according to this axis order. */ String[] axisOrder = getAxisOrder(location.getReferenceFrame()); int axis = 0; for (Coordinate coord : vector.getCoordinateArray()) { if (coord.isSetQuantity()) { location.setAxis(axisOrder[axis], coord.getQuantity().getValue()); } else if (coord.isSetCount()) { location.setAxis(axisOrder[axis], coord.getCount().getValue().doubleValue()); } location.setDimension(++axis); } mobile = false; metadata.setPosition(location.getX() + " " + location.getY()); metadata.setMobile(false); } } InputList inputs = system.getInputs().getInputList(); if (inputs != null) { for (IoComponentPropertyType input : inputs.getInputArray()) { /* * parse the time */ if (input.isSetTime()) { TimeDocument.Time prop = input.getTime(); time = new Time(input.getName()); time.setDefinition(SWECommonParser.getTimeDefinition(prop)); time.setReferenceFrame(prop.getReferenceFrame()); items.put(time.getProperty(), time); } else if (input.isSetAbstractDataRecord()) { AbstractDataRecordType prop = input.getAbstractDataRecord(); /* * is this the position? */ if (prop instanceof PositionType) { PositionType pos = (PositionType) prop; pos.getReferenceFrame(); /* * use a temporary object because perhaps * we have a stationary platform defined * and are not allowed to overwrite the * field "location" */ Location tmp = new Location(input.getName()); /* * use the reference frame attribute */ tmp.setReferenceFrame(pos.getReferenceFrame()); items.put(tmp.getProperty(), tmp); VectorPropertyType loc = pos.getLocation(); Coordinate[] coords = loc.getVector().getCoordinateArray(); /* * go through all coordinates * treat axis ordering according to their order */ for (int i = 0; i < coords.length; i++) { if (i == 0) { /* * first axis */ Item first = new Item(coords[i].getName()); tmp.addCompoundedItem(first); tmp.setFirstCoordinateName(first.getProperty()); if (coords[i].isSetQuantity() || coords[i].isSetCount()) { first.setDataType(Double.class); if (coords[i].isSetQuantity()) { Quantity quan = coords[i].getQuantity(); if (quan.isSetUom()) { first.setUom(quan.getUom().getCode()); } } } else { first.setDataType(String.class); } } else if (i == 1) { /* * second axis */ Item second = new Item(coords[i].getName()); tmp.addCompoundedItem(second); tmp.setSecondCoordinateName(second.getProperty()); if (coords[i].isSetQuantity() || coords[i].isSetCount()) { second.setDataType(Double.class); if (coords[i].isSetQuantity()) { Quantity quan = coords[i].getQuantity(); if (quan.isSetUom()) { second.setUom(quan.getUom().getCode()); } } } else { second.setDataType(String.class); } } else { /* * third axis */ Item third = new Item(coords[i].getName()); tmp.addCompoundedItem(third); tmp.setAltitudeName(third.getProperty()); if (coords[i].isSetQuantity() || coords[i].isSetCount()) { third.setDataType(Double.class); if (coords[i].isSetQuantity()) { Quantity quan = coords[i].getQuantity(); if (quan.isSetUom()) { third.setUom(quan.getUom().getCode()); } } } else { third.setDataType(String.class); } } } if (!mobile) { log.warn( "The SensorML indicated a stationary platform (sml:position was specified). The input " + "property '" + input.getName() + "' will not be treated as the dynamic position " + "of the platform but as a normal input property."); } else { /* * we are allowed to use this object * as location because the platform * is defined mobile */ location = tmp; } } else { //TODO: do other data records } } /* * parse other values, probably phenomenons */ else if (input.isSetQuantity() || input.isSetCount()) { /* * real numbers */ Item item = new Item(input.getName()); item.setDataType(Double.class); if (input.isSetQuantity()) { Quantity quan = input.getQuantity(); if (quan.isSetUom()) { item.setUom(quan.getUom().getCode()); } if (quan.isSetDefinition()) { item.setDefinition(quan.getDefinition()); } } items.put(item.getProperty(), item); } if (input.isSetText() || input.isSetBoolean() || input.isSetCategory()) { /* * treat this as string */ Item item = new Item(input.getName()); item.setDataType(String.class); items.put(item.getProperty(), item); } } } /* * check if a time is present, otherwise set default time property */ if (time == null) { /* * define default time property */ time = new Time(Plugin.TIME_DEFAULT_NAME); time.setReferenceFrame("urn:ogc:def:unit:iso8601"); time.setDefinition("urn:ogc:def:phenomenon:time"); items.put(time.getProperty(), time); } } /* * * PARSE the outputType * */ Output outputElem = plugin.getOutput(); AbstractBehaviourType behave = outputElem.getBehaviour(); String outputType = ""; if (behave instanceof AvailabilityBehaviourType) { outputType = Plugin.AVAILABLE_BEHAVIOUR; AvailabilityBehaviourType avail = (AvailabilityBehaviourType) behave; for (String prop : avail.getOutputProperties().getPropertyArray()) { Item item = items.get(prop); if (item instanceof CompoundItem) { addLeafProperties((CompoundItem) item, outputProperties); } else { outputProperties.add(prop); } } } else if (behave instanceof PeriodBehaviourType) { outputType = Plugin.PERIOD_BEHAVIOUR; result.setTimeDelta(((PeriodBehaviourType) behave).getTimedelta()); } /* * output if and only if all items are present */ /* * these properties are needed for a data tuple */ if (outputElem.isSetMandatoryProperties()) { //get from the mandatory list for (String prop : outputElem.getMandatoryProperties().getPropertyArray()) { Item item = items.get(prop); if (item instanceof CompoundItem) { addLeafProperties((CompoundItem) item, mandatoryProperties); } else { mandatoryProperties.add(prop); } } } else if (outputElem.isSetOutputOnAllItems()) { // all items are needed for (Item item : items.values()) { if (item instanceof CompoundItem) { addLeafProperties((CompoundItem) item, mandatoryProperties); } else if (item instanceof Time) { //do not add this as the time property is the key //for maps and hence not hold separatly } else { mandatoryProperties.add(item.getProperty()); } } } else if (outputElem.isSetSingleOutputAllowed()) { /* * nothing. leave mandatoryProperties empty */ } /* * finally save all leaf properties (a CompoundField never comes in as a * property of its name. get its leafs as the input properties -> * SimpleFields) */ for (Item item : items.values()) { if (item instanceof CompoundItem) { addLeafProperties((CompoundItem) item, inputProperties); } else { inputProperties.add(item.getProperty()); } } result.setLocation(location); result.setTime(time); result.setMobile(mobile); result.setMetadata(metadata); result.setName(name); result.setSensorML(sensorML); result.setInputProperties(inputProperties); result.setOutputProperties(outputProperties); result.setMandatoryProperties(mandatoryProperties); result.setItems(items); result.setOutputType(outputType); return result; }
From source file:edu.uci.ics.jung.io.BipartiteGraphReader.java
/** * <p>Creates a <code>KPartiteGraph</code> (where k = 2) based on connection * data gathered from a Reader. // ww w . j a v a2s . co m * The data must be in one of the two following formats:</p> * * <pre> * a_1 b_1 * a_2 b_1 * a_2 b_2 * a_3 b_3 ... * </pre> * * <p>or</p> * * <pre> * a_1 b_1 b_2 b_3 * a_2 b_2 b_3 * a_3 b_3 ... * </pre> * * <p> * where <code>x_i</code> is a unique label (ID) for vertex <code>i</code> * in partition <code>x</code>. Each line in the file defines an edge * between the specified vertices. The vertices themselves are defined * implicitly: if a label is read from the file for which no vertex yet * exists, a new vertex is created and that label is attached to it. * </p> * * <p>The first format is the default; the second is assumed if the * <code>asList</code> flag is set to <code>true</code>. In * the default format, everything after the first whitespace is * interpreted as part of the label for the second vertex.</p> * * <p> * Vertex labels are only required to be unique within their * partitions. Each partition has its own <code>StringLabeller</code>, * which is accessed via the key <code>VID_A</code> or <code>VID_B</code>, * as appropriate. * </p> * * <p> * The end of the file may be artificially set by putting the string <code>end_of_file</code> * on a line by itself. * </p> * * * * @return the 2-partite graph loaded with these vertices, and labelled with two StringLabellers * @throws * IOException May occur in the course of reading from a stream. */ public KPartiteGraph load(Reader reader) throws IOException { List predicates = new LinkedList(); predicates.add(PART_A); predicates.add(PART_B); KPartiteGraph bg = new KPartiteSparseGraph(predicates, true); Collection edge_constraints = bg.getEdgeConstraints(); if (directed) edge_constraints.add(Graph.DIRECTED_EDGE); else edge_constraints.add(Graph.UNDIRECTED_EDGE); if (!parallel) edge_constraints.add(Graph.NOT_PARALLEL_EDGE); VertexGenerator vg = new TypedVertexGenerator(edge_constraints); EdgeWeightLabeller ewl = EdgeWeightLabeller.getLabeller(bg); BufferedReader br = new BufferedReader(reader); while (br.ready()) { // read the line in, break it into 2 parts (one for each // vertex) String curLine = br.readLine(); if (curLine == null || curLine.equals("end_of_file")) break; if (curLine.trim().length() == 0) continue; String[] parts; if (asList) parts = curLine.trim().split("\\s+"); else parts = curLine.trim().split("\\s+", 2); // fetch/create vertices for each part of the string Vertex v_a = getOrCreateVertexByName(bg, vg, parts[0], PART_A); int i = 1; while (i < parts.length) { Vertex v_b = getOrCreateVertexByName(bg, vg, parts[i++], PART_B); Edge e = v_a.findEdge(v_b); boolean absent = (e == null); if (absent || parallel) { if (directed) e = bg.addEdge(new DirectedSparseEdge(v_a, v_b)); else e = bg.addEdge(new UndirectedSparseEdge(v_a, v_b)); } if (!parallel) // weight represents multiplicity of edge { if (absent) ewl.setWeight(e, 1); else ewl.setWeight(e, ewl.getWeight(e) + 1); } } } br.close(); reader.close(); return bg; }