List of usage examples for java.io FileReader FileReader
public FileReader(FileDescriptor fd)
From source file:TwitterClustering.java
public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here File outFile = new File(args[3]); Scanner s = new Scanner(new File(args[1])).useDelimiter(","); JSONParser parser = new JSONParser(); Set<Cluster> clusterSet = new HashSet<Cluster>(); HashMap<String, Tweet> tweets = new HashMap(); FileWriter fw = new FileWriter(outFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); // init//from w ww . jav a 2s.co m try { Object obj = parser.parse(new FileReader(args[2])); JSONArray jsonArray = (JSONArray) obj; for (int i = 0; i < jsonArray.size(); i++) { Tweet twt = new Tweet(); JSONObject jObj = (JSONObject) jsonArray.get(i); String text = jObj.get("text").toString(); long sum = 0; for (int y = 0; y < text.toCharArray().length; y++) { sum += (int) text.toCharArray()[y]; } String[] token = text.split(" "); String tID = jObj.get("id").toString(); Set<String> mySet = new HashSet<String>(Arrays.asList(token)); twt.setAttributeValue(sum); twt.setText(mySet); twt.setTweetID(tID); tweets.put(tID, twt); } // preparing initial clusters int i = 0; while (s.hasNext()) { String id = s.next();// id Tweet t = tweets.get(id.trim()); clusterSet.add(new Cluster(i + 1, t, new LinkedList())); i++; } Iterator it = tweets.entrySet().iterator(); for (int l = 0; l < 2; l++) { // limit to 25 iterations while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); // calculate distance to each centroid Tweet p = (Tweet) me.getValue(); HashMap<Cluster, Float> distMap = new HashMap(); for (Cluster clust : clusterSet) { distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText())); } HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap); sorted.keySet().iterator().next().getMembers().add(p); } // calculate new centroid and update Clusterset for (Cluster clust : clusterSet) { TreeMap<String, Long> tDistMap = new TreeMap(); Tweet newCentroid = null; Long avgSumDist = new Long(0); for (int j = 0; j < clust.getMembers().size(); j++) { avgSumDist += clust.getMembers().get(j).getAttributeValue(); tDistMap.put(clust.getMembers().get(j).getTweetID(), clust.getMembers().get(j).getAttributeValue()); } if (clust.getMembers().size() != 0) { avgSumDist /= (clust.getMembers().size()); } ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values()); if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) { // found closest newCentroid = tweets .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist))); clust.setCentroid(newCentroid); } } } // create an iterator Iterator iterator = clusterSet.iterator(); // check values while (iterator.hasNext()) { Cluster c = (Cluster) iterator.next(); bw.write(c.getId() + "\t"); System.out.print(c.getId() + "\t"); for (Tweet t : c.getMembers()) { bw.write(t.getTweetID() + ", "); System.out.print(t.getTweetID() + ","); } bw.write("\n"); System.out.println(""); } System.out.println(""); System.out.println("SSE " + sumSquaredErrror(clusterSet)); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); fw.close(); } }
From source file:org.ipinfodb.IpInfoDbClient.java
public static void main(String[] args) throws IOException { if (args.length < 3 || args.length > 4) { System.out.println("Usage: org.ipinfodb.IpInfoDbClient MODE API_KEY [IP_ADDRESS]\n" + "MODE can be either 'ip-country' or 'ip-city'.\n" + "If you don't have an API_KEY yet, you can get one for free by registering at http://www.ipinfodb.com/register.php."); return;/*from w w w .ja v a 2 s . com*/ } //Code for Reading the multiple ip addresses from a given txt file. File inputLogFilePath = new File(args[1]); FileReader fr = new FileReader(inputLogFilePath); BufferedReader br = new BufferedReader(fr); String logLine; /*File outputFile=new File("C:/Users/Intelligrape/Desktop/New_Sample_29042014.txt"); // if file doesnt exists, then create it if (!outputFile.exists()) { outputFile.createNewFile(); } FileWriter fw = new FileWriter(outputFile,true); BufferedWriter bw = new BufferedWriter(fw); bw.write("S.no, IPAddress, Country, Region, City, Zipcode"); bw.newLine();*/ try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver found"); } catch (ClassNotFoundException e) { System.out.println("Driver not found: " + e); } String url_db = "jdbc:mysql://mysqldb.c7zitrf2gguq.us-east-1.rds.amazonaws.com/matse?user=shagun&password=shagun001"; Connection con = null; int insertCounter = 0; int count = 1; while ((logLine = br.readLine()) != null) { String mode = args[2]; String apiKey = args[3]; String url = "http://api.ipinfodb.com/v3/" + mode + "/?format=json&key=" + apiKey; String[] split = logLine.split(","); String ip = split[3]; url += "&ip=" + ip; try { HttpGet request = new HttpGet(url); HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("IpInfoDb response is " + response.getStatusLine()); } String responseBody = EntityUtils.toString(response.getEntity()); IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class); if ("OK".equals(ipCityResponse.getStatusCode())) { //System.out.print(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode+ ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone); //bw.write(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode + ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone); try { con = DriverManager.getConnection(url_db); //System.out.println("Connected successfully"); Statement stmt = con.createStatement(); //System.out.println(logLine); //System.out.println(split.length); int result = stmt.executeUpdate("INSERT INTO LOGDATA1 VALUES('" + split[0] + "','" + split[1].trim() + "','" + split[2] + "','" + split[3] + "','" + split[4] + "','" + ipCityResponse.statusCode + "','" + ipCityResponse.countryCode + "','" + ipCityResponse.countryName + "','" + ipCityResponse.regionName + "','" + ipCityResponse.cityName + "','" + ipCityResponse.zipCode + "','" + ipCityResponse.latitude + "','" + ipCityResponse.longitude + "','" + ipCityResponse.timeZone + "')"); ++insertCounter; con.close(); System.out.println(insertCounter); } catch (SQLException e) { System.out.println("something wrong in the connection string: " + e); } } else { System.out.print("API status message is '" + ipCityResponse.getStatusMessage() + "'"); } } finally { //HTTP_CLIENT.getConnectionManager().shutdown(); } ++count; } HTTP_CLIENT.getConnectionManager().shutdown(); }
From source file:com.xiangzhurui.util.email.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;//from w ww . j a v a2 s . c o m FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:ca.uwaterloo.cpami.mahout.matrix.utils.GramSchmidt.java
public static void main(String[] args) throws IOException { //final Configuration conf = new Configuration(); //final FileSystem fs = FileSystem.get(conf); //final SequenceFile.Reader reader = new SequenceFile.Reader(fs, // new Path("R1.dat"), conf); //IntWritable key = new IntWritable(); //VectorWritable vec = new VectorWritable(); Matrix mat = new SparseMatrix(1500, 100); //SparseRealMatrix mat2 = new OpenMapRealMatrix(12419,1500 ); BufferedReader reader = new BufferedReader(new FileReader("R.3.csv")); String line = null;/*from w w w.j a va2 s . c o m*/ while ((line = reader.readLine()) != null) { String[] parts = line.split(","); mat.set(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Double.parseDouble(parts[2])); /* Vector v = vec.get(); int i=0; Iterator<Vector.Element> itr = v.iterateNonZero(); while(itr.hasNext()){ double elem = itr.next().get(); if(elem !=0) mat2.setEntry(i, key.get(), elem); i++; } */ } //mat = mat.transpose(); System.out.println(mat.viewColumn(0).isDense()); System.out.println(mat.viewRow(0).isDense()); mat = mat.transpose(); GramSchmidt.orthonormalizeColumns(mat); /* System.out.println("started QR"); System.out.println(Runtime.getRuntime().maxMemory()); System.out.println(Runtime.getRuntime().maxMemory()-Runtime.getRuntime().freeMemory()); QRDecomposition qr = new QRDecomposition(mat2); System.out.println(qr.getQ().getColumnDimension()); System.out.println(qr.getQ().getRowDimension()); */ //mat = mat.transpose(); //storeSparseColumns(mat); //for (int i = 0; i < 10; i++) { // System.out.println(mat.viewRow(i).getNumNondefaultElements()); //} }
From source file:net.fenyo.gnetwatch.Documentation.java
/** * General entry point.//from www .j a va 2 s .c om * @param args command line arguments. * @return void. * @throws IOException io exception. */ public static void main(String[] args) throws IOException, TransformerConfigurationException, TransformerException, FileNotFoundException, FOPException { final String docbook_stylesheets_path = args[0]; // Get configuration properties. final Config config = new Config(); // Read general logging rules. GenericTools.initLogEngine(config); log.info(config.getString("log_engine_initialized")); log.info(config.getString("begin")); Transformer docbookTransformerHTML = TransformerFactory.newInstance() .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/html/docbook.xsl"))); // docbookTransformerHTML.setParameter("draft.mode", "no"); docbookTransformerHTML.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))), new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.html")))); Transformer docbookTransformerFO = TransformerFactory.newInstance() .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/fo/docbook.xsl"))); // docbookTransformerFO.setParameter("draft.mode", "no"); docbookTransformerFO.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))), new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.fo")))); // for very old FOP version (0.20): // Driver driver = new Driver(); // driver.setRenderer(Driver.RENDER_PDF); // driver.setInputSource(new InputSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo")))); // driver.setOutputStream(new FileOutputStream(new File("c:/temp/gnetwatch-documentation.pdf"))); // driver.run(); // with new FOP version: OutputStream outStream = new BufferedOutputStream( new FileOutputStream("c:/temp/gnetwatch-documentation.pdf")); final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); Source source = new StreamSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo"))); Result result = new SAXResult(fop.getDefaultHandler()); transformer.transform(source, result); outStream.close(); }
From source file:DIA_Umpire_Quant.DIA_Umpire_ExtLibSearch.java
/** * @param args the command line arguments *///from ww w . jav a 2 s . co m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using external library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_ExtLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_extlibsearch.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String ExternalLibPath = ""; String ExternalLibDecoyTag = "DECOY"; float ExtProbThreshold = 0.99f; float RTWindow_Ext = -1f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "ExternalLibPath": { ExternalLibPath = value; break; } case "ExtProbThreshold": { ExtProbThreshold = Float.parseFloat(value); break; } case "RTWindow_Ext": { RTWindow_Ext = Float.parseFloat(value); break; } case "ExternalLibDecoyTag": { ExternalLibDecoyTag = value; if (ExternalLibDecoyTag.endsWith("_")) { ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0, ExternalLibDecoyTag.length() - 1); } break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library"> //External library search Logger.getRootLogger().info("Targeted extraction using external library"); //Read exteranl library FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, FilenameUtils.getBaseName(ExternalLibPath)); if (ExlibManager == null) { ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath)); //Import traML file ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag); //Check if there are decoy spectra ExlibManager.CheckDecoys(); //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath); ExlibManager.WriteFragmentLibSerialization(WorkFolder); } Logger.getRootLogger() .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size()); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } //Generate RT mapping RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager, diafile.GetParameter()); RTmap.GenerateModel(); RTmap.GenerateMappedPepIon(); diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.GenerateMassCalibrationRTMap(); //Perform targeted re-extraction diafile.TargetedExtractionQuant(false, ExlibManager, ExtProbThreshold, RTWindow_Ext); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); //Remove target IDs below the defined probability threshold diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold); diafile.ExportID(); diafile.ClearStructure(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); }
From source file:gentracklets.Propagate.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();/*from w w w.j a v a 2 s.c o m*/ DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 4.0; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); // propagator.addForceModel(srp); // propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(1); startDates.setElementAt(new AbsoluteDate(2016, 1, 26, 20, 00, 00, utc), 0); // set the step size [s] and total length double tstep = 100; double ld = 3; double ls = FastMath.floor(ld * (24 * 60 * 60) / tstep); System.out.println(ls); SpacecraftState currentStateKep = kepler.propagate(startDates.get(0)); SpacecraftState currentStatePer = propagator.propagate(startDates.get(0)); for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // with formatted output File file1 = new File("/home/zittersteijn/Documents/propagate/keplerian/MEO/" + app); File file2 = new File("/home/zittersteijn/Documents/propagate/perturbed/MEO/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < (int) ls; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); currentStateKep = kepler.propagate(propDate); currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the orbit to seperate files with the RA, DEC, epoch and fence given AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double sig0 = 1.0 / 3600.0 / 180.0 * FastMath.PI; double dRA = radecKep[0] - radecPer[0] / (sig0 * sig0); double dDEC = radecKep[2] - radecPer[2] / (sig0 * sig0); System.out.println(dRA + "\t" + dDEC); } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:RemoveHTMLReader.java
/** The test program: read a text file, strip HTML, print to console */ public static void main(String[] args) { try {/* ww w. j av a2s .c om*/ if (args.length != 1) throw new IllegalArgumentException("Wrong number of args"); // Create a stream to read from the file and strip tags from it BufferedReader in = new BufferedReader(new RemoveHTMLReader(new FileReader(args[0]))); // Read line by line, printing lines to the console String line; while ((line = in.readLine()) != null) System.out.println(line); in.close(); // Close the stream. } catch (Exception e) { System.err.println(e); System.err.println("Usage: java RemoveHTMLReader$Test" + " <filename>"); } }
From source file:gentracklets.GenTracklets.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();//w w w .jav a2 s .c o m DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 0.4; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); propagator.addForceModel(srp); propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(3); startDates.setElementAt(new AbsoluteDate(2015, 12, 8, 20, 00, 00, utc), 0); startDates.setElementAt(new AbsoluteDate(2015, 12, 9, 21, 00, 00, utc), 1); startDates.setElementAt(new AbsoluteDate(2015, 12, 10, 22, 00, 00, utc), 2); double tstep = 30; int l = 7; for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = "S_" + tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // FileWriter trackletsOutKep = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1h/AMR040/" + app); // FileWriter trackletsOutPer = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1h/AMR040/" + app); // BufferedWriter trackletsKepBW = new BufferedWriter(trackletsOutKep); // BufferedWriter trackletsPerBW = new BufferedWriter(trackletsOutPer); // with formatted output File file1 = new File( "/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1d/AMR040/" + app); File file2 = new File( "/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1d/AMR040/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < l; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); SpacecraftState currentStateKep = kepler.propagate(propDate); SpacecraftState currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the tracklets to seperate files with the RA, DEC, epoch and fence given // System.out.println(tles.get(kk).getSatelliteNumber() + "\t" + radec[0] / (2 * FastMath.PI) * 180 + "\t" + currentState.getDate()); AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:DruidThroughput.java
@SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { final int numQueries = QUERIES.length; final Random random = new Random(RANDOM_SEED); final AtomicInteger counter = new AtomicInteger(0); final AtomicLong totalResponseTime = new AtomicLong(0L); final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS); for (int i = 0; i < NUM_CLIENTS; i++) { executorService.submit(new Runnable() { @Override/* w ww .j a v a2 s . c o m*/ public void run() { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty"); post.addHeader("content-type", "application/json"); CloseableHttpResponse res; while (true) { try (BufferedReader reader = new BufferedReader(new FileReader( QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) { int length = reader.read(BUFFER); post.setEntity(new StringEntity(new String(BUFFER, 0, length))); } long start = System.currentTimeMillis(); res = client.execute(post); res.close(); counter.getAndIncrement(); totalResponseTime.getAndAdd(System.currentTimeMillis() - start); } } catch (IOException e) { e.printStackTrace(); } } }); } long startTime = System.currentTimeMillis(); while (true) { Thread.sleep(REPORT_INTERVAL_MILLIS); double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND; int count = counter.get(); double avgResponseTime = ((double) totalResponseTime.get()) / count; System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms"); } }